blindsig-client-server-example/client/blindsecp256k1-browser.js
client/blindsecp256k1-browser.jsRaw
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.blindsecp256k1 = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2(function (Buffer){(function (){
3"use strict";
4Object.defineProperty(exports, "__esModule", { value: true });
5exports.verify = exports.unblind = exports.blindSign = exports.blind = exports.newRequestParameters = exports.newKeyPair = exports.newBigFromString = exports.messageToBigNumber = exports.signatureToHex = exports.signatureFromHex = exports.pointToHex = exports.pointFromHex = exports.Point = exports.BigInteger = exports.ecparams = void 0;
6const crypto_1 = require("crypto");
7const BigInteger = require("bigi");
8exports.BigInteger = BigInteger;
9const ecurve_1 = require("ecurve");
10Object.defineProperty(exports, "Point", { enumerable: true, get: function () { return ecurve_1.Point; } });
11const keccak256_1 = require("@ethersproject/keccak256");
12const ecparams = ecurve_1.getCurveByName('secp256k1');
13exports.ecparams = ecparams;
14const G = ecparams.G;
15const n = ecparams.n;
16/**
17 * Imports a Point from hex string where X and Y coordinates were encoded as 32
18 * & 32 bytes in LittleEndian.
19 */
20function pointFromHex(pointHex) {
21 const xBuff = Buffer.from(pointHex.substr(0, 64), 'hex').reverse().toString('hex');
22 const yBuff = Buffer.from(pointHex.substr(64), 'hex').reverse().toString('hex');
23 const x = BigInteger.fromHex(xBuff);
24 const y = BigInteger.fromHex(yBuff);
25 const p = ecurve_1.Point.fromAffine(ecparams, x, y);
26 return p;
27}
28exports.pointFromHex = pointFromHex;
29function pointToHex(point) {
30 const buffX = point.affineX.toBuffer(32).reverse();
31 const buffY = point.affineY.toBuffer(32).reverse();
32 return buffX.toString("hex") + buffY.toString("hex");
33}
34exports.pointToHex = pointToHex;
35function signatureFromHex(hexSignature) {
36 if (!hexSignature || hexSignature.length != 192)
37 throw new Error("Invalid hex signature (96 bytes expected)");
38 const s = BigInteger.fromBuffer(Buffer.from(hexSignature.substr(0, 64), "hex").reverse());
39 const f = pointFromHex(hexSignature.substr(64));
40 return { s, f };
41}
42exports.signatureFromHex = signatureFromHex;
43function signatureToHex(signature) {
44 if (!signature || !signature.f || !signature.s)
45 throw new Error("The signature is empty");
46 const { f, s } = signature;
47 // hex(swapEndiannes(s) ) + hex(f)
48 const flippedHexS = s.toBuffer(32).reverse().toString("hex");
49 return flippedHexS + pointToHex(f);
50}
51exports.signatureToHex = signatureToHex;
52function messageToBigNumber(message) {
53 const msg = Buffer.from(message, 'utf8');
54 return BigInteger.fromBuffer(msg);
55}
56exports.messageToBigNumber = messageToBigNumber;
57function newBigFromString(s) {
58 let a = new BigInteger(null, null, null);
59 a.fromString(s, null);
60 return a;
61}
62exports.newBigFromString = newBigFromString;
63function newKeyPair() {
64 const sk = random(32);
65 return { sk: sk, pk: G.multiply(sk) };
66}
67exports.newKeyPair = newKeyPair;
68function newRequestParameters() {
69 const k = random(32);
70 return { k: k, signerR: G.multiply(k) };
71}
72exports.newRequestParameters = newRequestParameters;
73/**
74 * Blinds the message for the signer R.
75 * @param {BigInteger} m
76 * @param {Point} signerR
77 * @returns {struct} {mBlinded: BigInteger, userSecretData: {a: BigInteger, b: BigInteger, f: Point}}
78 */
79function blind(m, signerR) {
80 const u = { a: BigInteger.ZERO, b: BigInteger.ZERO, f: G };
81 u.a = random(32);
82 u.b = random(32);
83 const aR = signerR.multiply(u.a);
84 const bG = G.multiply(u.b);
85 u.f = aR.add(bG);
86 const rx = u.f.affineX.mod(n);
87 const ainv = u.a.modInverse(n);
88 const ainvrx = ainv.multiply(rx);
89 const mHex = m.toString(16);
90 const hHex = keccak256_1.keccak256('0x' + zeroPad(mHex, 32)).substr(2);
91 const h = BigInteger.fromHex(hHex);
92 const mBlinded = ainvrx.multiply(h);
93 return { mBlinded: mBlinded.mod(n), userSecretData: u };
94}
95exports.blind = blind;
96function blindSign(sk, mBlinded, k) {
97 let sBlind = sk.multiply(mBlinded);
98 sBlind = sBlind.add(k);
99 return sBlind.mod(n);
100}
101exports.blindSign = blindSign;
102/**
103 * Unblinds the blinded signature.
104 * @param blinded signature
105 * @param userSecretData
106 * @returns unblinded signature
107 */
108function unblind(sBlind, userSecretData) {
109 const s = userSecretData.a.multiply(sBlind).add(userSecretData.b);
110 return { s: s.mod(n), f: userSecretData.f };
111}
112exports.unblind = unblind;
113function verify(m, s, q) {
114 const sG = G.multiply(s.s);
115 const mHex = m.toString(16);
116 const hHex = keccak256_1.keccak256('0x' + zeroPad(mHex, 32)).substr(2);
117 const h = BigInteger.fromHex(hHex);
118 const rx = s.f.affineX.mod(n);
119 const right = s.f.add(q.multiply(rx.multiply(h)));
120 if ((sG.affineX.toString() == right.affineX.toString())
121 && (sG.affineY.toString() == right.affineY.toString())) {
122 return true;
123 }
124 return false;
125}
126exports.verify = verify;
127// HELPERS
128function random(bytes) {
129 let k;
130 do {
131 k = BigInteger.fromByteArrayUnsigned(crypto_1.randomBytes(bytes));
132 } while (k.toString() == '0' && k.gcd(n).toString() != '1');
133 return k;
134}
135function zeroPad(hexString, byteLength) {
136 if (hexString.length > (byteLength * 2))
137 throw new Error("Out of bounds");
138 while (hexString.length < (byteLength * 2)) {
139 hexString = "0" + hexString;
140 }
141 return hexString;
142}
143
144}).call(this)}).call(this,require("buffer").Buffer)
145},{"@ethersproject/keccak256":4,"bigi":29,"buffer":77,"crypto":86,"ecurve":100}],2:[function(require,module,exports){
146"use strict";
147Object.defineProperty(exports, "__esModule", { value: true });
148exports.version = "bytes/5.0.9";
149
150},{}],3:[function(require,module,exports){
151"use strict";
152Object.defineProperty(exports, "__esModule", { value: true });
153var logger_1 = require("@ethersproject/logger");
154var _version_1 = require("./_version");
155var logger = new logger_1.Logger(_version_1.version);
156///////////////////////////////
157function isHexable(value) {
158 return !!(value.toHexString);
159}
160function addSlice(array) {
161 if (array.slice) {
162 return array;
163 }
164 array.slice = function () {
165 var args = Array.prototype.slice.call(arguments);
166 return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));
167 };
168 return array;
169}
170function isBytesLike(value) {
171 return ((isHexString(value) && !(value.length % 2)) || isBytes(value));
172}
173exports.isBytesLike = isBytesLike;
174function isBytes(value) {
175 if (value == null) {
176 return false;
177 }
178 if (value.constructor === Uint8Array) {
179 return true;
180 }
181 if (typeof (value) === "string") {
182 return false;
183 }
184 if (value.length == null) {
185 return false;
186 }
187 for (var i = 0; i < value.length; i++) {
188 var v = value[i];
189 if (typeof (v) !== "number" || v < 0 || v >= 256 || (v % 1)) {
190 return false;
191 }
192 }
193 return true;
194}
195exports.isBytes = isBytes;
196function arrayify(value, options) {
197 if (!options) {
198 options = {};
199 }
200 if (typeof (value) === "number") {
201 logger.checkSafeUint53(value, "invalid arrayify value");
202 var result = [];
203 while (value) {
204 result.unshift(value & 0xff);
205 value = parseInt(String(value / 256));
206 }
207 if (result.length === 0) {
208 result.push(0);
209 }
210 return addSlice(new Uint8Array(result));
211 }
212 if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
213 value = "0x" + value;
214 }
215 if (isHexable(value)) {
216 value = value.toHexString();
217 }
218 if (isHexString(value)) {
219 var hex = value.substring(2);
220 if (hex.length % 2) {
221 if (options.hexPad === "left") {
222 hex = "0x0" + hex.substring(2);
223 }
224 else if (options.hexPad === "right") {
225 hex += "0";
226 }
227 else {
228 logger.throwArgumentError("hex data is odd-length", "value", value);
229 }
230 }
231 var result = [];
232 for (var i = 0; i < hex.length; i += 2) {
233 result.push(parseInt(hex.substring(i, i + 2), 16));
234 }
235 return addSlice(new Uint8Array(result));
236 }
237 if (isBytes(value)) {
238 return addSlice(new Uint8Array(value));
239 }
240 return logger.throwArgumentError("invalid arrayify value", "value", value);
241}
242exports.arrayify = arrayify;
243function concat(items) {
244 var objects = items.map(function (item) { return arrayify(item); });
245 var length = objects.reduce(function (accum, item) { return (accum + item.length); }, 0);
246 var result = new Uint8Array(length);
247 objects.reduce(function (offset, object) {
248 result.set(object, offset);
249 return offset + object.length;
250 }, 0);
251 return addSlice(result);
252}
253exports.concat = concat;
254function stripZeros(value) {
255 var result = arrayify(value);
256 if (result.length === 0) {
257 return result;
258 }
259 // Find the first non-zero entry
260 var start = 0;
261 while (start < result.length && result[start] === 0) {
262 start++;
263 }
264 // If we started with zeros, strip them
265 if (start) {
266 result = result.slice(start);
267 }
268 return result;
269}
270exports.stripZeros = stripZeros;
271function zeroPad(value, length) {
272 value = arrayify(value);
273 if (value.length > length) {
274 logger.throwArgumentError("value out of range", "value", arguments[0]);
275 }
276 var result = new Uint8Array(length);
277 result.set(value, length - value.length);
278 return addSlice(result);
279}
280exports.zeroPad = zeroPad;
281function isHexString(value, length) {
282 if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
283 return false;
284 }
285 if (length && value.length !== 2 + 2 * length) {
286 return false;
287 }
288 return true;
289}
290exports.isHexString = isHexString;
291var HexCharacters = "0123456789abcdef";
292function hexlify(value, options) {
293 if (!options) {
294 options = {};
295 }
296 if (typeof (value) === "number") {
297 logger.checkSafeUint53(value, "invalid hexlify value");
298 var hex = "";
299 while (value) {
300 hex = HexCharacters[value & 0x0f] + hex;
301 value = Math.floor(value / 16);
302 }
303 if (hex.length) {
304 if (hex.length % 2) {
305 hex = "0" + hex;
306 }
307 return "0x" + hex;
308 }
309 return "0x00";
310 }
311 if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
312 value = "0x" + value;
313 }
314 if (isHexable(value)) {
315 return value.toHexString();
316 }
317 if (isHexString(value)) {
318 if (value.length % 2) {
319 if (options.hexPad === "left") {
320 value = "0x0" + value.substring(2);
321 }
322 else if (options.hexPad === "right") {
323 value += "0";
324 }
325 else {
326 logger.throwArgumentError("hex data is odd-length", "value", value);
327 }
328 }
329 return value.toLowerCase();
330 }
331 if (isBytes(value)) {
332 var result = "0x";
333 for (var i = 0; i < value.length; i++) {
334 var v = value[i];
335 result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
336 }
337 return result;
338 }
339 return logger.throwArgumentError("invalid hexlify value", "value", value);
340}
341exports.hexlify = hexlify;
342/*
343function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {
344 if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") {
345 return "0x0" + value.substring(2);
346 }
347 return value;
348}
349*/
350function hexDataLength(data) {
351 if (typeof (data) !== "string") {
352 data = hexlify(data);
353 }
354 else if (!isHexString(data) || (data.length % 2)) {
355 return null;
356 }
357 return (data.length - 2) / 2;
358}
359exports.hexDataLength = hexDataLength;
360function hexDataSlice(data, offset, endOffset) {
361 if (typeof (data) !== "string") {
362 data = hexlify(data);
363 }
364 else if (!isHexString(data) || (data.length % 2)) {
365 logger.throwArgumentError("invalid hexData", "value", data);
366 }
367 offset = 2 + 2 * offset;
368 if (endOffset != null) {
369 return "0x" + data.substring(offset, 2 + 2 * endOffset);
370 }
371 return "0x" + data.substring(offset);
372}
373exports.hexDataSlice = hexDataSlice;
374function hexConcat(items) {
375 var result = "0x";
376 items.forEach(function (item) {
377 result += hexlify(item).substring(2);
378 });
379 return result;
380}
381exports.hexConcat = hexConcat;
382function hexValue(value) {
383 var trimmed = hexStripZeros(hexlify(value, { hexPad: "left" }));
384 if (trimmed === "0x") {
385 return "0x0";
386 }
387 return trimmed;
388}
389exports.hexValue = hexValue;
390function hexStripZeros(value) {
391 if (typeof (value) !== "string") {
392 value = hexlify(value);
393 }
394 if (!isHexString(value)) {
395 logger.throwArgumentError("invalid hex string", "value", value);
396 }
397 value = value.substring(2);
398 var offset = 0;
399 while (offset < value.length && value[offset] === "0") {
400 offset++;
401 }
402 return "0x" + value.substring(offset);
403}
404exports.hexStripZeros = hexStripZeros;
405function hexZeroPad(value, length) {
406 if (typeof (value) !== "string") {
407 value = hexlify(value);
408 }
409 else if (!isHexString(value)) {
410 logger.throwArgumentError("invalid hex string", "value", value);
411 }
412 if (value.length > 2 * length + 2) {
413 logger.throwArgumentError("value out of range", "value", arguments[1]);
414 }
415 while (value.length < 2 * length + 2) {
416 value = "0x0" + value.substring(2);
417 }
418 return value;
419}
420exports.hexZeroPad = hexZeroPad;
421function splitSignature(signature) {
422 var result = {
423 r: "0x",
424 s: "0x",
425 _vs: "0x",
426 recoveryParam: 0,
427 v: 0
428 };
429 if (isBytesLike(signature)) {
430 var bytes = arrayify(signature);
431 if (bytes.length !== 65) {
432 logger.throwArgumentError("invalid signature string; must be 65 bytes", "signature", signature);
433 }
434 // Get the r, s and v
435 result.r = hexlify(bytes.slice(0, 32));
436 result.s = hexlify(bytes.slice(32, 64));
437 result.v = bytes[64];
438 // Allow a recid to be used as the v
439 if (result.v < 27) {
440 if (result.v === 0 || result.v === 1) {
441 result.v += 27;
442 }
443 else {
444 logger.throwArgumentError("signature invalid v byte", "signature", signature);
445 }
446 }
447 // Compute recoveryParam from v
448 result.recoveryParam = 1 - (result.v % 2);
449 // Compute _vs from recoveryParam and s
450 if (result.recoveryParam) {
451 bytes[32] |= 0x80;
452 }
453 result._vs = hexlify(bytes.slice(32, 64));
454 }
455 else {
456 result.r = signature.r;
457 result.s = signature.s;
458 result.v = signature.v;
459 result.recoveryParam = signature.recoveryParam;
460 result._vs = signature._vs;
461 // If the _vs is available, use it to populate missing s, v and recoveryParam
462 // and verify non-missing s, v and recoveryParam
463 if (result._vs != null) {
464 var vs_1 = zeroPad(arrayify(result._vs), 32);
465 result._vs = hexlify(vs_1);
466 // Set or check the recid
467 var recoveryParam = ((vs_1[0] >= 128) ? 1 : 0);
468 if (result.recoveryParam == null) {
469 result.recoveryParam = recoveryParam;
470 }
471 else if (result.recoveryParam !== recoveryParam) {
472 logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature);
473 }
474 // Set or check the s
475 vs_1[0] &= 0x7f;
476 var s = hexlify(vs_1);
477 if (result.s == null) {
478 result.s = s;
479 }
480 else if (result.s !== s) {
481 logger.throwArgumentError("signature v mismatch _vs", "signature", signature);
482 }
483 }
484 // Use recid and v to populate each other
485 if (result.recoveryParam == null) {
486 if (result.v == null) {
487 logger.throwArgumentError("signature missing v and recoveryParam", "signature", signature);
488 }
489 else {
490 result.recoveryParam = 1 - (result.v % 2);
491 }
492 }
493 else {
494 if (result.v == null) {
495 result.v = 27 + result.recoveryParam;
496 }
497 else if (result.recoveryParam !== (1 - (result.v % 2))) {
498 logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature);
499 }
500 }
501 if (result.r == null || !isHexString(result.r)) {
502 logger.throwArgumentError("signature missing or invalid r", "signature", signature);
503 }
504 else {
505 result.r = hexZeroPad(result.r, 32);
506 }
507 if (result.s == null || !isHexString(result.s)) {
508 logger.throwArgumentError("signature missing or invalid s", "signature", signature);
509 }
510 else {
511 result.s = hexZeroPad(result.s, 32);
512 }
513 var vs = arrayify(result.s);
514 if (vs[0] >= 128) {
515 logger.throwArgumentError("signature s out of range", "signature", signature);
516 }
517 if (result.recoveryParam) {
518 vs[0] |= 0x80;
519 }
520 var _vs = hexlify(vs);
521 if (result._vs) {
522 if (!isHexString(result._vs)) {
523 logger.throwArgumentError("signature invalid _vs", "signature", signature);
524 }
525 result._vs = hexZeroPad(result._vs, 32);
526 }
527 // Set or check the _vs
528 if (result._vs == null) {
529 result._vs = _vs;
530 }
531 else if (result._vs !== _vs) {
532 logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature);
533 }
534 }
535 return result;
536}
537exports.splitSignature = splitSignature;
538function joinSignature(signature) {
539 signature = splitSignature(signature);
540 return hexlify(concat([
541 signature.r,
542 signature.s,
543 (signature.recoveryParam ? "0x1c" : "0x1b")
544 ]));
545}
546exports.joinSignature = joinSignature;
547
548},{"./_version":2,"@ethersproject/logger":6}],4:[function(require,module,exports){
549"use strict";
550var __importDefault = (this && this.__importDefault) || function (mod) {
551 return (mod && mod.__esModule) ? mod : { "default": mod };
552};
553Object.defineProperty(exports, "__esModule", { value: true });
554var js_sha3_1 = __importDefault(require("js-sha3"));
555var bytes_1 = require("@ethersproject/bytes");
556function keccak256(data) {
557 return '0x' + js_sha3_1.default.keccak_256(bytes_1.arrayify(data));
558}
559exports.keccak256 = keccak256;
560
561},{"@ethersproject/bytes":3,"js-sha3":155}],5:[function(require,module,exports){
562"use strict";
563Object.defineProperty(exports, "__esModule", { value: true });
564exports.version = "logger/5.0.8";
565
566},{}],6:[function(require,module,exports){
567"use strict";
568Object.defineProperty(exports, "__esModule", { value: true });
569var _permanentCensorErrors = false;
570var _censorErrors = false;
571var LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 };
572var _logLevel = LogLevels["default"];
573var _version_1 = require("./_version");
574var _globalLogger = null;
575function _checkNormalize() {
576 try {
577 var missing_1 = [];
578 // Make sure all forms of normalization are supported
579 ["NFD", "NFC", "NFKD", "NFKC"].forEach(function (form) {
580 try {
581 if ("test".normalize(form) !== "test") {
582 throw new Error("bad normalize");
583 }
584 ;
585 }
586 catch (error) {
587 missing_1.push(form);
588 }
589 });
590 if (missing_1.length) {
591 throw new Error("missing " + missing_1.join(", "));
592 }
593 if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) {
594 throw new Error("broken implementation");
595 }
596 }
597 catch (error) {
598 return error.message;
599 }
600 return null;
601}
602var _normalizeError = _checkNormalize();
603var LogLevel;
604(function (LogLevel) {
605 LogLevel["DEBUG"] = "DEBUG";
606 LogLevel["INFO"] = "INFO";
607 LogLevel["WARNING"] = "WARNING";
608 LogLevel["ERROR"] = "ERROR";
609 LogLevel["OFF"] = "OFF";
610})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
611var ErrorCode;
612(function (ErrorCode) {
613 ///////////////////
614 // Generic Errors
615 // Unknown Error
616 ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
617 // Not Implemented
618 ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
619 // Unsupported Operation
620 // - operation
621 ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION";
622 // Network Error (i.e. Ethereum Network, such as an invalid chain ID)
623 // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown)
624 ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
625 // Some sort of bad response from the server
626 ErrorCode["SERVER_ERROR"] = "SERVER_ERROR";
627 // Timeout
628 ErrorCode["TIMEOUT"] = "TIMEOUT";
629 ///////////////////
630 // Operational Errors
631 // Buffer Overrun
632 ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN";
633 // Numeric Fault
634 // - operation: the operation being executed
635 // - fault: the reason this faulted
636 ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT";
637 ///////////////////
638 // Argument Errors
639 // Missing new operator to an object
640 // - name: The name of the class
641 ErrorCode["MISSING_NEW"] = "MISSING_NEW";
642 // Invalid argument (e.g. value is incompatible with type) to a function:
643 // - argument: The argument name that was invalid
644 // - value: The value of the argument
645 ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
646 // Missing argument to a function:
647 // - count: The number of arguments received
648 // - expectedCount: The number of arguments expected
649 ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT";
650 // Too many arguments
651 // - count: The number of arguments received
652 // - expectedCount: The number of arguments expected
653 ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT";
654 ///////////////////
655 // Blockchain Errors
656 // Call exception
657 // - transaction: the transaction
658 // - address?: the contract address
659 // - args?: The arguments passed into the function
660 // - method?: The Solidity method signature
661 // - errorSignature?: The EIP848 error signature
662 // - errorArgs?: The EIP848 error parameters
663 // - reason: The reason (only for EIP848 "Error(string)")
664 ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION";
665 // Insufficien funds (< value + gasLimit * gasPrice)
666 // - transaction: the transaction attempted
667 ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
668 // Nonce has already been used
669 // - transaction: the transaction attempted
670 ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED";
671 // The replacement fee for the transaction is too low
672 // - transaction: the transaction attempted
673 ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED";
674 // The gas limit could not be estimated
675 // - transaction: the transaction passed to estimateGas
676 ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
677})(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));
678;
679var Logger = /** @class */ (function () {
680 function Logger(version) {
681 Object.defineProperty(this, "version", {
682 enumerable: true,
683 value: version,
684 writable: false
685 });
686 }
687 Logger.prototype._log = function (logLevel, args) {
688 var level = logLevel.toLowerCase();
689 if (LogLevels[level] == null) {
690 this.throwArgumentError("invalid log level name", "logLevel", logLevel);
691 }
692 if (_logLevel > LogLevels[level]) {
693 return;
694 }
695 console.log.apply(console, args);
696 };
697 Logger.prototype.debug = function () {
698 var args = [];
699 for (var _i = 0; _i < arguments.length; _i++) {
700 args[_i] = arguments[_i];
701 }
702 this._log(Logger.levels.DEBUG, args);
703 };
704 Logger.prototype.info = function () {
705 var args = [];
706 for (var _i = 0; _i < arguments.length; _i++) {
707 args[_i] = arguments[_i];
708 }
709 this._log(Logger.levels.INFO, args);
710 };
711 Logger.prototype.warn = function () {
712 var args = [];
713 for (var _i = 0; _i < arguments.length; _i++) {
714 args[_i] = arguments[_i];
715 }
716 this._log(Logger.levels.WARNING, args);
717 };
718 Logger.prototype.makeError = function (message, code, params) {
719 // Errors are being censored
720 if (_censorErrors) {
721 return this.makeError("censored error", code, {});
722 }
723 if (!code) {
724 code = Logger.errors.UNKNOWN_ERROR;
725 }
726 if (!params) {
727 params = {};
728 }
729 var messageDetails = [];
730 Object.keys(params).forEach(function (key) {
731 try {
732 messageDetails.push(key + "=" + JSON.stringify(params[key]));
733 }
734 catch (error) {
735 messageDetails.push(key + "=" + JSON.stringify(params[key].toString()));
736 }
737 });
738 messageDetails.push("code=" + code);
739 messageDetails.push("version=" + this.version);
740 var reason = message;
741 if (messageDetails.length) {
742 message += " (" + messageDetails.join(", ") + ")";
743 }
744 // @TODO: Any??
745 var error = new Error(message);
746 error.reason = reason;
747 error.code = code;
748 Object.keys(params).forEach(function (key) {
749 error[key] = params[key];
750 });
751 return error;
752 };
753 Logger.prototype.throwError = function (message, code, params) {
754 throw this.makeError(message, code, params);
755 };
756 Logger.prototype.throwArgumentError = function (message, name, value) {
757 return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {
758 argument: name,
759 value: value
760 });
761 };
762 Logger.prototype.assert = function (condition, message, code, params) {
763 if (!!condition) {
764 return;
765 }
766 this.throwError(message, code, params);
767 };
768 Logger.prototype.assertArgument = function (condition, message, name, value) {
769 if (!!condition) {
770 return;
771 }
772 this.throwArgumentError(message, name, value);
773 };
774 Logger.prototype.checkNormalize = function (message) {
775 if (message == null) {
776 message = "platform missing String.prototype.normalize";
777 }
778 if (_normalizeError) {
779 this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, {
780 operation: "String.prototype.normalize", form: _normalizeError
781 });
782 }
783 };
784 Logger.prototype.checkSafeUint53 = function (value, message) {
785 if (typeof (value) !== "number") {
786 return;
787 }
788 if (message == null) {
789 message = "value not safe";
790 }
791 if (value < 0 || value >= 0x1fffffffffffff) {
792 this.throwError(message, Logger.errors.NUMERIC_FAULT, {
793 operation: "checkSafeInteger",
794 fault: "out-of-safe-range",
795 value: value
796 });
797 }
798 if (value % 1) {
799 this.throwError(message, Logger.errors.NUMERIC_FAULT, {
800 operation: "checkSafeInteger",
801 fault: "non-integer",
802 value: value
803 });
804 }
805 };
806 Logger.prototype.checkArgumentCount = function (count, expectedCount, message) {
807 if (message) {
808 message = ": " + message;
809 }
810 else {
811 message = "";
812 }
813 if (count < expectedCount) {
814 this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, {
815 count: count,
816 expectedCount: expectedCount
817 });
818 }
819 if (count > expectedCount) {
820 this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, {
821 count: count,
822 expectedCount: expectedCount
823 });
824 }
825 };
826 Logger.prototype.checkNew = function (target, kind) {
827 if (target === Object || target == null) {
828 this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
829 }
830 };
831 Logger.prototype.checkAbstract = function (target, kind) {
832 if (target === kind) {
833 this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" });
834 }
835 else if (target === Object || target == null) {
836 this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
837 }
838 };
839 Logger.globalLogger = function () {
840 if (!_globalLogger) {
841 _globalLogger = new Logger(_version_1.version);
842 }
843 return _globalLogger;
844 };
845 Logger.setCensorship = function (censorship, permanent) {
846 if (!censorship && permanent) {
847 this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, {
848 operation: "setCensorship"
849 });
850 }
851 if (_permanentCensorErrors) {
852 if (!censorship) {
853 return;
854 }
855 this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, {
856 operation: "setCensorship"
857 });
858 }
859 _censorErrors = !!censorship;
860 _permanentCensorErrors = !!permanent;
861 };
862 Logger.setLogLevel = function (logLevel) {
863 var level = LogLevels[logLevel.toLowerCase()];
864 if (level == null) {
865 Logger.globalLogger().warn("invalid log level - " + logLevel);
866 return;
867 }
868 _logLevel = level;
869 };
870 Logger.from = function (version) {
871 return new Logger(version);
872 };
873 Logger.errors = ErrorCode;
874 Logger.levels = LogLevel;
875 return Logger;
876}());
877exports.Logger = Logger;
878
879},{"./_version":5}],7:[function(require,module,exports){
880'use strict';
881
882const asn1 = exports;
883
884asn1.bignum = require('bn.js');
885
886asn1.define = require('./asn1/api').define;
887asn1.base = require('./asn1/base');
888asn1.constants = require('./asn1/constants');
889asn1.decoders = require('./asn1/decoders');
890asn1.encoders = require('./asn1/encoders');
891
892},{"./asn1/api":8,"./asn1/base":10,"./asn1/constants":14,"./asn1/decoders":16,"./asn1/encoders":19,"bn.js":21}],8:[function(require,module,exports){
893'use strict';
894
895const encoders = require('./encoders');
896const decoders = require('./decoders');
897const inherits = require('inherits');
898
899const api = exports;
900
901api.define = function define(name, body) {
902 return new Entity(name, body);
903};
904
905function Entity(name, body) {
906 this.name = name;
907 this.body = body;
908
909 this.decoders = {};
910 this.encoders = {};
911}
912
913Entity.prototype._createNamed = function createNamed(Base) {
914 const name = this.name;
915
916 function Generated(entity) {
917 this._initNamed(entity, name);
918 }
919 inherits(Generated, Base);
920 Generated.prototype._initNamed = function _initNamed(entity, name) {
921 Base.call(this, entity, name);
922 };
923
924 return new Generated(this);
925};
926
927Entity.prototype._getDecoder = function _getDecoder(enc) {
928 enc = enc || 'der';
929 // Lazily create decoder
930 if (!this.decoders.hasOwnProperty(enc))
931 this.decoders[enc] = this._createNamed(decoders[enc]);
932 return this.decoders[enc];
933};
934
935Entity.prototype.decode = function decode(data, enc, options) {
936 return this._getDecoder(enc).decode(data, options);
937};
938
939Entity.prototype._getEncoder = function _getEncoder(enc) {
940 enc = enc || 'der';
941 // Lazily create encoder
942 if (!this.encoders.hasOwnProperty(enc))
943 this.encoders[enc] = this._createNamed(encoders[enc]);
944 return this.encoders[enc];
945};
946
947Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
948 return this._getEncoder(enc).encode(data, reporter);
949};
950
951},{"./decoders":16,"./encoders":19,"inherits":152}],9:[function(require,module,exports){
952'use strict';
953
954const inherits = require('inherits');
955const Reporter = require('../base/reporter').Reporter;
956const Buffer = require('safer-buffer').Buffer;
957
958function DecoderBuffer(base, options) {
959 Reporter.call(this, options);
960 if (!Buffer.isBuffer(base)) {
961 this.error('Input not Buffer');
962 return;
963 }
964
965 this.base = base;
966 this.offset = 0;
967 this.length = base.length;
968}
969inherits(DecoderBuffer, Reporter);
970exports.DecoderBuffer = DecoderBuffer;
971
972DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) {
973 if (data instanceof DecoderBuffer) {
974 return true;
975 }
976
977 // Or accept compatible API
978 const isCompatible = typeof data === 'object' &&
979 Buffer.isBuffer(data.base) &&
980 data.constructor.name === 'DecoderBuffer' &&
981 typeof data.offset === 'number' &&
982 typeof data.length === 'number' &&
983 typeof data.save === 'function' &&
984 typeof data.restore === 'function' &&
985 typeof data.isEmpty === 'function' &&
986 typeof data.readUInt8 === 'function' &&
987 typeof data.skip === 'function' &&
988 typeof data.raw === 'function';
989
990 return isCompatible;
991};
992
993DecoderBuffer.prototype.save = function save() {
994 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
995};
996
997DecoderBuffer.prototype.restore = function restore(save) {
998 // Return skipped data
999 const res = new DecoderBuffer(this.base);
1000 res.offset = save.offset;
1001 res.length = this.offset;
1002
1003 this.offset = save.offset;
1004 Reporter.prototype.restore.call(this, save.reporter);
1005
1006 return res;
1007};
1008
1009DecoderBuffer.prototype.isEmpty = function isEmpty() {
1010 return this.offset === this.length;
1011};
1012
1013DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
1014 if (this.offset + 1 <= this.length)
1015 return this.base.readUInt8(this.offset++, true);
1016 else
1017 return this.error(fail || 'DecoderBuffer overrun');
1018};
1019
1020DecoderBuffer.prototype.skip = function skip(bytes, fail) {
1021 if (!(this.offset + bytes <= this.length))
1022 return this.error(fail || 'DecoderBuffer overrun');
1023
1024 const res = new DecoderBuffer(this.base);
1025
1026 // Share reporter state
1027 res._reporterState = this._reporterState;
1028
1029 res.offset = this.offset;
1030 res.length = this.offset + bytes;
1031 this.offset += bytes;
1032 return res;
1033};
1034
1035DecoderBuffer.prototype.raw = function raw(save) {
1036 return this.base.slice(save ? save.offset : this.offset, this.length);
1037};
1038
1039function EncoderBuffer(value, reporter) {
1040 if (Array.isArray(value)) {
1041 this.length = 0;
1042 this.value = value.map(function(item) {
1043 if (!EncoderBuffer.isEncoderBuffer(item))
1044 item = new EncoderBuffer(item, reporter);
1045 this.length += item.length;
1046 return item;
1047 }, this);
1048 } else if (typeof value === 'number') {
1049 if (!(0 <= value && value <= 0xff))
1050 return reporter.error('non-byte EncoderBuffer value');
1051 this.value = value;
1052 this.length = 1;
1053 } else if (typeof value === 'string') {
1054 this.value = value;
1055 this.length = Buffer.byteLength(value);
1056 } else if (Buffer.isBuffer(value)) {
1057 this.value = value;
1058 this.length = value.length;
1059 } else {
1060 return reporter.error('Unsupported type: ' + typeof value);
1061 }
1062}
1063exports.EncoderBuffer = EncoderBuffer;
1064
1065EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) {
1066 if (data instanceof EncoderBuffer) {
1067 return true;
1068 }
1069
1070 // Or accept compatible API
1071 const isCompatible = typeof data === 'object' &&
1072 data.constructor.name === 'EncoderBuffer' &&
1073 typeof data.length === 'number' &&
1074 typeof data.join === 'function';
1075
1076 return isCompatible;
1077};
1078
1079EncoderBuffer.prototype.join = function join(out, offset) {
1080 if (!out)
1081 out = Buffer.alloc(this.length);
1082 if (!offset)
1083 offset = 0;
1084
1085 if (this.length === 0)
1086 return out;
1087
1088 if (Array.isArray(this.value)) {
1089 this.value.forEach(function(item) {
1090 item.join(out, offset);
1091 offset += item.length;
1092 });
1093 } else {
1094 if (typeof this.value === 'number')
1095 out[offset] = this.value;
1096 else if (typeof this.value === 'string')
1097 out.write(this.value, offset);
1098 else if (Buffer.isBuffer(this.value))
1099 this.value.copy(out, offset);
1100 offset += this.length;
1101 }
1102
1103 return out;
1104};
1105
1106},{"../base/reporter":12,"inherits":152,"safer-buffer":201}],10:[function(require,module,exports){
1107'use strict';
1108
1109const base = exports;
1110
1111base.Reporter = require('./reporter').Reporter;
1112base.DecoderBuffer = require('./buffer').DecoderBuffer;
1113base.EncoderBuffer = require('./buffer').EncoderBuffer;
1114base.Node = require('./node');
1115
1116},{"./buffer":9,"./node":11,"./reporter":12}],11:[function(require,module,exports){
1117'use strict';
1118
1119const Reporter = require('../base/reporter').Reporter;
1120const EncoderBuffer = require('../base/buffer').EncoderBuffer;
1121const DecoderBuffer = require('../base/buffer').DecoderBuffer;
1122const assert = require('minimalistic-assert');
1123
1124// Supported tags
1125const tags = [
1126 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
1127 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
1128 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
1129 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
1130];
1131
1132// Public methods list
1133const methods = [
1134 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
1135 'any', 'contains'
1136].concat(tags);
1137
1138// Overrided methods list
1139const overrided = [
1140 '_peekTag', '_decodeTag', '_use',
1141 '_decodeStr', '_decodeObjid', '_decodeTime',
1142 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
1143
1144 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
1145 '_encodeNull', '_encodeInt', '_encodeBool'
1146];
1147
1148function Node(enc, parent, name) {
1149 const state = {};
1150 this._baseState = state;
1151
1152 state.name = name;
1153 state.enc = enc;
1154
1155 state.parent = parent || null;
1156 state.children = null;
1157
1158 // State
1159 state.tag = null;
1160 state.args = null;
1161 state.reverseArgs = null;
1162 state.choice = null;
1163 state.optional = false;
1164 state.any = false;
1165 state.obj = false;
1166 state.use = null;
1167 state.useDecoder = null;
1168 state.key = null;
1169 state['default'] = null;
1170 state.explicit = null;
1171 state.implicit = null;
1172 state.contains = null;
1173
1174 // Should create new instance on each method
1175 if (!state.parent) {
1176 state.children = [];
1177 this._wrap();
1178 }
1179}
1180module.exports = Node;
1181
1182const stateProps = [
1183 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
1184 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
1185 'implicit', 'contains'
1186];
1187
1188Node.prototype.clone = function clone() {
1189 const state = this._baseState;
1190 const cstate = {};
1191 stateProps.forEach(function(prop) {
1192 cstate[prop] = state[prop];
1193 });
1194 const res = new this.constructor(cstate.parent);
1195 res._baseState = cstate;
1196 return res;
1197};
1198
1199Node.prototype._wrap = function wrap() {
1200 const state = this._baseState;
1201 methods.forEach(function(method) {
1202 this[method] = function _wrappedMethod() {
1203 const clone = new this.constructor(this);
1204 state.children.push(clone);
1205 return clone[method].apply(clone, arguments);
1206 };
1207 }, this);
1208};
1209
1210Node.prototype._init = function init(body) {
1211 const state = this._baseState;
1212
1213 assert(state.parent === null);
1214 body.call(this);
1215
1216 // Filter children
1217 state.children = state.children.filter(function(child) {
1218 return child._baseState.parent === this;
1219 }, this);
1220 assert.equal(state.children.length, 1, 'Root node can have only one child');
1221};
1222
1223Node.prototype._useArgs = function useArgs(args) {
1224 const state = this._baseState;
1225
1226 // Filter children and args
1227 const children = args.filter(function(arg) {
1228 return arg instanceof this.constructor;
1229 }, this);
1230 args = args.filter(function(arg) {
1231 return !(arg instanceof this.constructor);
1232 }, this);
1233
1234 if (children.length !== 0) {
1235 assert(state.children === null);
1236 state.children = children;
1237
1238 // Replace parent to maintain backward link
1239 children.forEach(function(child) {
1240 child._baseState.parent = this;
1241 }, this);
1242 }
1243 if (args.length !== 0) {
1244 assert(state.args === null);
1245 state.args = args;
1246 state.reverseArgs = args.map(function(arg) {
1247 if (typeof arg !== 'object' || arg.constructor !== Object)
1248 return arg;
1249
1250 const res = {};
1251 Object.keys(arg).forEach(function(key) {
1252 if (key == (key | 0))
1253 key |= 0;
1254 const value = arg[key];
1255 res[value] = key;
1256 });
1257 return res;
1258 });
1259 }
1260};
1261
1262//
1263// Overrided methods
1264//
1265
1266overrided.forEach(function(method) {
1267 Node.prototype[method] = function _overrided() {
1268 const state = this._baseState;
1269 throw new Error(method + ' not implemented for encoding: ' + state.enc);
1270 };
1271});
1272
1273//
1274// Public methods
1275//
1276
1277tags.forEach(function(tag) {
1278 Node.prototype[tag] = function _tagMethod() {
1279 const state = this._baseState;
1280 const args = Array.prototype.slice.call(arguments);
1281
1282 assert(state.tag === null);
1283 state.tag = tag;
1284
1285 this._useArgs(args);
1286
1287 return this;
1288 };
1289});
1290
1291Node.prototype.use = function use(item) {
1292 assert(item);
1293 const state = this._baseState;
1294
1295 assert(state.use === null);
1296 state.use = item;
1297
1298 return this;
1299};
1300
1301Node.prototype.optional = function optional() {
1302 const state = this._baseState;
1303
1304 state.optional = true;
1305
1306 return this;
1307};
1308
1309Node.prototype.def = function def(val) {
1310 const state = this._baseState;
1311
1312 assert(state['default'] === null);
1313 state['default'] = val;
1314 state.optional = true;
1315
1316 return this;
1317};
1318
1319Node.prototype.explicit = function explicit(num) {
1320 const state = this._baseState;
1321
1322 assert(state.explicit === null && state.implicit === null);
1323 state.explicit = num;
1324
1325 return this;
1326};
1327
1328Node.prototype.implicit = function implicit(num) {
1329 const state = this._baseState;
1330
1331 assert(state.explicit === null && state.implicit === null);
1332 state.implicit = num;
1333
1334 return this;
1335};
1336
1337Node.prototype.obj = function obj() {
1338 const state = this._baseState;
1339 const args = Array.prototype.slice.call(arguments);
1340
1341 state.obj = true;
1342
1343 if (args.length !== 0)
1344 this._useArgs(args);
1345
1346 return this;
1347};
1348
1349Node.prototype.key = function key(newKey) {
1350 const state = this._baseState;
1351
1352 assert(state.key === null);
1353 state.key = newKey;
1354
1355 return this;
1356};
1357
1358Node.prototype.any = function any() {
1359 const state = this._baseState;
1360
1361 state.any = true;
1362
1363 return this;
1364};
1365
1366Node.prototype.choice = function choice(obj) {
1367 const state = this._baseState;
1368
1369 assert(state.choice === null);
1370 state.choice = obj;
1371 this._useArgs(Object.keys(obj).map(function(key) {
1372 return obj[key];
1373 }));
1374
1375 return this;
1376};
1377
1378Node.prototype.contains = function contains(item) {
1379 const state = this._baseState;
1380
1381 assert(state.use === null);
1382 state.contains = item;
1383
1384 return this;
1385};
1386
1387//
1388// Decoding
1389//
1390
1391Node.prototype._decode = function decode(input, options) {
1392 const state = this._baseState;
1393
1394 // Decode root node
1395 if (state.parent === null)
1396 return input.wrapResult(state.children[0]._decode(input, options));
1397
1398 let result = state['default'];
1399 let present = true;
1400
1401 let prevKey = null;
1402 if (state.key !== null)
1403 prevKey = input.enterKey(state.key);
1404
1405 // Check if tag is there
1406 if (state.optional) {
1407 let tag = null;
1408 if (state.explicit !== null)
1409 tag = state.explicit;
1410 else if (state.implicit !== null)
1411 tag = state.implicit;
1412 else if (state.tag !== null)
1413 tag = state.tag;
1414
1415 if (tag === null && !state.any) {
1416 // Trial and Error
1417 const save = input.save();
1418 try {
1419 if (state.choice === null)
1420 this._decodeGeneric(state.tag, input, options);
1421 else
1422 this._decodeChoice(input, options);
1423 present = true;
1424 } catch (e) {
1425 present = false;
1426 }
1427 input.restore(save);
1428 } else {
1429 present = this._peekTag(input, tag, state.any);
1430
1431 if (input.isError(present))
1432 return present;
1433 }
1434 }
1435
1436 // Push object on stack
1437 let prevObj;
1438 if (state.obj && present)
1439 prevObj = input.enterObject();
1440
1441 if (present) {
1442 // Unwrap explicit values
1443 if (state.explicit !== null) {
1444 const explicit = this._decodeTag(input, state.explicit);
1445 if (input.isError(explicit))
1446 return explicit;
1447 input = explicit;
1448 }
1449
1450 const start = input.offset;
1451
1452 // Unwrap implicit and normal values
1453 if (state.use === null && state.choice === null) {
1454 let save;
1455 if (state.any)
1456 save = input.save();
1457 const body = this._decodeTag(
1458 input,
1459 state.implicit !== null ? state.implicit : state.tag,
1460 state.any
1461 );
1462 if (input.isError(body))
1463 return body;
1464
1465 if (state.any)
1466 result = input.raw(save);
1467 else
1468 input = body;
1469 }
1470
1471 if (options && options.track && state.tag !== null)
1472 options.track(input.path(), start, input.length, 'tagged');
1473
1474 if (options && options.track && state.tag !== null)
1475 options.track(input.path(), input.offset, input.length, 'content');
1476
1477 // Select proper method for tag
1478 if (state.any) {
1479 // no-op
1480 } else if (state.choice === null) {
1481 result = this._decodeGeneric(state.tag, input, options);
1482 } else {
1483 result = this._decodeChoice(input, options);
1484 }
1485
1486 if (input.isError(result))
1487 return result;
1488
1489 // Decode children
1490 if (!state.any && state.choice === null && state.children !== null) {
1491 state.children.forEach(function decodeChildren(child) {
1492 // NOTE: We are ignoring errors here, to let parser continue with other
1493 // parts of encoded data
1494 child._decode(input, options);
1495 });
1496 }
1497
1498 // Decode contained/encoded by schema, only in bit or octet strings
1499 if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
1500 const data = new DecoderBuffer(result);
1501 result = this._getUse(state.contains, input._reporterState.obj)
1502 ._decode(data, options);
1503 }
1504 }
1505
1506 // Pop object
1507 if (state.obj && present)
1508 result = input.leaveObject(prevObj);
1509
1510 // Set key
1511 if (state.key !== null && (result !== null || present === true))
1512 input.leaveKey(prevKey, state.key, result);
1513 else if (prevKey !== null)
1514 input.exitKey(prevKey);
1515
1516 return result;
1517};
1518
1519Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
1520 const state = this._baseState;
1521
1522 if (tag === 'seq' || tag === 'set')
1523 return null;
1524 if (tag === 'seqof' || tag === 'setof')
1525 return this._decodeList(input, tag, state.args[0], options);
1526 else if (/str$/.test(tag))
1527 return this._decodeStr(input, tag, options);
1528 else if (tag === 'objid' && state.args)
1529 return this._decodeObjid(input, state.args[0], state.args[1], options);
1530 else if (tag === 'objid')
1531 return this._decodeObjid(input, null, null, options);
1532 else if (tag === 'gentime' || tag === 'utctime')
1533 return this._decodeTime(input, tag, options);
1534 else if (tag === 'null_')
1535 return this._decodeNull(input, options);
1536 else if (tag === 'bool')
1537 return this._decodeBool(input, options);
1538 else if (tag === 'objDesc')
1539 return this._decodeStr(input, tag, options);
1540 else if (tag === 'int' || tag === 'enum')
1541 return this._decodeInt(input, state.args && state.args[0], options);
1542
1543 if (state.use !== null) {
1544 return this._getUse(state.use, input._reporterState.obj)
1545 ._decode(input, options);
1546 } else {
1547 return input.error('unknown tag: ' + tag);
1548 }
1549};
1550
1551Node.prototype._getUse = function _getUse(entity, obj) {
1552
1553 const state = this._baseState;
1554 // Create altered use decoder if implicit is set
1555 state.useDecoder = this._use(entity, obj);
1556 assert(state.useDecoder._baseState.parent === null);
1557 state.useDecoder = state.useDecoder._baseState.children[0];
1558 if (state.implicit !== state.useDecoder._baseState.implicit) {
1559 state.useDecoder = state.useDecoder.clone();
1560 state.useDecoder._baseState.implicit = state.implicit;
1561 }
1562 return state.useDecoder;
1563};
1564
1565Node.prototype._decodeChoice = function decodeChoice(input, options) {
1566 const state = this._baseState;
1567 let result = null;
1568 let match = false;
1569
1570 Object.keys(state.choice).some(function(key) {
1571 const save = input.save();
1572 const node = state.choice[key];
1573 try {
1574 const value = node._decode(input, options);
1575 if (input.isError(value))
1576 return false;
1577
1578 result = { type: key, value: value };
1579 match = true;
1580 } catch (e) {
1581 input.restore(save);
1582 return false;
1583 }
1584 return true;
1585 }, this);
1586
1587 if (!match)
1588 return input.error('Choice not matched');
1589
1590 return result;
1591};
1592
1593//
1594// Encoding
1595//
1596
1597Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
1598 return new EncoderBuffer(data, this.reporter);
1599};
1600
1601Node.prototype._encode = function encode(data, reporter, parent) {
1602 const state = this._baseState;
1603 if (state['default'] !== null && state['default'] === data)
1604 return;
1605
1606 const result = this._encodeValue(data, reporter, parent);
1607 if (result === undefined)
1608 return;
1609
1610 if (this._skipDefault(result, reporter, parent))
1611 return;
1612
1613 return result;
1614};
1615
1616Node.prototype._encodeValue = function encode(data, reporter, parent) {
1617 const state = this._baseState;
1618
1619 // Decode root node
1620 if (state.parent === null)
1621 return state.children[0]._encode(data, reporter || new Reporter());
1622
1623 let result = null;
1624
1625 // Set reporter to share it with a child class
1626 this.reporter = reporter;
1627
1628 // Check if data is there
1629 if (state.optional && data === undefined) {
1630 if (state['default'] !== null)
1631 data = state['default'];
1632 else
1633 return;
1634 }
1635
1636 // Encode children first
1637 let content = null;
1638 let primitive = false;
1639 if (state.any) {
1640 // Anything that was given is translated to buffer
1641 result = this._createEncoderBuffer(data);
1642 } else if (state.choice) {
1643 result = this._encodeChoice(data, reporter);
1644 } else if (state.contains) {
1645 content = this._getUse(state.contains, parent)._encode(data, reporter);
1646 primitive = true;
1647 } else if (state.children) {
1648 content = state.children.map(function(child) {
1649 if (child._baseState.tag === 'null_')
1650 return child._encode(null, reporter, data);
1651
1652 if (child._baseState.key === null)
1653 return reporter.error('Child should have a key');
1654 const prevKey = reporter.enterKey(child._baseState.key);
1655
1656 if (typeof data !== 'object')
1657 return reporter.error('Child expected, but input is not object');
1658
1659 const res = child._encode(data[child._baseState.key], reporter, data);
1660 reporter.leaveKey(prevKey);
1661
1662 return res;
1663 }, this).filter(function(child) {
1664 return child;
1665 });
1666 content = this._createEncoderBuffer(content);
1667 } else {
1668 if (state.tag === 'seqof' || state.tag === 'setof') {
1669 // TODO(indutny): this should be thrown on DSL level
1670 if (!(state.args && state.args.length === 1))
1671 return reporter.error('Too many args for : ' + state.tag);
1672
1673 if (!Array.isArray(data))
1674 return reporter.error('seqof/setof, but data is not Array');
1675
1676 const child = this.clone();
1677 child._baseState.implicit = null;
1678 content = this._createEncoderBuffer(data.map(function(item) {
1679 const state = this._baseState;
1680
1681 return this._getUse(state.args[0], data)._encode(item, reporter);
1682 }, child));
1683 } else if (state.use !== null) {
1684 result = this._getUse(state.use, parent)._encode(data, reporter);
1685 } else {
1686 content = this._encodePrimitive(state.tag, data);
1687 primitive = true;
1688 }
1689 }
1690
1691 // Encode data itself
1692 if (!state.any && state.choice === null) {
1693 const tag = state.implicit !== null ? state.implicit : state.tag;
1694 const cls = state.implicit === null ? 'universal' : 'context';
1695
1696 if (tag === null) {
1697 if (state.use === null)
1698 reporter.error('Tag could be omitted only for .use()');
1699 } else {
1700 if (state.use === null)
1701 result = this._encodeComposite(tag, primitive, cls, content);
1702 }
1703 }
1704
1705 // Wrap in explicit
1706 if (state.explicit !== null)
1707 result = this._encodeComposite(state.explicit, false, 'context', result);
1708
1709 return result;
1710};
1711
1712Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
1713 const state = this._baseState;
1714
1715 const node = state.choice[data.type];
1716 if (!node) {
1717 assert(
1718 false,
1719 data.type + ' not found in ' +
1720 JSON.stringify(Object.keys(state.choice)));
1721 }
1722 return node._encode(data.value, reporter);
1723};
1724
1725Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
1726 const state = this._baseState;
1727
1728 if (/str$/.test(tag))
1729 return this._encodeStr(data, tag);
1730 else if (tag === 'objid' && state.args)
1731 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
1732 else if (tag === 'objid')
1733 return this._encodeObjid(data, null, null);
1734 else if (tag === 'gentime' || tag === 'utctime')
1735 return this._encodeTime(data, tag);
1736 else if (tag === 'null_')
1737 return this._encodeNull();
1738 else if (tag === 'int' || tag === 'enum')
1739 return this._encodeInt(data, state.args && state.reverseArgs[0]);
1740 else if (tag === 'bool')
1741 return this._encodeBool(data);
1742 else if (tag === 'objDesc')
1743 return this._encodeStr(data, tag);
1744 else
1745 throw new Error('Unsupported tag: ' + tag);
1746};
1747
1748Node.prototype._isNumstr = function isNumstr(str) {
1749 return /^[0-9 ]*$/.test(str);
1750};
1751
1752Node.prototype._isPrintstr = function isPrintstr(str) {
1753 return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str);
1754};
1755
1756},{"../base/buffer":9,"../base/reporter":12,"minimalistic-assert":159}],12:[function(require,module,exports){
1757'use strict';
1758
1759const inherits = require('inherits');
1760
1761function Reporter(options) {
1762 this._reporterState = {
1763 obj: null,
1764 path: [],
1765 options: options || {},
1766 errors: []
1767 };
1768}
1769exports.Reporter = Reporter;
1770
1771Reporter.prototype.isError = function isError(obj) {
1772 return obj instanceof ReporterError;
1773};
1774
1775Reporter.prototype.save = function save() {
1776 const state = this._reporterState;
1777
1778 return { obj: state.obj, pathLen: state.path.length };
1779};
1780
1781Reporter.prototype.restore = function restore(data) {
1782 const state = this._reporterState;
1783
1784 state.obj = data.obj;
1785 state.path = state.path.slice(0, data.pathLen);
1786};
1787
1788Reporter.prototype.enterKey = function enterKey(key) {
1789 return this._reporterState.path.push(key);
1790};
1791
1792Reporter.prototype.exitKey = function exitKey(index) {
1793 const state = this._reporterState;
1794
1795 state.path = state.path.slice(0, index - 1);
1796};
1797
1798Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
1799 const state = this._reporterState;
1800
1801 this.exitKey(index);
1802 if (state.obj !== null)
1803 state.obj[key] = value;
1804};
1805
1806Reporter.prototype.path = function path() {
1807 return this._reporterState.path.join('/');
1808};
1809
1810Reporter.prototype.enterObject = function enterObject() {
1811 const state = this._reporterState;
1812
1813 const prev = state.obj;
1814 state.obj = {};
1815 return prev;
1816};
1817
1818Reporter.prototype.leaveObject = function leaveObject(prev) {
1819 const state = this._reporterState;
1820
1821 const now = state.obj;
1822 state.obj = prev;
1823 return now;
1824};
1825
1826Reporter.prototype.error = function error(msg) {
1827 let err;
1828 const state = this._reporterState;
1829
1830 const inherited = msg instanceof ReporterError;
1831 if (inherited) {
1832 err = msg;
1833 } else {
1834 err = new ReporterError(state.path.map(function(elem) {
1835 return '[' + JSON.stringify(elem) + ']';
1836 }).join(''), msg.message || msg, msg.stack);
1837 }
1838
1839 if (!state.options.partial)
1840 throw err;
1841
1842 if (!inherited)
1843 state.errors.push(err);
1844
1845 return err;
1846};
1847
1848Reporter.prototype.wrapResult = function wrapResult(result) {
1849 const state = this._reporterState;
1850 if (!state.options.partial)
1851 return result;
1852
1853 return {
1854 result: this.isError(result) ? null : result,
1855 errors: state.errors
1856 };
1857};
1858
1859function ReporterError(path, msg) {
1860 this.path = path;
1861 this.rethrow(msg);
1862}
1863inherits(ReporterError, Error);
1864
1865ReporterError.prototype.rethrow = function rethrow(msg) {
1866 this.message = msg + ' at: ' + (this.path || '(shallow)');
1867 if (Error.captureStackTrace)
1868 Error.captureStackTrace(this, ReporterError);
1869
1870 if (!this.stack) {
1871 try {
1872 // IE only adds stack when thrown
1873 throw new Error(this.message);
1874 } catch (e) {
1875 this.stack = e.stack;
1876 }
1877 }
1878 return this;
1879};
1880
1881},{"inherits":152}],13:[function(require,module,exports){
1882'use strict';
1883
1884// Helper
1885function reverse(map) {
1886 const res = {};
1887
1888 Object.keys(map).forEach(function(key) {
1889 // Convert key to integer if it is stringified
1890 if ((key | 0) == key)
1891 key = key | 0;
1892
1893 const value = map[key];
1894 res[value] = key;
1895 });
1896
1897 return res;
1898}
1899
1900exports.tagClass = {
1901 0: 'universal',
1902 1: 'application',
1903 2: 'context',
1904 3: 'private'
1905};
1906exports.tagClassByName = reverse(exports.tagClass);
1907
1908exports.tag = {
1909 0x00: 'end',
1910 0x01: 'bool',
1911 0x02: 'int',
1912 0x03: 'bitstr',
1913 0x04: 'octstr',
1914 0x05: 'null_',
1915 0x06: 'objid',
1916 0x07: 'objDesc',
1917 0x08: 'external',
1918 0x09: 'real',
1919 0x0a: 'enum',
1920 0x0b: 'embed',
1921 0x0c: 'utf8str',
1922 0x0d: 'relativeOid',
1923 0x10: 'seq',
1924 0x11: 'set',
1925 0x12: 'numstr',
1926 0x13: 'printstr',
1927 0x14: 't61str',
1928 0x15: 'videostr',
1929 0x16: 'ia5str',
1930 0x17: 'utctime',
1931 0x18: 'gentime',
1932 0x19: 'graphstr',
1933 0x1a: 'iso646str',
1934 0x1b: 'genstr',
1935 0x1c: 'unistr',
1936 0x1d: 'charstr',
1937 0x1e: 'bmpstr'
1938};
1939exports.tagByName = reverse(exports.tag);
1940
1941},{}],14:[function(require,module,exports){
1942'use strict';
1943
1944const constants = exports;
1945
1946// Helper
1947constants._reverse = function reverse(map) {
1948 const res = {};
1949
1950 Object.keys(map).forEach(function(key) {
1951 // Convert key to integer if it is stringified
1952 if ((key | 0) == key)
1953 key = key | 0;
1954
1955 const value = map[key];
1956 res[value] = key;
1957 });
1958
1959 return res;
1960};
1961
1962constants.der = require('./der');
1963
1964},{"./der":13}],15:[function(require,module,exports){
1965'use strict';
1966
1967const inherits = require('inherits');
1968
1969const bignum = require('bn.js');
1970const DecoderBuffer = require('../base/buffer').DecoderBuffer;
1971const Node = require('../base/node');
1972
1973// Import DER constants
1974const der = require('../constants/der');
1975
1976function DERDecoder(entity) {
1977 this.enc = 'der';
1978 this.name = entity.name;
1979 this.entity = entity;
1980
1981 // Construct base tree
1982 this.tree = new DERNode();
1983 this.tree._init(entity.body);
1984}
1985module.exports = DERDecoder;
1986
1987DERDecoder.prototype.decode = function decode(data, options) {
1988 if (!DecoderBuffer.isDecoderBuffer(data)) {
1989 data = new DecoderBuffer(data, options);
1990 }
1991
1992 return this.tree._decode(data, options);
1993};
1994
1995// Tree methods
1996
1997function DERNode(parent) {
1998 Node.call(this, 'der', parent);
1999}
2000inherits(DERNode, Node);
2001
2002DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
2003 if (buffer.isEmpty())
2004 return false;
2005
2006 const state = buffer.save();
2007 const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
2008 if (buffer.isError(decodedTag))
2009 return decodedTag;
2010
2011 buffer.restore(state);
2012
2013 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
2014 (decodedTag.tagStr + 'of') === tag || any;
2015};
2016
2017DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
2018 const decodedTag = derDecodeTag(buffer,
2019 'Failed to decode tag of "' + tag + '"');
2020 if (buffer.isError(decodedTag))
2021 return decodedTag;
2022
2023 let len = derDecodeLen(buffer,
2024 decodedTag.primitive,
2025 'Failed to get length of "' + tag + '"');
2026
2027 // Failure
2028 if (buffer.isError(len))
2029 return len;
2030
2031 if (!any &&
2032 decodedTag.tag !== tag &&
2033 decodedTag.tagStr !== tag &&
2034 decodedTag.tagStr + 'of' !== tag) {
2035 return buffer.error('Failed to match tag: "' + tag + '"');
2036 }
2037
2038 if (decodedTag.primitive || len !== null)
2039 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
2040
2041 // Indefinite length... find END tag
2042 const state = buffer.save();
2043 const res = this._skipUntilEnd(
2044 buffer,
2045 'Failed to skip indefinite length body: "' + this.tag + '"');
2046 if (buffer.isError(res))
2047 return res;
2048
2049 len = buffer.offset - state.offset;
2050 buffer.restore(state);
2051 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
2052};
2053
2054DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
2055 for (;;) {
2056 const tag = derDecodeTag(buffer, fail);
2057 if (buffer.isError(tag))
2058 return tag;
2059 const len = derDecodeLen(buffer, tag.primitive, fail);
2060 if (buffer.isError(len))
2061 return len;
2062
2063 let res;
2064 if (tag.primitive || len !== null)
2065 res = buffer.skip(len);
2066 else
2067 res = this._skipUntilEnd(buffer, fail);
2068
2069 // Failure
2070 if (buffer.isError(res))
2071 return res;
2072
2073 if (tag.tagStr === 'end')
2074 break;
2075 }
2076};
2077
2078DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
2079 options) {
2080 const result = [];
2081 while (!buffer.isEmpty()) {
2082 const possibleEnd = this._peekTag(buffer, 'end');
2083 if (buffer.isError(possibleEnd))
2084 return possibleEnd;
2085
2086 const res = decoder.decode(buffer, 'der', options);
2087 if (buffer.isError(res) && possibleEnd)
2088 break;
2089 result.push(res);
2090 }
2091 return result;
2092};
2093
2094DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
2095 if (tag === 'bitstr') {
2096 const unused = buffer.readUInt8();
2097 if (buffer.isError(unused))
2098 return unused;
2099 return { unused: unused, data: buffer.raw() };
2100 } else if (tag === 'bmpstr') {
2101 const raw = buffer.raw();
2102 if (raw.length % 2 === 1)
2103 return buffer.error('Decoding of string type: bmpstr length mismatch');
2104
2105 let str = '';
2106 for (let i = 0; i < raw.length / 2; i++) {
2107 str += String.fromCharCode(raw.readUInt16BE(i * 2));
2108 }
2109 return str;
2110 } else if (tag === 'numstr') {
2111 const numstr = buffer.raw().toString('ascii');
2112 if (!this._isNumstr(numstr)) {
2113 return buffer.error('Decoding of string type: ' +
2114 'numstr unsupported characters');
2115 }
2116 return numstr;
2117 } else if (tag === 'octstr') {
2118 return buffer.raw();
2119 } else if (tag === 'objDesc') {
2120 return buffer.raw();
2121 } else if (tag === 'printstr') {
2122 const printstr = buffer.raw().toString('ascii');
2123 if (!this._isPrintstr(printstr)) {
2124 return buffer.error('Decoding of string type: ' +
2125 'printstr unsupported characters');
2126 }
2127 return printstr;
2128 } else if (/str$/.test(tag)) {
2129 return buffer.raw().toString();
2130 } else {
2131 return buffer.error('Decoding of string type: ' + tag + ' unsupported');
2132 }
2133};
2134
2135DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
2136 let result;
2137 const identifiers = [];
2138 let ident = 0;
2139 let subident = 0;
2140 while (!buffer.isEmpty()) {
2141 subident = buffer.readUInt8();
2142 ident <<= 7;
2143 ident |= subident & 0x7f;
2144 if ((subident & 0x80) === 0) {
2145 identifiers.push(ident);
2146 ident = 0;
2147 }
2148 }
2149 if (subident & 0x80)
2150 identifiers.push(ident);
2151
2152 const first = (identifiers[0] / 40) | 0;
2153 const second = identifiers[0] % 40;
2154
2155 if (relative)
2156 result = identifiers;
2157 else
2158 result = [first, second].concat(identifiers.slice(1));
2159
2160 if (values) {
2161 let tmp = values[result.join(' ')];
2162 if (tmp === undefined)
2163 tmp = values[result.join('.')];
2164 if (tmp !== undefined)
2165 result = tmp;
2166 }
2167
2168 return result;
2169};
2170
2171DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
2172 const str = buffer.raw().toString();
2173
2174 let year;
2175 let mon;
2176 let day;
2177 let hour;
2178 let min;
2179 let sec;
2180 if (tag === 'gentime') {
2181 year = str.slice(0, 4) | 0;
2182 mon = str.slice(4, 6) | 0;
2183 day = str.slice(6, 8) | 0;
2184 hour = str.slice(8, 10) | 0;
2185 min = str.slice(10, 12) | 0;
2186 sec = str.slice(12, 14) | 0;
2187 } else if (tag === 'utctime') {
2188 year = str.slice(0, 2) | 0;
2189 mon = str.slice(2, 4) | 0;
2190 day = str.slice(4, 6) | 0;
2191 hour = str.slice(6, 8) | 0;
2192 min = str.slice(8, 10) | 0;
2193 sec = str.slice(10, 12) | 0;
2194 if (year < 70)
2195 year = 2000 + year;
2196 else
2197 year = 1900 + year;
2198 } else {
2199 return buffer.error('Decoding ' + tag + ' time is not supported yet');
2200 }
2201
2202 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
2203};
2204
2205DERNode.prototype._decodeNull = function decodeNull() {
2206 return null;
2207};
2208
2209DERNode.prototype._decodeBool = function decodeBool(buffer) {
2210 const res = buffer.readUInt8();
2211 if (buffer.isError(res))
2212 return res;
2213 else
2214 return res !== 0;
2215};
2216
2217DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
2218 // Bigint, return as it is (assume big endian)
2219 const raw = buffer.raw();
2220 let res = new bignum(raw);
2221
2222 if (values)
2223 res = values[res.toString(10)] || res;
2224
2225 return res;
2226};
2227
2228DERNode.prototype._use = function use(entity, obj) {
2229 if (typeof entity === 'function')
2230 entity = entity(obj);
2231 return entity._getDecoder('der').tree;
2232};
2233
2234// Utility methods
2235
2236function derDecodeTag(buf, fail) {
2237 let tag = buf.readUInt8(fail);
2238 if (buf.isError(tag))
2239 return tag;
2240
2241 const cls = der.tagClass[tag >> 6];
2242 const primitive = (tag & 0x20) === 0;
2243
2244 // Multi-octet tag - load
2245 if ((tag & 0x1f) === 0x1f) {
2246 let oct = tag;
2247 tag = 0;
2248 while ((oct & 0x80) === 0x80) {
2249 oct = buf.readUInt8(fail);
2250 if (buf.isError(oct))
2251 return oct;
2252
2253 tag <<= 7;
2254 tag |= oct & 0x7f;
2255 }
2256 } else {
2257 tag &= 0x1f;
2258 }
2259 const tagStr = der.tag[tag];
2260
2261 return {
2262 cls: cls,
2263 primitive: primitive,
2264 tag: tag,
2265 tagStr: tagStr
2266 };
2267}
2268
2269function derDecodeLen(buf, primitive, fail) {
2270 let len = buf.readUInt8(fail);
2271 if (buf.isError(len))
2272 return len;
2273
2274 // Indefinite form
2275 if (!primitive && len === 0x80)
2276 return null;
2277
2278 // Definite form
2279 if ((len & 0x80) === 0) {
2280 // Short form
2281 return len;
2282 }
2283
2284 // Long form
2285 const num = len & 0x7f;
2286 if (num > 4)
2287 return buf.error('length octect is too long');
2288
2289 len = 0;
2290 for (let i = 0; i < num; i++) {
2291 len <<= 8;
2292 const j = buf.readUInt8(fail);
2293 if (buf.isError(j))
2294 return j;
2295 len |= j;
2296 }
2297
2298 return len;
2299}
2300
2301},{"../base/buffer":9,"../base/node":11,"../constants/der":13,"bn.js":21,"inherits":152}],16:[function(require,module,exports){
2302'use strict';
2303
2304const decoders = exports;
2305
2306decoders.der = require('./der');
2307decoders.pem = require('./pem');
2308
2309},{"./der":15,"./pem":17}],17:[function(require,module,exports){
2310'use strict';
2311
2312const inherits = require('inherits');
2313const Buffer = require('safer-buffer').Buffer;
2314
2315const DERDecoder = require('./der');
2316
2317function PEMDecoder(entity) {
2318 DERDecoder.call(this, entity);
2319 this.enc = 'pem';
2320}
2321inherits(PEMDecoder, DERDecoder);
2322module.exports = PEMDecoder;
2323
2324PEMDecoder.prototype.decode = function decode(data, options) {
2325 const lines = data.toString().split(/[\r\n]+/g);
2326
2327 const label = options.label.toUpperCase();
2328
2329 const re = /^-----(BEGIN|END) ([^-]+)-----$/;
2330 let start = -1;
2331 let end = -1;
2332 for (let i = 0; i < lines.length; i++) {
2333 const match = lines[i].match(re);
2334 if (match === null)
2335 continue;
2336
2337 if (match[2] !== label)
2338 continue;
2339
2340 if (start === -1) {
2341 if (match[1] !== 'BEGIN')
2342 break;
2343 start = i;
2344 } else {
2345 if (match[1] !== 'END')
2346 break;
2347 end = i;
2348 break;
2349 }
2350 }
2351 if (start === -1 || end === -1)
2352 throw new Error('PEM section not found for: ' + label);
2353
2354 const base64 = lines.slice(start + 1, end).join('');
2355 // Remove excessive symbols
2356 base64.replace(/[^a-z0-9+/=]+/gi, '');
2357
2358 const input = Buffer.from(base64, 'base64');
2359 return DERDecoder.prototype.decode.call(this, input, options);
2360};
2361
2362},{"./der":15,"inherits":152,"safer-buffer":201}],18:[function(require,module,exports){
2363'use strict';
2364
2365const inherits = require('inherits');
2366const Buffer = require('safer-buffer').Buffer;
2367const Node = require('../base/node');
2368
2369// Import DER constants
2370const der = require('../constants/der');
2371
2372function DEREncoder(entity) {
2373 this.enc = 'der';
2374 this.name = entity.name;
2375 this.entity = entity;
2376
2377 // Construct base tree
2378 this.tree = new DERNode();
2379 this.tree._init(entity.body);
2380}
2381module.exports = DEREncoder;
2382
2383DEREncoder.prototype.encode = function encode(data, reporter) {
2384 return this.tree._encode(data, reporter).join();
2385};
2386
2387// Tree methods
2388
2389function DERNode(parent) {
2390 Node.call(this, 'der', parent);
2391}
2392inherits(DERNode, Node);
2393
2394DERNode.prototype._encodeComposite = function encodeComposite(tag,
2395 primitive,
2396 cls,
2397 content) {
2398 const encodedTag = encodeTag(tag, primitive, cls, this.reporter);
2399
2400 // Short form
2401 if (content.length < 0x80) {
2402 const header = Buffer.alloc(2);
2403 header[0] = encodedTag;
2404 header[1] = content.length;
2405 return this._createEncoderBuffer([ header, content ]);
2406 }
2407
2408 // Long form
2409 // Count octets required to store length
2410 let lenOctets = 1;
2411 for (let i = content.length; i >= 0x100; i >>= 8)
2412 lenOctets++;
2413
2414 const header = Buffer.alloc(1 + 1 + lenOctets);
2415 header[0] = encodedTag;
2416 header[1] = 0x80 | lenOctets;
2417
2418 for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
2419 header[i] = j & 0xff;
2420
2421 return this._createEncoderBuffer([ header, content ]);
2422};
2423
2424DERNode.prototype._encodeStr = function encodeStr(str, tag) {
2425 if (tag === 'bitstr') {
2426 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
2427 } else if (tag === 'bmpstr') {
2428 const buf = Buffer.alloc(str.length * 2);
2429 for (let i = 0; i < str.length; i++) {
2430 buf.writeUInt16BE(str.charCodeAt(i), i * 2);
2431 }
2432 return this._createEncoderBuffer(buf);
2433 } else if (tag === 'numstr') {
2434 if (!this._isNumstr(str)) {
2435 return this.reporter.error('Encoding of string type: numstr supports ' +
2436 'only digits and space');
2437 }
2438 return this._createEncoderBuffer(str);
2439 } else if (tag === 'printstr') {
2440 if (!this._isPrintstr(str)) {
2441 return this.reporter.error('Encoding of string type: printstr supports ' +
2442 'only latin upper and lower case letters, ' +
2443 'digits, space, apostrophe, left and rigth ' +
2444 'parenthesis, plus sign, comma, hyphen, ' +
2445 'dot, slash, colon, equal sign, ' +
2446 'question mark');
2447 }
2448 return this._createEncoderBuffer(str);
2449 } else if (/str$/.test(tag)) {
2450 return this._createEncoderBuffer(str);
2451 } else if (tag === 'objDesc') {
2452 return this._createEncoderBuffer(str);
2453 } else {
2454 return this.reporter.error('Encoding of string type: ' + tag +
2455 ' unsupported');
2456 }
2457};
2458
2459DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
2460 if (typeof id === 'string') {
2461 if (!values)
2462 return this.reporter.error('string objid given, but no values map found');
2463 if (!values.hasOwnProperty(id))
2464 return this.reporter.error('objid not found in values map');
2465 id = values[id].split(/[\s.]+/g);
2466 for (let i = 0; i < id.length; i++)
2467 id[i] |= 0;
2468 } else if (Array.isArray(id)) {
2469 id = id.slice();
2470 for (let i = 0; i < id.length; i++)
2471 id[i] |= 0;
2472 }
2473
2474 if (!Array.isArray(id)) {
2475 return this.reporter.error('objid() should be either array or string, ' +
2476 'got: ' + JSON.stringify(id));
2477 }
2478
2479 if (!relative) {
2480 if (id[1] >= 40)
2481 return this.reporter.error('Second objid identifier OOB');
2482 id.splice(0, 2, id[0] * 40 + id[1]);
2483 }
2484
2485 // Count number of octets
2486 let size = 0;
2487 for (let i = 0; i < id.length; i++) {
2488 let ident = id[i];
2489 for (size++; ident >= 0x80; ident >>= 7)
2490 size++;
2491 }
2492
2493 const objid = Buffer.alloc(size);
2494 let offset = objid.length - 1;
2495 for (let i = id.length - 1; i >= 0; i--) {
2496 let ident = id[i];
2497 objid[offset--] = ident & 0x7f;
2498 while ((ident >>= 7) > 0)
2499 objid[offset--] = 0x80 | (ident & 0x7f);
2500 }
2501
2502 return this._createEncoderBuffer(objid);
2503};
2504
2505function two(num) {
2506 if (num < 10)
2507 return '0' + num;
2508 else
2509 return num;
2510}
2511
2512DERNode.prototype._encodeTime = function encodeTime(time, tag) {
2513 let str;
2514 const date = new Date(time);
2515
2516 if (tag === 'gentime') {
2517 str = [
2518 two(date.getUTCFullYear()),
2519 two(date.getUTCMonth() + 1),
2520 two(date.getUTCDate()),
2521 two(date.getUTCHours()),
2522 two(date.getUTCMinutes()),
2523 two(date.getUTCSeconds()),
2524 'Z'
2525 ].join('');
2526 } else if (tag === 'utctime') {
2527 str = [
2528 two(date.getUTCFullYear() % 100),
2529 two(date.getUTCMonth() + 1),
2530 two(date.getUTCDate()),
2531 two(date.getUTCHours()),
2532 two(date.getUTCMinutes()),
2533 two(date.getUTCSeconds()),
2534 'Z'
2535 ].join('');
2536 } else {
2537 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
2538 }
2539
2540 return this._encodeStr(str, 'octstr');
2541};
2542
2543DERNode.prototype._encodeNull = function encodeNull() {
2544 return this._createEncoderBuffer('');
2545};
2546
2547DERNode.prototype._encodeInt = function encodeInt(num, values) {
2548 if (typeof num === 'string') {
2549 if (!values)
2550 return this.reporter.error('String int or enum given, but no values map');
2551 if (!values.hasOwnProperty(num)) {
2552 return this.reporter.error('Values map doesn\'t contain: ' +
2553 JSON.stringify(num));
2554 }
2555 num = values[num];
2556 }
2557
2558 // Bignum, assume big endian
2559 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
2560 const numArray = num.toArray();
2561 if (!num.sign && numArray[0] & 0x80) {
2562 numArray.unshift(0);
2563 }
2564 num = Buffer.from(numArray);
2565 }
2566
2567 if (Buffer.isBuffer(num)) {
2568 let size = num.length;
2569 if (num.length === 0)
2570 size++;
2571
2572 const out = Buffer.alloc(size);
2573 num.copy(out);
2574 if (num.length === 0)
2575 out[0] = 0;
2576 return this._createEncoderBuffer(out);
2577 }
2578
2579 if (num < 0x80)
2580 return this._createEncoderBuffer(num);
2581
2582 if (num < 0x100)
2583 return this._createEncoderBuffer([0, num]);
2584
2585 let size = 1;
2586 for (let i = num; i >= 0x100; i >>= 8)
2587 size++;
2588
2589 const out = new Array(size);
2590 for (let i = out.length - 1; i >= 0; i--) {
2591 out[i] = num & 0xff;
2592 num >>= 8;
2593 }
2594 if(out[0] & 0x80) {
2595 out.unshift(0);
2596 }
2597
2598 return this._createEncoderBuffer(Buffer.from(out));
2599};
2600
2601DERNode.prototype._encodeBool = function encodeBool(value) {
2602 return this._createEncoderBuffer(value ? 0xff : 0);
2603};
2604
2605DERNode.prototype._use = function use(entity, obj) {
2606 if (typeof entity === 'function')
2607 entity = entity(obj);
2608 return entity._getEncoder('der').tree;
2609};
2610
2611DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
2612 const state = this._baseState;
2613 let i;
2614 if (state['default'] === null)
2615 return false;
2616
2617 const data = dataBuffer.join();
2618 if (state.defaultBuffer === undefined)
2619 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
2620
2621 if (data.length !== state.defaultBuffer.length)
2622 return false;
2623
2624 for (i=0; i < data.length; i++)
2625 if (data[i] !== state.defaultBuffer[i])
2626 return false;
2627
2628 return true;
2629};
2630
2631// Utility methods
2632
2633function encodeTag(tag, primitive, cls, reporter) {
2634 let res;
2635
2636 if (tag === 'seqof')
2637 tag = 'seq';
2638 else if (tag === 'setof')
2639 tag = 'set';
2640
2641 if (der.tagByName.hasOwnProperty(tag))
2642 res = der.tagByName[tag];
2643 else if (typeof tag === 'number' && (tag | 0) === tag)
2644 res = tag;
2645 else
2646 return reporter.error('Unknown tag: ' + tag);
2647
2648 if (res >= 0x1f)
2649 return reporter.error('Multi-octet tag encoding unsupported');
2650
2651 if (!primitive)
2652 res |= 0x20;
2653
2654 res |= (der.tagClassByName[cls || 'universal'] << 6);
2655
2656 return res;
2657}
2658
2659},{"../base/node":11,"../constants/der":13,"inherits":152,"safer-buffer":201}],19:[function(require,module,exports){
2660'use strict';
2661
2662const encoders = exports;
2663
2664encoders.der = require('./der');
2665encoders.pem = require('./pem');
2666
2667},{"./der":18,"./pem":20}],20:[function(require,module,exports){
2668'use strict';
2669
2670const inherits = require('inherits');
2671
2672const DEREncoder = require('./der');
2673
2674function PEMEncoder(entity) {
2675 DEREncoder.call(this, entity);
2676 this.enc = 'pem';
2677}
2678inherits(PEMEncoder, DEREncoder);
2679module.exports = PEMEncoder;
2680
2681PEMEncoder.prototype.encode = function encode(data, options) {
2682 const buf = DEREncoder.prototype.encode.call(this, data);
2683
2684 const p = buf.toString('base64');
2685 const out = [ '-----BEGIN ' + options.label + '-----' ];
2686 for (let i = 0; i < p.length; i += 64)
2687 out.push(p.slice(i, i + 64));
2688 out.push('-----END ' + options.label + '-----');
2689 return out.join('\n');
2690};
2691
2692},{"./der":18,"inherits":152}],21:[function(require,module,exports){
2693(function (module, exports) {
2694 'use strict';
2695
2696 // Utils
2697 function assert (val, msg) {
2698 if (!val) throw new Error(msg || 'Assertion failed');
2699 }
2700
2701 // Could use `inherits` module, but don't want to move from single file
2702 // architecture yet.
2703 function inherits (ctor, superCtor) {
2704 ctor.super_ = superCtor;
2705 var TempCtor = function () {};
2706 TempCtor.prototype = superCtor.prototype;
2707 ctor.prototype = new TempCtor();
2708 ctor.prototype.constructor = ctor;
2709 }
2710
2711 // BN
2712
2713 function BN (number, base, endian) {
2714 if (BN.isBN(number)) {
2715 return number;
2716 }
2717
2718 this.negative = 0;
2719 this.words = null;
2720 this.length = 0;
2721
2722 // Reduction context
2723 this.red = null;
2724
2725 if (number !== null) {
2726 if (base === 'le' || base === 'be') {
2727 endian = base;
2728 base = 10;
2729 }
2730
2731 this._init(number || 0, base || 10, endian || 'be');
2732 }
2733 }
2734 if (typeof module === 'object') {
2735 module.exports = BN;
2736 } else {
2737 exports.BN = BN;
2738 }
2739
2740 BN.BN = BN;
2741 BN.wordSize = 26;
2742
2743 var Buffer;
2744 try {
2745 Buffer = require('buffer').Buffer;
2746 } catch (e) {
2747 }
2748
2749 BN.isBN = function isBN (num) {
2750 if (num instanceof BN) {
2751 return true;
2752 }
2753
2754 return num !== null && typeof num === 'object' &&
2755 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
2756 };
2757
2758 BN.max = function max (left, right) {
2759 if (left.cmp(right) > 0) return left;
2760 return right;
2761 };
2762
2763 BN.min = function min (left, right) {
2764 if (left.cmp(right) < 0) return left;
2765 return right;
2766 };
2767
2768 BN.prototype._init = function init (number, base, endian) {
2769 if (typeof number === 'number') {
2770 return this._initNumber(number, base, endian);
2771 }
2772
2773 if (typeof number === 'object') {
2774 return this._initArray(number, base, endian);
2775 }
2776
2777 if (base === 'hex') {
2778 base = 16;
2779 }
2780 assert(base === (base | 0) && base >= 2 && base <= 36);
2781
2782 number = number.toString().replace(/\s+/g, '');
2783 var start = 0;
2784 if (number[0] === '-') {
2785 start++;
2786 }
2787
2788 if (base === 16) {
2789 this._parseHex(number, start);
2790 } else {
2791 this._parseBase(number, base, start);
2792 }
2793
2794 if (number[0] === '-') {
2795 this.negative = 1;
2796 }
2797
2798 this.strip();
2799
2800 if (endian !== 'le') return;
2801
2802 this._initArray(this.toArray(), base, endian);
2803 };
2804
2805 BN.prototype._initNumber = function _initNumber (number, base, endian) {
2806 if (number < 0) {
2807 this.negative = 1;
2808 number = -number;
2809 }
2810 if (number < 0x4000000) {
2811 this.words = [ number & 0x3ffffff ];
2812 this.length = 1;
2813 } else if (number < 0x10000000000000) {
2814 this.words = [
2815 number & 0x3ffffff,
2816 (number / 0x4000000) & 0x3ffffff
2817 ];
2818 this.length = 2;
2819 } else {
2820 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
2821 this.words = [
2822 number & 0x3ffffff,
2823 (number / 0x4000000) & 0x3ffffff,
2824 1
2825 ];
2826 this.length = 3;
2827 }
2828
2829 if (endian !== 'le') return;
2830
2831 // Reverse the bytes
2832 this._initArray(this.toArray(), base, endian);
2833 };
2834
2835 BN.prototype._initArray = function _initArray (number, base, endian) {
2836 // Perhaps a Uint8Array
2837 assert(typeof number.length === 'number');
2838 if (number.length <= 0) {
2839 this.words = [ 0 ];
2840 this.length = 1;
2841 return this;
2842 }
2843
2844 this.length = Math.ceil(number.length / 3);
2845 this.words = new Array(this.length);
2846 for (var i = 0; i < this.length; i++) {
2847 this.words[i] = 0;
2848 }
2849
2850 var j, w;
2851 var off = 0;
2852 if (endian === 'be') {
2853 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
2854 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
2855 this.words[j] |= (w << off) & 0x3ffffff;
2856 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
2857 off += 24;
2858 if (off >= 26) {
2859 off -= 26;
2860 j++;
2861 }
2862 }
2863 } else if (endian === 'le') {
2864 for (i = 0, j = 0; i < number.length; i += 3) {
2865 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
2866 this.words[j] |= (w << off) & 0x3ffffff;
2867 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
2868 off += 24;
2869 if (off >= 26) {
2870 off -= 26;
2871 j++;
2872 }
2873 }
2874 }
2875 return this.strip();
2876 };
2877
2878 function parseHex (str, start, end) {
2879 var r = 0;
2880 var len = Math.min(str.length, end);
2881 for (var i = start; i < len; i++) {
2882 var c = str.charCodeAt(i) - 48;
2883
2884 r <<= 4;
2885
2886 // 'a' - 'f'
2887 if (c >= 49 && c <= 54) {
2888 r |= c - 49 + 0xa;
2889
2890 // 'A' - 'F'
2891 } else if (c >= 17 && c <= 22) {
2892 r |= c - 17 + 0xa;
2893
2894 // '0' - '9'
2895 } else {
2896 r |= c & 0xf;
2897 }
2898 }
2899 return r;
2900 }
2901
2902 BN.prototype._parseHex = function _parseHex (number, start) {
2903 // Create possibly bigger array to ensure that it fits the number
2904 this.length = Math.ceil((number.length - start) / 6);
2905 this.words = new Array(this.length);
2906 for (var i = 0; i < this.length; i++) {
2907 this.words[i] = 0;
2908 }
2909
2910 var j, w;
2911 // Scan 24-bit chunks and add them to the number
2912 var off = 0;
2913 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
2914 w = parseHex(number, i, i + 6);
2915 this.words[j] |= (w << off) & 0x3ffffff;
2916 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
2917 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
2918 off += 24;
2919 if (off >= 26) {
2920 off -= 26;
2921 j++;
2922 }
2923 }
2924 if (i + 6 !== start) {
2925 w = parseHex(number, start, i + 6);
2926 this.words[j] |= (w << off) & 0x3ffffff;
2927 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
2928 }
2929 this.strip();
2930 };
2931
2932 function parseBase (str, start, end, mul) {
2933 var r = 0;
2934 var len = Math.min(str.length, end);
2935 for (var i = start; i < len; i++) {
2936 var c = str.charCodeAt(i) - 48;
2937
2938 r *= mul;
2939
2940 // 'a'
2941 if (c >= 49) {
2942 r += c - 49 + 0xa;
2943
2944 // 'A'
2945 } else if (c >= 17) {
2946 r += c - 17 + 0xa;
2947
2948 // '0' - '9'
2949 } else {
2950 r += c;
2951 }
2952 }
2953 return r;
2954 }
2955
2956 BN.prototype._parseBase = function _parseBase (number, base, start) {
2957 // Initialize as zero
2958 this.words = [ 0 ];
2959 this.length = 1;
2960
2961 // Find length of limb in base
2962 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
2963 limbLen++;
2964 }
2965 limbLen--;
2966 limbPow = (limbPow / base) | 0;
2967
2968 var total = number.length - start;
2969 var mod = total % limbLen;
2970 var end = Math.min(total, total - mod) + start;
2971
2972 var word = 0;
2973 for (var i = start; i < end; i += limbLen) {
2974 word = parseBase(number, i, i + limbLen, base);
2975
2976 this.imuln(limbPow);
2977 if (this.words[0] + word < 0x4000000) {
2978 this.words[0] += word;
2979 } else {
2980 this._iaddn(word);
2981 }
2982 }
2983
2984 if (mod !== 0) {
2985 var pow = 1;
2986 word = parseBase(number, i, number.length, base);
2987
2988 for (i = 0; i < mod; i++) {
2989 pow *= base;
2990 }
2991
2992 this.imuln(pow);
2993 if (this.words[0] + word < 0x4000000) {
2994 this.words[0] += word;
2995 } else {
2996 this._iaddn(word);
2997 }
2998 }
2999 };
3000
3001 BN.prototype.copy = function copy (dest) {
3002 dest.words = new Array(this.length);
3003 for (var i = 0; i < this.length; i++) {
3004 dest.words[i] = this.words[i];
3005 }
3006 dest.length = this.length;
3007 dest.negative = this.negative;
3008 dest.red = this.red;
3009 };
3010
3011 BN.prototype.clone = function clone () {
3012 var r = new BN(null);
3013 this.copy(r);
3014 return r;
3015 };
3016
3017 BN.prototype._expand = function _expand (size) {
3018 while (this.length < size) {
3019 this.words[this.length++] = 0;
3020 }
3021 return this;
3022 };
3023
3024 // Remove leading `0` from `this`
3025 BN.prototype.strip = function strip () {
3026 while (this.length > 1 && this.words[this.length - 1] === 0) {
3027 this.length--;
3028 }
3029 return this._normSign();
3030 };
3031
3032 BN.prototype._normSign = function _normSign () {
3033 // -0 = 0
3034 if (this.length === 1 && this.words[0] === 0) {
3035 this.negative = 0;
3036 }
3037 return this;
3038 };
3039
3040 BN.prototype.inspect = function inspect () {
3041 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
3042 };
3043
3044 /*
3045
3046 var zeros = [];
3047 var groupSizes = [];
3048 var groupBases = [];
3049
3050 var s = '';
3051 var i = -1;
3052 while (++i < BN.wordSize) {
3053 zeros[i] = s;
3054 s += '0';
3055 }
3056 groupSizes[0] = 0;
3057 groupSizes[1] = 0;
3058 groupBases[0] = 0;
3059 groupBases[1] = 0;
3060 var base = 2 - 1;
3061 while (++base < 36 + 1) {
3062 var groupSize = 0;
3063 var groupBase = 1;
3064 while (groupBase < (1 << BN.wordSize) / base) {
3065 groupBase *= base;
3066 groupSize += 1;
3067 }
3068 groupSizes[base] = groupSize;
3069 groupBases[base] = groupBase;
3070 }
3071
3072 */
3073
3074 var zeros = [
3075 '',
3076 '0',
3077 '00',
3078 '000',
3079 '0000',
3080 '00000',
3081 '000000',
3082 '0000000',
3083 '00000000',
3084 '000000000',
3085 '0000000000',
3086 '00000000000',
3087 '000000000000',
3088 '0000000000000',
3089 '00000000000000',
3090 '000000000000000',
3091 '0000000000000000',
3092 '00000000000000000',
3093 '000000000000000000',
3094 '0000000000000000000',
3095 '00000000000000000000',
3096 '000000000000000000000',
3097 '0000000000000000000000',
3098 '00000000000000000000000',
3099 '000000000000000000000000',
3100 '0000000000000000000000000'
3101 ];
3102
3103 var groupSizes = [
3104 0, 0,
3105 25, 16, 12, 11, 10, 9, 8,
3106 8, 7, 7, 7, 7, 6, 6,
3107 6, 6, 6, 6, 6, 5, 5,
3108 5, 5, 5, 5, 5, 5, 5,
3109 5, 5, 5, 5, 5, 5, 5
3110 ];
3111
3112 var groupBases = [
3113 0, 0,
3114 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
3115 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
3116 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
3117 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
3118 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
3119 ];
3120
3121 BN.prototype.toString = function toString (base, padding) {
3122 base = base || 10;
3123 padding = padding | 0 || 1;
3124
3125 var out;
3126 if (base === 16 || base === 'hex') {
3127 out = '';
3128 var off = 0;
3129 var carry = 0;
3130 for (var i = 0; i < this.length; i++) {
3131 var w = this.words[i];
3132 var word = (((w << off) | carry) & 0xffffff).toString(16);
3133 carry = (w >>> (24 - off)) & 0xffffff;
3134 if (carry !== 0 || i !== this.length - 1) {
3135 out = zeros[6 - word.length] + word + out;
3136 } else {
3137 out = word + out;
3138 }
3139 off += 2;
3140 if (off >= 26) {
3141 off -= 26;
3142 i--;
3143 }
3144 }
3145 if (carry !== 0) {
3146 out = carry.toString(16) + out;
3147 }
3148 while (out.length % padding !== 0) {
3149 out = '0' + out;
3150 }
3151 if (this.negative !== 0) {
3152 out = '-' + out;
3153 }
3154 return out;
3155 }
3156
3157 if (base === (base | 0) && base >= 2 && base <= 36) {
3158 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
3159 var groupSize = groupSizes[base];
3160 // var groupBase = Math.pow(base, groupSize);
3161 var groupBase = groupBases[base];
3162 out = '';
3163 var c = this.clone();
3164 c.negative = 0;
3165 while (!c.isZero()) {
3166 var r = c.modn(groupBase).toString(base);
3167 c = c.idivn(groupBase);
3168
3169 if (!c.isZero()) {
3170 out = zeros[groupSize - r.length] + r + out;
3171 } else {
3172 out = r + out;
3173 }
3174 }
3175 if (this.isZero()) {
3176 out = '0' + out;
3177 }
3178 while (out.length % padding !== 0) {
3179 out = '0' + out;
3180 }
3181 if (this.negative !== 0) {
3182 out = '-' + out;
3183 }
3184 return out;
3185 }
3186
3187 assert(false, 'Base should be between 2 and 36');
3188 };
3189
3190 BN.prototype.toNumber = function toNumber () {
3191 var ret = this.words[0];
3192 if (this.length === 2) {
3193 ret += this.words[1] * 0x4000000;
3194 } else if (this.length === 3 && this.words[2] === 0x01) {
3195 // NOTE: at this stage it is known that the top bit is set
3196 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
3197 } else if (this.length > 2) {
3198 assert(false, 'Number can only safely store up to 53 bits');
3199 }
3200 return (this.negative !== 0) ? -ret : ret;
3201 };
3202
3203 BN.prototype.toJSON = function toJSON () {
3204 return this.toString(16);
3205 };
3206
3207 BN.prototype.toBuffer = function toBuffer (endian, length) {
3208 assert(typeof Buffer !== 'undefined');
3209 return this.toArrayLike(Buffer, endian, length);
3210 };
3211
3212 BN.prototype.toArray = function toArray (endian, length) {
3213 return this.toArrayLike(Array, endian, length);
3214 };
3215
3216 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
3217 var byteLength = this.byteLength();
3218 var reqLength = length || Math.max(1, byteLength);
3219 assert(byteLength <= reqLength, 'byte array longer than desired length');
3220 assert(reqLength > 0, 'Requested array length <= 0');
3221
3222 this.strip();
3223 var littleEndian = endian === 'le';
3224 var res = new ArrayType(reqLength);
3225
3226 var b, i;
3227 var q = this.clone();
3228 if (!littleEndian) {
3229 // Assume big-endian
3230 for (i = 0; i < reqLength - byteLength; i++) {
3231 res[i] = 0;
3232 }
3233
3234 for (i = 0; !q.isZero(); i++) {
3235 b = q.andln(0xff);
3236 q.iushrn(8);
3237
3238 res[reqLength - i - 1] = b;
3239 }
3240 } else {
3241 for (i = 0; !q.isZero(); i++) {
3242 b = q.andln(0xff);
3243 q.iushrn(8);
3244
3245 res[i] = b;
3246 }
3247
3248 for (; i < reqLength; i++) {
3249 res[i] = 0;
3250 }
3251 }
3252
3253 return res;
3254 };
3255
3256 if (Math.clz32) {
3257 BN.prototype._countBits = function _countBits (w) {
3258 return 32 - Math.clz32(w);
3259 };
3260 } else {
3261 BN.prototype._countBits = function _countBits (w) {
3262 var t = w;
3263 var r = 0;
3264 if (t >= 0x1000) {
3265 r += 13;
3266 t >>>= 13;
3267 }
3268 if (t >= 0x40) {
3269 r += 7;
3270 t >>>= 7;
3271 }
3272 if (t >= 0x8) {
3273 r += 4;
3274 t >>>= 4;
3275 }
3276 if (t >= 0x02) {
3277 r += 2;
3278 t >>>= 2;
3279 }
3280 return r + t;
3281 };
3282 }
3283
3284 BN.prototype._zeroBits = function _zeroBits (w) {
3285 // Short-cut
3286 if (w === 0) return 26;
3287
3288 var t = w;
3289 var r = 0;
3290 if ((t & 0x1fff) === 0) {
3291 r += 13;
3292 t >>>= 13;
3293 }
3294 if ((t & 0x7f) === 0) {
3295 r += 7;
3296 t >>>= 7;
3297 }
3298 if ((t & 0xf) === 0) {
3299 r += 4;
3300 t >>>= 4;
3301 }
3302 if ((t & 0x3) === 0) {
3303 r += 2;
3304 t >>>= 2;
3305 }
3306 if ((t & 0x1) === 0) {
3307 r++;
3308 }
3309 return r;
3310 };
3311
3312 // Return number of used bits in a BN
3313 BN.prototype.bitLength = function bitLength () {
3314 var w = this.words[this.length - 1];
3315 var hi = this._countBits(w);
3316 return (this.length - 1) * 26 + hi;
3317 };
3318
3319 function toBitArray (num) {
3320 var w = new Array(num.bitLength());
3321
3322 for (var bit = 0; bit < w.length; bit++) {
3323 var off = (bit / 26) | 0;
3324 var wbit = bit % 26;
3325
3326 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
3327 }
3328
3329 return w;
3330 }
3331
3332 // Number of trailing zero bits
3333 BN.prototype.zeroBits = function zeroBits () {
3334 if (this.isZero()) return 0;
3335
3336 var r = 0;
3337 for (var i = 0; i < this.length; i++) {
3338 var b = this._zeroBits(this.words[i]);
3339 r += b;
3340 if (b !== 26) break;
3341 }
3342 return r;
3343 };
3344
3345 BN.prototype.byteLength = function byteLength () {
3346 return Math.ceil(this.bitLength() / 8);
3347 };
3348
3349 BN.prototype.toTwos = function toTwos (width) {
3350 if (this.negative !== 0) {
3351 return this.abs().inotn(width).iaddn(1);
3352 }
3353 return this.clone();
3354 };
3355
3356 BN.prototype.fromTwos = function fromTwos (width) {
3357 if (this.testn(width - 1)) {
3358 return this.notn(width).iaddn(1).ineg();
3359 }
3360 return this.clone();
3361 };
3362
3363 BN.prototype.isNeg = function isNeg () {
3364 return this.negative !== 0;
3365 };
3366
3367 // Return negative clone of `this`
3368 BN.prototype.neg = function neg () {
3369 return this.clone().ineg();
3370 };
3371
3372 BN.prototype.ineg = function ineg () {
3373 if (!this.isZero()) {
3374 this.negative ^= 1;
3375 }
3376
3377 return this;
3378 };
3379
3380 // Or `num` with `this` in-place
3381 BN.prototype.iuor = function iuor (num) {
3382 while (this.length < num.length) {
3383 this.words[this.length++] = 0;
3384 }
3385
3386 for (var i = 0; i < num.length; i++) {
3387 this.words[i] = this.words[i] | num.words[i];
3388 }
3389
3390 return this.strip();
3391 };
3392
3393 BN.prototype.ior = function ior (num) {
3394 assert((this.negative | num.negative) === 0);
3395 return this.iuor(num);
3396 };
3397
3398 // Or `num` with `this`
3399 BN.prototype.or = function or (num) {
3400 if (this.length > num.length) return this.clone().ior(num);
3401 return num.clone().ior(this);
3402 };
3403
3404 BN.prototype.uor = function uor (num) {
3405 if (this.length > num.length) return this.clone().iuor(num);
3406 return num.clone().iuor(this);
3407 };
3408
3409 // And `num` with `this` in-place
3410 BN.prototype.iuand = function iuand (num) {
3411 // b = min-length(num, this)
3412 var b;
3413 if (this.length > num.length) {
3414 b = num;
3415 } else {
3416 b = this;
3417 }
3418
3419 for (var i = 0; i < b.length; i++) {
3420 this.words[i] = this.words[i] & num.words[i];
3421 }
3422
3423 this.length = b.length;
3424
3425 return this.strip();
3426 };
3427
3428 BN.prototype.iand = function iand (num) {
3429 assert((this.negative | num.negative) === 0);
3430 return this.iuand(num);
3431 };
3432
3433 // And `num` with `this`
3434 BN.prototype.and = function and (num) {
3435 if (this.length > num.length) return this.clone().iand(num);
3436 return num.clone().iand(this);
3437 };
3438
3439 BN.prototype.uand = function uand (num) {
3440 if (this.length > num.length) return this.clone().iuand(num);
3441 return num.clone().iuand(this);
3442 };
3443
3444 // Xor `num` with `this` in-place
3445 BN.prototype.iuxor = function iuxor (num) {
3446 // a.length > b.length
3447 var a;
3448 var b;
3449 if (this.length > num.length) {
3450 a = this;
3451 b = num;
3452 } else {
3453 a = num;
3454 b = this;
3455 }
3456
3457 for (var i = 0; i < b.length; i++) {
3458 this.words[i] = a.words[i] ^ b.words[i];
3459 }
3460
3461 if (this !== a) {
3462 for (; i < a.length; i++) {
3463 this.words[i] = a.words[i];
3464 }
3465 }
3466
3467 this.length = a.length;
3468
3469 return this.strip();
3470 };
3471
3472 BN.prototype.ixor = function ixor (num) {
3473 assert((this.negative | num.negative) === 0);
3474 return this.iuxor(num);
3475 };
3476
3477 // Xor `num` with `this`
3478 BN.prototype.xor = function xor (num) {
3479 if (this.length > num.length) return this.clone().ixor(num);
3480 return num.clone().ixor(this);
3481 };
3482
3483 BN.prototype.uxor = function uxor (num) {
3484 if (this.length > num.length) return this.clone().iuxor(num);
3485 return num.clone().iuxor(this);
3486 };
3487
3488 // Not ``this`` with ``width`` bitwidth
3489 BN.prototype.inotn = function inotn (width) {
3490 assert(typeof width === 'number' && width >= 0);
3491
3492 var bytesNeeded = Math.ceil(width / 26) | 0;
3493 var bitsLeft = width % 26;
3494
3495 // Extend the buffer with leading zeroes
3496 this._expand(bytesNeeded);
3497
3498 if (bitsLeft > 0) {
3499 bytesNeeded--;
3500 }
3501
3502 // Handle complete words
3503 for (var i = 0; i < bytesNeeded; i++) {
3504 this.words[i] = ~this.words[i] & 0x3ffffff;
3505 }
3506
3507 // Handle the residue
3508 if (bitsLeft > 0) {
3509 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
3510 }
3511
3512 // And remove leading zeroes
3513 return this.strip();
3514 };
3515
3516 BN.prototype.notn = function notn (width) {
3517 return this.clone().inotn(width);
3518 };
3519
3520 // Set `bit` of `this`
3521 BN.prototype.setn = function setn (bit, val) {
3522 assert(typeof bit === 'number' && bit >= 0);
3523
3524 var off = (bit / 26) | 0;
3525 var wbit = bit % 26;
3526
3527 this._expand(off + 1);
3528
3529 if (val) {
3530 this.words[off] = this.words[off] | (1 << wbit);
3531 } else {
3532 this.words[off] = this.words[off] & ~(1 << wbit);
3533 }
3534
3535 return this.strip();
3536 };
3537
3538 // Add `num` to `this` in-place
3539 BN.prototype.iadd = function iadd (num) {
3540 var r;
3541
3542 // negative + positive
3543 if (this.negative !== 0 && num.negative === 0) {
3544 this.negative = 0;
3545 r = this.isub(num);
3546 this.negative ^= 1;
3547 return this._normSign();
3548
3549 // positive + negative
3550 } else if (this.negative === 0 && num.negative !== 0) {
3551 num.negative = 0;
3552 r = this.isub(num);
3553 num.negative = 1;
3554 return r._normSign();
3555 }
3556
3557 // a.length > b.length
3558 var a, b;
3559 if (this.length > num.length) {
3560 a = this;
3561 b = num;
3562 } else {
3563 a = num;
3564 b = this;
3565 }
3566
3567 var carry = 0;
3568 for (var i = 0; i < b.length; i++) {
3569 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
3570 this.words[i] = r & 0x3ffffff;
3571 carry = r >>> 26;
3572 }
3573 for (; carry !== 0 && i < a.length; i++) {
3574 r = (a.words[i] | 0) + carry;
3575 this.words[i] = r & 0x3ffffff;
3576 carry = r >>> 26;
3577 }
3578
3579 this.length = a.length;
3580 if (carry !== 0) {
3581 this.words[this.length] = carry;
3582 this.length++;
3583 // Copy the rest of the words
3584 } else if (a !== this) {
3585 for (; i < a.length; i++) {
3586 this.words[i] = a.words[i];
3587 }
3588 }
3589
3590 return this;
3591 };
3592
3593 // Add `num` to `this`
3594 BN.prototype.add = function add (num) {
3595 var res;
3596 if (num.negative !== 0 && this.negative === 0) {
3597 num.negative = 0;
3598 res = this.sub(num);
3599 num.negative ^= 1;
3600 return res;
3601 } else if (num.negative === 0 && this.negative !== 0) {
3602 this.negative = 0;
3603 res = num.sub(this);
3604 this.negative = 1;
3605 return res;
3606 }
3607
3608 if (this.length > num.length) return this.clone().iadd(num);
3609
3610 return num.clone().iadd(this);
3611 };
3612
3613 // Subtract `num` from `this` in-place
3614 BN.prototype.isub = function isub (num) {
3615 // this - (-num) = this + num
3616 if (num.negative !== 0) {
3617 num.negative = 0;
3618 var r = this.iadd(num);
3619 num.negative = 1;
3620 return r._normSign();
3621
3622 // -this - num = -(this + num)
3623 } else if (this.negative !== 0) {
3624 this.negative = 0;
3625 this.iadd(num);
3626 this.negative = 1;
3627 return this._normSign();
3628 }
3629
3630 // At this point both numbers are positive
3631 var cmp = this.cmp(num);
3632
3633 // Optimization - zeroify
3634 if (cmp === 0) {
3635 this.negative = 0;
3636 this.length = 1;
3637 this.words[0] = 0;
3638 return this;
3639 }
3640
3641 // a > b
3642 var a, b;
3643 if (cmp > 0) {
3644 a = this;
3645 b = num;
3646 } else {
3647 a = num;
3648 b = this;
3649 }
3650
3651 var carry = 0;
3652 for (var i = 0; i < b.length; i++) {
3653 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
3654 carry = r >> 26;
3655 this.words[i] = r & 0x3ffffff;
3656 }
3657 for (; carry !== 0 && i < a.length; i++) {
3658 r = (a.words[i] | 0) + carry;
3659 carry = r >> 26;
3660 this.words[i] = r & 0x3ffffff;
3661 }
3662
3663 // Copy rest of the words
3664 if (carry === 0 && i < a.length && a !== this) {
3665 for (; i < a.length; i++) {
3666 this.words[i] = a.words[i];
3667 }
3668 }
3669
3670 this.length = Math.max(this.length, i);
3671
3672 if (a !== this) {
3673 this.negative = 1;
3674 }
3675
3676 return this.strip();
3677 };
3678
3679 // Subtract `num` from `this`
3680 BN.prototype.sub = function sub (num) {
3681 return this.clone().isub(num);
3682 };
3683
3684 function smallMulTo (self, num, out) {
3685 out.negative = num.negative ^ self.negative;
3686 var len = (self.length + num.length) | 0;
3687 out.length = len;
3688 len = (len - 1) | 0;
3689
3690 // Peel one iteration (compiler can't do it, because of code complexity)
3691 var a = self.words[0] | 0;
3692 var b = num.words[0] | 0;
3693 var r = a * b;
3694
3695 var lo = r & 0x3ffffff;
3696 var carry = (r / 0x4000000) | 0;
3697 out.words[0] = lo;
3698
3699 for (var k = 1; k < len; k++) {
3700 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
3701 // note that ncarry could be >= 0x3ffffff
3702 var ncarry = carry >>> 26;
3703 var rword = carry & 0x3ffffff;
3704 var maxJ = Math.min(k, num.length - 1);
3705 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
3706 var i = (k - j) | 0;
3707 a = self.words[i] | 0;
3708 b = num.words[j] | 0;
3709 r = a * b + rword;
3710 ncarry += (r / 0x4000000) | 0;
3711 rword = r & 0x3ffffff;
3712 }
3713 out.words[k] = rword | 0;
3714 carry = ncarry | 0;
3715 }
3716 if (carry !== 0) {
3717 out.words[k] = carry | 0;
3718 } else {
3719 out.length--;
3720 }
3721
3722 return out.strip();
3723 }
3724
3725 // TODO(indutny): it may be reasonable to omit it for users who don't need
3726 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
3727 // multiplication (like elliptic secp256k1).
3728 var comb10MulTo = function comb10MulTo (self, num, out) {
3729 var a = self.words;
3730 var b = num.words;
3731 var o = out.words;
3732 var c = 0;
3733 var lo;
3734 var mid;
3735 var hi;
3736 var a0 = a[0] | 0;
3737 var al0 = a0 & 0x1fff;
3738 var ah0 = a0 >>> 13;
3739 var a1 = a[1] | 0;
3740 var al1 = a1 & 0x1fff;
3741 var ah1 = a1 >>> 13;
3742 var a2 = a[2] | 0;
3743 var al2 = a2 & 0x1fff;
3744 var ah2 = a2 >>> 13;
3745 var a3 = a[3] | 0;
3746 var al3 = a3 & 0x1fff;
3747 var ah3 = a3 >>> 13;
3748 var a4 = a[4] | 0;
3749 var al4 = a4 & 0x1fff;
3750 var ah4 = a4 >>> 13;
3751 var a5 = a[5] | 0;
3752 var al5 = a5 & 0x1fff;
3753 var ah5 = a5 >>> 13;
3754 var a6 = a[6] | 0;
3755 var al6 = a6 & 0x1fff;
3756 var ah6 = a6 >>> 13;
3757 var a7 = a[7] | 0;
3758 var al7 = a7 & 0x1fff;
3759 var ah7 = a7 >>> 13;
3760 var a8 = a[8] | 0;
3761 var al8 = a8 & 0x1fff;
3762 var ah8 = a8 >>> 13;
3763 var a9 = a[9] | 0;
3764 var al9 = a9 & 0x1fff;
3765 var ah9 = a9 >>> 13;
3766 var b0 = b[0] | 0;
3767 var bl0 = b0 & 0x1fff;
3768 var bh0 = b0 >>> 13;
3769 var b1 = b[1] | 0;
3770 var bl1 = b1 & 0x1fff;
3771 var bh1 = b1 >>> 13;
3772 var b2 = b[2] | 0;
3773 var bl2 = b2 & 0x1fff;
3774 var bh2 = b2 >>> 13;
3775 var b3 = b[3] | 0;
3776 var bl3 = b3 & 0x1fff;
3777 var bh3 = b3 >>> 13;
3778 var b4 = b[4] | 0;
3779 var bl4 = b4 & 0x1fff;
3780 var bh4 = b4 >>> 13;
3781 var b5 = b[5] | 0;
3782 var bl5 = b5 & 0x1fff;
3783 var bh5 = b5 >>> 13;
3784 var b6 = b[6] | 0;
3785 var bl6 = b6 & 0x1fff;
3786 var bh6 = b6 >>> 13;
3787 var b7 = b[7] | 0;
3788 var bl7 = b7 & 0x1fff;
3789 var bh7 = b7 >>> 13;
3790 var b8 = b[8] | 0;
3791 var bl8 = b8 & 0x1fff;
3792 var bh8 = b8 >>> 13;
3793 var b9 = b[9] | 0;
3794 var bl9 = b9 & 0x1fff;
3795 var bh9 = b9 >>> 13;
3796
3797 out.negative = self.negative ^ num.negative;
3798 out.length = 19;
3799 /* k = 0 */
3800 lo = Math.imul(al0, bl0);
3801 mid = Math.imul(al0, bh0);
3802 mid = (mid + Math.imul(ah0, bl0)) | 0;
3803 hi = Math.imul(ah0, bh0);
3804 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3805 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
3806 w0 &= 0x3ffffff;
3807 /* k = 1 */
3808 lo = Math.imul(al1, bl0);
3809 mid = Math.imul(al1, bh0);
3810 mid = (mid + Math.imul(ah1, bl0)) | 0;
3811 hi = Math.imul(ah1, bh0);
3812 lo = (lo + Math.imul(al0, bl1)) | 0;
3813 mid = (mid + Math.imul(al0, bh1)) | 0;
3814 mid = (mid + Math.imul(ah0, bl1)) | 0;
3815 hi = (hi + Math.imul(ah0, bh1)) | 0;
3816 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3817 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
3818 w1 &= 0x3ffffff;
3819 /* k = 2 */
3820 lo = Math.imul(al2, bl0);
3821 mid = Math.imul(al2, bh0);
3822 mid = (mid + Math.imul(ah2, bl0)) | 0;
3823 hi = Math.imul(ah2, bh0);
3824 lo = (lo + Math.imul(al1, bl1)) | 0;
3825 mid = (mid + Math.imul(al1, bh1)) | 0;
3826 mid = (mid + Math.imul(ah1, bl1)) | 0;
3827 hi = (hi + Math.imul(ah1, bh1)) | 0;
3828 lo = (lo + Math.imul(al0, bl2)) | 0;
3829 mid = (mid + Math.imul(al0, bh2)) | 0;
3830 mid = (mid + Math.imul(ah0, bl2)) | 0;
3831 hi = (hi + Math.imul(ah0, bh2)) | 0;
3832 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3833 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
3834 w2 &= 0x3ffffff;
3835 /* k = 3 */
3836 lo = Math.imul(al3, bl0);
3837 mid = Math.imul(al3, bh0);
3838 mid = (mid + Math.imul(ah3, bl0)) | 0;
3839 hi = Math.imul(ah3, bh0);
3840 lo = (lo + Math.imul(al2, bl1)) | 0;
3841 mid = (mid + Math.imul(al2, bh1)) | 0;
3842 mid = (mid + Math.imul(ah2, bl1)) | 0;
3843 hi = (hi + Math.imul(ah2, bh1)) | 0;
3844 lo = (lo + Math.imul(al1, bl2)) | 0;
3845 mid = (mid + Math.imul(al1, bh2)) | 0;
3846 mid = (mid + Math.imul(ah1, bl2)) | 0;
3847 hi = (hi + Math.imul(ah1, bh2)) | 0;
3848 lo = (lo + Math.imul(al0, bl3)) | 0;
3849 mid = (mid + Math.imul(al0, bh3)) | 0;
3850 mid = (mid + Math.imul(ah0, bl3)) | 0;
3851 hi = (hi + Math.imul(ah0, bh3)) | 0;
3852 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3853 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
3854 w3 &= 0x3ffffff;
3855 /* k = 4 */
3856 lo = Math.imul(al4, bl0);
3857 mid = Math.imul(al4, bh0);
3858 mid = (mid + Math.imul(ah4, bl0)) | 0;
3859 hi = Math.imul(ah4, bh0);
3860 lo = (lo + Math.imul(al3, bl1)) | 0;
3861 mid = (mid + Math.imul(al3, bh1)) | 0;
3862 mid = (mid + Math.imul(ah3, bl1)) | 0;
3863 hi = (hi + Math.imul(ah3, bh1)) | 0;
3864 lo = (lo + Math.imul(al2, bl2)) | 0;
3865 mid = (mid + Math.imul(al2, bh2)) | 0;
3866 mid = (mid + Math.imul(ah2, bl2)) | 0;
3867 hi = (hi + Math.imul(ah2, bh2)) | 0;
3868 lo = (lo + Math.imul(al1, bl3)) | 0;
3869 mid = (mid + Math.imul(al1, bh3)) | 0;
3870 mid = (mid + Math.imul(ah1, bl3)) | 0;
3871 hi = (hi + Math.imul(ah1, bh3)) | 0;
3872 lo = (lo + Math.imul(al0, bl4)) | 0;
3873 mid = (mid + Math.imul(al0, bh4)) | 0;
3874 mid = (mid + Math.imul(ah0, bl4)) | 0;
3875 hi = (hi + Math.imul(ah0, bh4)) | 0;
3876 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3877 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
3878 w4 &= 0x3ffffff;
3879 /* k = 5 */
3880 lo = Math.imul(al5, bl0);
3881 mid = Math.imul(al5, bh0);
3882 mid = (mid + Math.imul(ah5, bl0)) | 0;
3883 hi = Math.imul(ah5, bh0);
3884 lo = (lo + Math.imul(al4, bl1)) | 0;
3885 mid = (mid + Math.imul(al4, bh1)) | 0;
3886 mid = (mid + Math.imul(ah4, bl1)) | 0;
3887 hi = (hi + Math.imul(ah4, bh1)) | 0;
3888 lo = (lo + Math.imul(al3, bl2)) | 0;
3889 mid = (mid + Math.imul(al3, bh2)) | 0;
3890 mid = (mid + Math.imul(ah3, bl2)) | 0;
3891 hi = (hi + Math.imul(ah3, bh2)) | 0;
3892 lo = (lo + Math.imul(al2, bl3)) | 0;
3893 mid = (mid + Math.imul(al2, bh3)) | 0;
3894 mid = (mid + Math.imul(ah2, bl3)) | 0;
3895 hi = (hi + Math.imul(ah2, bh3)) | 0;
3896 lo = (lo + Math.imul(al1, bl4)) | 0;
3897 mid = (mid + Math.imul(al1, bh4)) | 0;
3898 mid = (mid + Math.imul(ah1, bl4)) | 0;
3899 hi = (hi + Math.imul(ah1, bh4)) | 0;
3900 lo = (lo + Math.imul(al0, bl5)) | 0;
3901 mid = (mid + Math.imul(al0, bh5)) | 0;
3902 mid = (mid + Math.imul(ah0, bl5)) | 0;
3903 hi = (hi + Math.imul(ah0, bh5)) | 0;
3904 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3905 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
3906 w5 &= 0x3ffffff;
3907 /* k = 6 */
3908 lo = Math.imul(al6, bl0);
3909 mid = Math.imul(al6, bh0);
3910 mid = (mid + Math.imul(ah6, bl0)) | 0;
3911 hi = Math.imul(ah6, bh0);
3912 lo = (lo + Math.imul(al5, bl1)) | 0;
3913 mid = (mid + Math.imul(al5, bh1)) | 0;
3914 mid = (mid + Math.imul(ah5, bl1)) | 0;
3915 hi = (hi + Math.imul(ah5, bh1)) | 0;
3916 lo = (lo + Math.imul(al4, bl2)) | 0;
3917 mid = (mid + Math.imul(al4, bh2)) | 0;
3918 mid = (mid + Math.imul(ah4, bl2)) | 0;
3919 hi = (hi + Math.imul(ah4, bh2)) | 0;
3920 lo = (lo + Math.imul(al3, bl3)) | 0;
3921 mid = (mid + Math.imul(al3, bh3)) | 0;
3922 mid = (mid + Math.imul(ah3, bl3)) | 0;
3923 hi = (hi + Math.imul(ah3, bh3)) | 0;
3924 lo = (lo + Math.imul(al2, bl4)) | 0;
3925 mid = (mid + Math.imul(al2, bh4)) | 0;
3926 mid = (mid + Math.imul(ah2, bl4)) | 0;
3927 hi = (hi + Math.imul(ah2, bh4)) | 0;
3928 lo = (lo + Math.imul(al1, bl5)) | 0;
3929 mid = (mid + Math.imul(al1, bh5)) | 0;
3930 mid = (mid + Math.imul(ah1, bl5)) | 0;
3931 hi = (hi + Math.imul(ah1, bh5)) | 0;
3932 lo = (lo + Math.imul(al0, bl6)) | 0;
3933 mid = (mid + Math.imul(al0, bh6)) | 0;
3934 mid = (mid + Math.imul(ah0, bl6)) | 0;
3935 hi = (hi + Math.imul(ah0, bh6)) | 0;
3936 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3937 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
3938 w6 &= 0x3ffffff;
3939 /* k = 7 */
3940 lo = Math.imul(al7, bl0);
3941 mid = Math.imul(al7, bh0);
3942 mid = (mid + Math.imul(ah7, bl0)) | 0;
3943 hi = Math.imul(ah7, bh0);
3944 lo = (lo + Math.imul(al6, bl1)) | 0;
3945 mid = (mid + Math.imul(al6, bh1)) | 0;
3946 mid = (mid + Math.imul(ah6, bl1)) | 0;
3947 hi = (hi + Math.imul(ah6, bh1)) | 0;
3948 lo = (lo + Math.imul(al5, bl2)) | 0;
3949 mid = (mid + Math.imul(al5, bh2)) | 0;
3950 mid = (mid + Math.imul(ah5, bl2)) | 0;
3951 hi = (hi + Math.imul(ah5, bh2)) | 0;
3952 lo = (lo + Math.imul(al4, bl3)) | 0;
3953 mid = (mid + Math.imul(al4, bh3)) | 0;
3954 mid = (mid + Math.imul(ah4, bl3)) | 0;
3955 hi = (hi + Math.imul(ah4, bh3)) | 0;
3956 lo = (lo + Math.imul(al3, bl4)) | 0;
3957 mid = (mid + Math.imul(al3, bh4)) | 0;
3958 mid = (mid + Math.imul(ah3, bl4)) | 0;
3959 hi = (hi + Math.imul(ah3, bh4)) | 0;
3960 lo = (lo + Math.imul(al2, bl5)) | 0;
3961 mid = (mid + Math.imul(al2, bh5)) | 0;
3962 mid = (mid + Math.imul(ah2, bl5)) | 0;
3963 hi = (hi + Math.imul(ah2, bh5)) | 0;
3964 lo = (lo + Math.imul(al1, bl6)) | 0;
3965 mid = (mid + Math.imul(al1, bh6)) | 0;
3966 mid = (mid + Math.imul(ah1, bl6)) | 0;
3967 hi = (hi + Math.imul(ah1, bh6)) | 0;
3968 lo = (lo + Math.imul(al0, bl7)) | 0;
3969 mid = (mid + Math.imul(al0, bh7)) | 0;
3970 mid = (mid + Math.imul(ah0, bl7)) | 0;
3971 hi = (hi + Math.imul(ah0, bh7)) | 0;
3972 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
3973 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
3974 w7 &= 0x3ffffff;
3975 /* k = 8 */
3976 lo = Math.imul(al8, bl0);
3977 mid = Math.imul(al8, bh0);
3978 mid = (mid + Math.imul(ah8, bl0)) | 0;
3979 hi = Math.imul(ah8, bh0);
3980 lo = (lo + Math.imul(al7, bl1)) | 0;
3981 mid = (mid + Math.imul(al7, bh1)) | 0;
3982 mid = (mid + Math.imul(ah7, bl1)) | 0;
3983 hi = (hi + Math.imul(ah7, bh1)) | 0;
3984 lo = (lo + Math.imul(al6, bl2)) | 0;
3985 mid = (mid + Math.imul(al6, bh2)) | 0;
3986 mid = (mid + Math.imul(ah6, bl2)) | 0;
3987 hi = (hi + Math.imul(ah6, bh2)) | 0;
3988 lo = (lo + Math.imul(al5, bl3)) | 0;
3989 mid = (mid + Math.imul(al5, bh3)) | 0;
3990 mid = (mid + Math.imul(ah5, bl3)) | 0;
3991 hi = (hi + Math.imul(ah5, bh3)) | 0;
3992 lo = (lo + Math.imul(al4, bl4)) | 0;
3993 mid = (mid + Math.imul(al4, bh4)) | 0;
3994 mid = (mid + Math.imul(ah4, bl4)) | 0;
3995 hi = (hi + Math.imul(ah4, bh4)) | 0;
3996 lo = (lo + Math.imul(al3, bl5)) | 0;
3997 mid = (mid + Math.imul(al3, bh5)) | 0;
3998 mid = (mid + Math.imul(ah3, bl5)) | 0;
3999 hi = (hi + Math.imul(ah3, bh5)) | 0;
4000 lo = (lo + Math.imul(al2, bl6)) | 0;
4001 mid = (mid + Math.imul(al2, bh6)) | 0;
4002 mid = (mid + Math.imul(ah2, bl6)) | 0;
4003 hi = (hi + Math.imul(ah2, bh6)) | 0;
4004 lo = (lo + Math.imul(al1, bl7)) | 0;
4005 mid = (mid + Math.imul(al1, bh7)) | 0;
4006 mid = (mid + Math.imul(ah1, bl7)) | 0;
4007 hi = (hi + Math.imul(ah1, bh7)) | 0;
4008 lo = (lo + Math.imul(al0, bl8)) | 0;
4009 mid = (mid + Math.imul(al0, bh8)) | 0;
4010 mid = (mid + Math.imul(ah0, bl8)) | 0;
4011 hi = (hi + Math.imul(ah0, bh8)) | 0;
4012 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4013 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
4014 w8 &= 0x3ffffff;
4015 /* k = 9 */
4016 lo = Math.imul(al9, bl0);
4017 mid = Math.imul(al9, bh0);
4018 mid = (mid + Math.imul(ah9, bl0)) | 0;
4019 hi = Math.imul(ah9, bh0);
4020 lo = (lo + Math.imul(al8, bl1)) | 0;
4021 mid = (mid + Math.imul(al8, bh1)) | 0;
4022 mid = (mid + Math.imul(ah8, bl1)) | 0;
4023 hi = (hi + Math.imul(ah8, bh1)) | 0;
4024 lo = (lo + Math.imul(al7, bl2)) | 0;
4025 mid = (mid + Math.imul(al7, bh2)) | 0;
4026 mid = (mid + Math.imul(ah7, bl2)) | 0;
4027 hi = (hi + Math.imul(ah7, bh2)) | 0;
4028 lo = (lo + Math.imul(al6, bl3)) | 0;
4029 mid = (mid + Math.imul(al6, bh3)) | 0;
4030 mid = (mid + Math.imul(ah6, bl3)) | 0;
4031 hi = (hi + Math.imul(ah6, bh3)) | 0;
4032 lo = (lo + Math.imul(al5, bl4)) | 0;
4033 mid = (mid + Math.imul(al5, bh4)) | 0;
4034 mid = (mid + Math.imul(ah5, bl4)) | 0;
4035 hi = (hi + Math.imul(ah5, bh4)) | 0;
4036 lo = (lo + Math.imul(al4, bl5)) | 0;
4037 mid = (mid + Math.imul(al4, bh5)) | 0;
4038 mid = (mid + Math.imul(ah4, bl5)) | 0;
4039 hi = (hi + Math.imul(ah4, bh5)) | 0;
4040 lo = (lo + Math.imul(al3, bl6)) | 0;
4041 mid = (mid + Math.imul(al3, bh6)) | 0;
4042 mid = (mid + Math.imul(ah3, bl6)) | 0;
4043 hi = (hi + Math.imul(ah3, bh6)) | 0;
4044 lo = (lo + Math.imul(al2, bl7)) | 0;
4045 mid = (mid + Math.imul(al2, bh7)) | 0;
4046 mid = (mid + Math.imul(ah2, bl7)) | 0;
4047 hi = (hi + Math.imul(ah2, bh7)) | 0;
4048 lo = (lo + Math.imul(al1, bl8)) | 0;
4049 mid = (mid + Math.imul(al1, bh8)) | 0;
4050 mid = (mid + Math.imul(ah1, bl8)) | 0;
4051 hi = (hi + Math.imul(ah1, bh8)) | 0;
4052 lo = (lo + Math.imul(al0, bl9)) | 0;
4053 mid = (mid + Math.imul(al0, bh9)) | 0;
4054 mid = (mid + Math.imul(ah0, bl9)) | 0;
4055 hi = (hi + Math.imul(ah0, bh9)) | 0;
4056 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4057 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
4058 w9 &= 0x3ffffff;
4059 /* k = 10 */
4060 lo = Math.imul(al9, bl1);
4061 mid = Math.imul(al9, bh1);
4062 mid = (mid + Math.imul(ah9, bl1)) | 0;
4063 hi = Math.imul(ah9, bh1);
4064 lo = (lo + Math.imul(al8, bl2)) | 0;
4065 mid = (mid + Math.imul(al8, bh2)) | 0;
4066 mid = (mid + Math.imul(ah8, bl2)) | 0;
4067 hi = (hi + Math.imul(ah8, bh2)) | 0;
4068 lo = (lo + Math.imul(al7, bl3)) | 0;
4069 mid = (mid + Math.imul(al7, bh3)) | 0;
4070 mid = (mid + Math.imul(ah7, bl3)) | 0;
4071 hi = (hi + Math.imul(ah7, bh3)) | 0;
4072 lo = (lo + Math.imul(al6, bl4)) | 0;
4073 mid = (mid + Math.imul(al6, bh4)) | 0;
4074 mid = (mid + Math.imul(ah6, bl4)) | 0;
4075 hi = (hi + Math.imul(ah6, bh4)) | 0;
4076 lo = (lo + Math.imul(al5, bl5)) | 0;
4077 mid = (mid + Math.imul(al5, bh5)) | 0;
4078 mid = (mid + Math.imul(ah5, bl5)) | 0;
4079 hi = (hi + Math.imul(ah5, bh5)) | 0;
4080 lo = (lo + Math.imul(al4, bl6)) | 0;
4081 mid = (mid + Math.imul(al4, bh6)) | 0;
4082 mid = (mid + Math.imul(ah4, bl6)) | 0;
4083 hi = (hi + Math.imul(ah4, bh6)) | 0;
4084 lo = (lo + Math.imul(al3, bl7)) | 0;
4085 mid = (mid + Math.imul(al3, bh7)) | 0;
4086 mid = (mid + Math.imul(ah3, bl7)) | 0;
4087 hi = (hi + Math.imul(ah3, bh7)) | 0;
4088 lo = (lo + Math.imul(al2, bl8)) | 0;
4089 mid = (mid + Math.imul(al2, bh8)) | 0;
4090 mid = (mid + Math.imul(ah2, bl8)) | 0;
4091 hi = (hi + Math.imul(ah2, bh8)) | 0;
4092 lo = (lo + Math.imul(al1, bl9)) | 0;
4093 mid = (mid + Math.imul(al1, bh9)) | 0;
4094 mid = (mid + Math.imul(ah1, bl9)) | 0;
4095 hi = (hi + Math.imul(ah1, bh9)) | 0;
4096 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4097 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
4098 w10 &= 0x3ffffff;
4099 /* k = 11 */
4100 lo = Math.imul(al9, bl2);
4101 mid = Math.imul(al9, bh2);
4102 mid = (mid + Math.imul(ah9, bl2)) | 0;
4103 hi = Math.imul(ah9, bh2);
4104 lo = (lo + Math.imul(al8, bl3)) | 0;
4105 mid = (mid + Math.imul(al8, bh3)) | 0;
4106 mid = (mid + Math.imul(ah8, bl3)) | 0;
4107 hi = (hi + Math.imul(ah8, bh3)) | 0;
4108 lo = (lo + Math.imul(al7, bl4)) | 0;
4109 mid = (mid + Math.imul(al7, bh4)) | 0;
4110 mid = (mid + Math.imul(ah7, bl4)) | 0;
4111 hi = (hi + Math.imul(ah7, bh4)) | 0;
4112 lo = (lo + Math.imul(al6, bl5)) | 0;
4113 mid = (mid + Math.imul(al6, bh5)) | 0;
4114 mid = (mid + Math.imul(ah6, bl5)) | 0;
4115 hi = (hi + Math.imul(ah6, bh5)) | 0;
4116 lo = (lo + Math.imul(al5, bl6)) | 0;
4117 mid = (mid + Math.imul(al5, bh6)) | 0;
4118 mid = (mid + Math.imul(ah5, bl6)) | 0;
4119 hi = (hi + Math.imul(ah5, bh6)) | 0;
4120 lo = (lo + Math.imul(al4, bl7)) | 0;
4121 mid = (mid + Math.imul(al4, bh7)) | 0;
4122 mid = (mid + Math.imul(ah4, bl7)) | 0;
4123 hi = (hi + Math.imul(ah4, bh7)) | 0;
4124 lo = (lo + Math.imul(al3, bl8)) | 0;
4125 mid = (mid + Math.imul(al3, bh8)) | 0;
4126 mid = (mid + Math.imul(ah3, bl8)) | 0;
4127 hi = (hi + Math.imul(ah3, bh8)) | 0;
4128 lo = (lo + Math.imul(al2, bl9)) | 0;
4129 mid = (mid + Math.imul(al2, bh9)) | 0;
4130 mid = (mid + Math.imul(ah2, bl9)) | 0;
4131 hi = (hi + Math.imul(ah2, bh9)) | 0;
4132 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4133 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
4134 w11 &= 0x3ffffff;
4135 /* k = 12 */
4136 lo = Math.imul(al9, bl3);
4137 mid = Math.imul(al9, bh3);
4138 mid = (mid + Math.imul(ah9, bl3)) | 0;
4139 hi = Math.imul(ah9, bh3);
4140 lo = (lo + Math.imul(al8, bl4)) | 0;
4141 mid = (mid + Math.imul(al8, bh4)) | 0;
4142 mid = (mid + Math.imul(ah8, bl4)) | 0;
4143 hi = (hi + Math.imul(ah8, bh4)) | 0;
4144 lo = (lo + Math.imul(al7, bl5)) | 0;
4145 mid = (mid + Math.imul(al7, bh5)) | 0;
4146 mid = (mid + Math.imul(ah7, bl5)) | 0;
4147 hi = (hi + Math.imul(ah7, bh5)) | 0;
4148 lo = (lo + Math.imul(al6, bl6)) | 0;
4149 mid = (mid + Math.imul(al6, bh6)) | 0;
4150 mid = (mid + Math.imul(ah6, bl6)) | 0;
4151 hi = (hi + Math.imul(ah6, bh6)) | 0;
4152 lo = (lo + Math.imul(al5, bl7)) | 0;
4153 mid = (mid + Math.imul(al5, bh7)) | 0;
4154 mid = (mid + Math.imul(ah5, bl7)) | 0;
4155 hi = (hi + Math.imul(ah5, bh7)) | 0;
4156 lo = (lo + Math.imul(al4, bl8)) | 0;
4157 mid = (mid + Math.imul(al4, bh8)) | 0;
4158 mid = (mid + Math.imul(ah4, bl8)) | 0;
4159 hi = (hi + Math.imul(ah4, bh8)) | 0;
4160 lo = (lo + Math.imul(al3, bl9)) | 0;
4161 mid = (mid + Math.imul(al3, bh9)) | 0;
4162 mid = (mid + Math.imul(ah3, bl9)) | 0;
4163 hi = (hi + Math.imul(ah3, bh9)) | 0;
4164 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4165 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
4166 w12 &= 0x3ffffff;
4167 /* k = 13 */
4168 lo = Math.imul(al9, bl4);
4169 mid = Math.imul(al9, bh4);
4170 mid = (mid + Math.imul(ah9, bl4)) | 0;
4171 hi = Math.imul(ah9, bh4);
4172 lo = (lo + Math.imul(al8, bl5)) | 0;
4173 mid = (mid + Math.imul(al8, bh5)) | 0;
4174 mid = (mid + Math.imul(ah8, bl5)) | 0;
4175 hi = (hi + Math.imul(ah8, bh5)) | 0;
4176 lo = (lo + Math.imul(al7, bl6)) | 0;
4177 mid = (mid + Math.imul(al7, bh6)) | 0;
4178 mid = (mid + Math.imul(ah7, bl6)) | 0;
4179 hi = (hi + Math.imul(ah7, bh6)) | 0;
4180 lo = (lo + Math.imul(al6, bl7)) | 0;
4181 mid = (mid + Math.imul(al6, bh7)) | 0;
4182 mid = (mid + Math.imul(ah6, bl7)) | 0;
4183 hi = (hi + Math.imul(ah6, bh7)) | 0;
4184 lo = (lo + Math.imul(al5, bl8)) | 0;
4185 mid = (mid + Math.imul(al5, bh8)) | 0;
4186 mid = (mid + Math.imul(ah5, bl8)) | 0;
4187 hi = (hi + Math.imul(ah5, bh8)) | 0;
4188 lo = (lo + Math.imul(al4, bl9)) | 0;
4189 mid = (mid + Math.imul(al4, bh9)) | 0;
4190 mid = (mid + Math.imul(ah4, bl9)) | 0;
4191 hi = (hi + Math.imul(ah4, bh9)) | 0;
4192 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4193 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
4194 w13 &= 0x3ffffff;
4195 /* k = 14 */
4196 lo = Math.imul(al9, bl5);
4197 mid = Math.imul(al9, bh5);
4198 mid = (mid + Math.imul(ah9, bl5)) | 0;
4199 hi = Math.imul(ah9, bh5);
4200 lo = (lo + Math.imul(al8, bl6)) | 0;
4201 mid = (mid + Math.imul(al8, bh6)) | 0;
4202 mid = (mid + Math.imul(ah8, bl6)) | 0;
4203 hi = (hi + Math.imul(ah8, bh6)) | 0;
4204 lo = (lo + Math.imul(al7, bl7)) | 0;
4205 mid = (mid + Math.imul(al7, bh7)) | 0;
4206 mid = (mid + Math.imul(ah7, bl7)) | 0;
4207 hi = (hi + Math.imul(ah7, bh7)) | 0;
4208 lo = (lo + Math.imul(al6, bl8)) | 0;
4209 mid = (mid + Math.imul(al6, bh8)) | 0;
4210 mid = (mid + Math.imul(ah6, bl8)) | 0;
4211 hi = (hi + Math.imul(ah6, bh8)) | 0;
4212 lo = (lo + Math.imul(al5, bl9)) | 0;
4213 mid = (mid + Math.imul(al5, bh9)) | 0;
4214 mid = (mid + Math.imul(ah5, bl9)) | 0;
4215 hi = (hi + Math.imul(ah5, bh9)) | 0;
4216 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4217 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
4218 w14 &= 0x3ffffff;
4219 /* k = 15 */
4220 lo = Math.imul(al9, bl6);
4221 mid = Math.imul(al9, bh6);
4222 mid = (mid + Math.imul(ah9, bl6)) | 0;
4223 hi = Math.imul(ah9, bh6);
4224 lo = (lo + Math.imul(al8, bl7)) | 0;
4225 mid = (mid + Math.imul(al8, bh7)) | 0;
4226 mid = (mid + Math.imul(ah8, bl7)) | 0;
4227 hi = (hi + Math.imul(ah8, bh7)) | 0;
4228 lo = (lo + Math.imul(al7, bl8)) | 0;
4229 mid = (mid + Math.imul(al7, bh8)) | 0;
4230 mid = (mid + Math.imul(ah7, bl8)) | 0;
4231 hi = (hi + Math.imul(ah7, bh8)) | 0;
4232 lo = (lo + Math.imul(al6, bl9)) | 0;
4233 mid = (mid + Math.imul(al6, bh9)) | 0;
4234 mid = (mid + Math.imul(ah6, bl9)) | 0;
4235 hi = (hi + Math.imul(ah6, bh9)) | 0;
4236 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4237 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
4238 w15 &= 0x3ffffff;
4239 /* k = 16 */
4240 lo = Math.imul(al9, bl7);
4241 mid = Math.imul(al9, bh7);
4242 mid = (mid + Math.imul(ah9, bl7)) | 0;
4243 hi = Math.imul(ah9, bh7);
4244 lo = (lo + Math.imul(al8, bl8)) | 0;
4245 mid = (mid + Math.imul(al8, bh8)) | 0;
4246 mid = (mid + Math.imul(ah8, bl8)) | 0;
4247 hi = (hi + Math.imul(ah8, bh8)) | 0;
4248 lo = (lo + Math.imul(al7, bl9)) | 0;
4249 mid = (mid + Math.imul(al7, bh9)) | 0;
4250 mid = (mid + Math.imul(ah7, bl9)) | 0;
4251 hi = (hi + Math.imul(ah7, bh9)) | 0;
4252 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4253 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
4254 w16 &= 0x3ffffff;
4255 /* k = 17 */
4256 lo = Math.imul(al9, bl8);
4257 mid = Math.imul(al9, bh8);
4258 mid = (mid + Math.imul(ah9, bl8)) | 0;
4259 hi = Math.imul(ah9, bh8);
4260 lo = (lo + Math.imul(al8, bl9)) | 0;
4261 mid = (mid + Math.imul(al8, bh9)) | 0;
4262 mid = (mid + Math.imul(ah8, bl9)) | 0;
4263 hi = (hi + Math.imul(ah8, bh9)) | 0;
4264 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4265 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
4266 w17 &= 0x3ffffff;
4267 /* k = 18 */
4268 lo = Math.imul(al9, bl9);
4269 mid = Math.imul(al9, bh9);
4270 mid = (mid + Math.imul(ah9, bl9)) | 0;
4271 hi = Math.imul(ah9, bh9);
4272 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
4273 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
4274 w18 &= 0x3ffffff;
4275 o[0] = w0;
4276 o[1] = w1;
4277 o[2] = w2;
4278 o[3] = w3;
4279 o[4] = w4;
4280 o[5] = w5;
4281 o[6] = w6;
4282 o[7] = w7;
4283 o[8] = w8;
4284 o[9] = w9;
4285 o[10] = w10;
4286 o[11] = w11;
4287 o[12] = w12;
4288 o[13] = w13;
4289 o[14] = w14;
4290 o[15] = w15;
4291 o[16] = w16;
4292 o[17] = w17;
4293 o[18] = w18;
4294 if (c !== 0) {
4295 o[19] = c;
4296 out.length++;
4297 }
4298 return out;
4299 };
4300
4301 // Polyfill comb
4302 if (!Math.imul) {
4303 comb10MulTo = smallMulTo;
4304 }
4305
4306 function bigMulTo (self, num, out) {
4307 out.negative = num.negative ^ self.negative;
4308 out.length = self.length + num.length;
4309
4310 var carry = 0;
4311 var hncarry = 0;
4312 for (var k = 0; k < out.length - 1; k++) {
4313 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
4314 // note that ncarry could be >= 0x3ffffff
4315 var ncarry = hncarry;
4316 hncarry = 0;
4317 var rword = carry & 0x3ffffff;
4318 var maxJ = Math.min(k, num.length - 1);
4319 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
4320 var i = k - j;
4321 var a = self.words[i] | 0;
4322 var b = num.words[j] | 0;
4323 var r = a * b;
4324
4325 var lo = r & 0x3ffffff;
4326 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
4327 lo = (lo + rword) | 0;
4328 rword = lo & 0x3ffffff;
4329 ncarry = (ncarry + (lo >>> 26)) | 0;
4330
4331 hncarry += ncarry >>> 26;
4332 ncarry &= 0x3ffffff;
4333 }
4334 out.words[k] = rword;
4335 carry = ncarry;
4336 ncarry = hncarry;
4337 }
4338 if (carry !== 0) {
4339 out.words[k] = carry;
4340 } else {
4341 out.length--;
4342 }
4343
4344 return out.strip();
4345 }
4346
4347 function jumboMulTo (self, num, out) {
4348 var fftm = new FFTM();
4349 return fftm.mulp(self, num, out);
4350 }
4351
4352 BN.prototype.mulTo = function mulTo (num, out) {
4353 var res;
4354 var len = this.length + num.length;
4355 if (this.length === 10 && num.length === 10) {
4356 res = comb10MulTo(this, num, out);
4357 } else if (len < 63) {
4358 res = smallMulTo(this, num, out);
4359 } else if (len < 1024) {
4360 res = bigMulTo(this, num, out);
4361 } else {
4362 res = jumboMulTo(this, num, out);
4363 }
4364
4365 return res;
4366 };
4367
4368 // Cooley-Tukey algorithm for FFT
4369 // slightly revisited to rely on looping instead of recursion
4370
4371 function FFTM (x, y) {
4372 this.x = x;
4373 this.y = y;
4374 }
4375
4376 FFTM.prototype.makeRBT = function makeRBT (N) {
4377 var t = new Array(N);
4378 var l = BN.prototype._countBits(N) - 1;
4379 for (var i = 0; i < N; i++) {
4380 t[i] = this.revBin(i, l, N);
4381 }
4382
4383 return t;
4384 };
4385
4386 // Returns binary-reversed representation of `x`
4387 FFTM.prototype.revBin = function revBin (x, l, N) {
4388 if (x === 0 || x === N - 1) return x;
4389
4390 var rb = 0;
4391 for (var i = 0; i < l; i++) {
4392 rb |= (x & 1) << (l - i - 1);
4393 x >>= 1;
4394 }
4395
4396 return rb;
4397 };
4398
4399 // Performs "tweedling" phase, therefore 'emulating'
4400 // behaviour of the recursive algorithm
4401 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
4402 for (var i = 0; i < N; i++) {
4403 rtws[i] = rws[rbt[i]];
4404 itws[i] = iws[rbt[i]];
4405 }
4406 };
4407
4408 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
4409 this.permute(rbt, rws, iws, rtws, itws, N);
4410
4411 for (var s = 1; s < N; s <<= 1) {
4412 var l = s << 1;
4413
4414 var rtwdf = Math.cos(2 * Math.PI / l);
4415 var itwdf = Math.sin(2 * Math.PI / l);
4416
4417 for (var p = 0; p < N; p += l) {
4418 var rtwdf_ = rtwdf;
4419 var itwdf_ = itwdf;
4420
4421 for (var j = 0; j < s; j++) {
4422 var re = rtws[p + j];
4423 var ie = itws[p + j];
4424
4425 var ro = rtws[p + j + s];
4426 var io = itws[p + j + s];
4427
4428 var rx = rtwdf_ * ro - itwdf_ * io;
4429
4430 io = rtwdf_ * io + itwdf_ * ro;
4431 ro = rx;
4432
4433 rtws[p + j] = re + ro;
4434 itws[p + j] = ie + io;
4435
4436 rtws[p + j + s] = re - ro;
4437 itws[p + j + s] = ie - io;
4438
4439 /* jshint maxdepth : false */
4440 if (j !== l) {
4441 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
4442
4443 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
4444 rtwdf_ = rx;
4445 }
4446 }
4447 }
4448 }
4449 };
4450
4451 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
4452 var N = Math.max(m, n) | 1;
4453 var odd = N & 1;
4454 var i = 0;
4455 for (N = N / 2 | 0; N; N = N >>> 1) {
4456 i++;
4457 }
4458
4459 return 1 << i + 1 + odd;
4460 };
4461
4462 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
4463 if (N <= 1) return;
4464
4465 for (var i = 0; i < N / 2; i++) {
4466 var t = rws[i];
4467
4468 rws[i] = rws[N - i - 1];
4469 rws[N - i - 1] = t;
4470
4471 t = iws[i];
4472
4473 iws[i] = -iws[N - i - 1];
4474 iws[N - i - 1] = -t;
4475 }
4476 };
4477
4478 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
4479 var carry = 0;
4480 for (var i = 0; i < N / 2; i++) {
4481 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
4482 Math.round(ws[2 * i] / N) +
4483 carry;
4484
4485 ws[i] = w & 0x3ffffff;
4486
4487 if (w < 0x4000000) {
4488 carry = 0;
4489 } else {
4490 carry = w / 0x4000000 | 0;
4491 }
4492 }
4493
4494 return ws;
4495 };
4496
4497 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
4498 var carry = 0;
4499 for (var i = 0; i < len; i++) {
4500 carry = carry + (ws[i] | 0);
4501
4502 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
4503 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
4504 }
4505
4506 // Pad with zeroes
4507 for (i = 2 * len; i < N; ++i) {
4508 rws[i] = 0;
4509 }
4510
4511 assert(carry === 0);
4512 assert((carry & ~0x1fff) === 0);
4513 };
4514
4515 FFTM.prototype.stub = function stub (N) {
4516 var ph = new Array(N);
4517 for (var i = 0; i < N; i++) {
4518 ph[i] = 0;
4519 }
4520
4521 return ph;
4522 };
4523
4524 FFTM.prototype.mulp = function mulp (x, y, out) {
4525 var N = 2 * this.guessLen13b(x.length, y.length);
4526
4527 var rbt = this.makeRBT(N);
4528
4529 var _ = this.stub(N);
4530
4531 var rws = new Array(N);
4532 var rwst = new Array(N);
4533 var iwst = new Array(N);
4534
4535 var nrws = new Array(N);
4536 var nrwst = new Array(N);
4537 var niwst = new Array(N);
4538
4539 var rmws = out.words;
4540 rmws.length = N;
4541
4542 this.convert13b(x.words, x.length, rws, N);
4543 this.convert13b(y.words, y.length, nrws, N);
4544
4545 this.transform(rws, _, rwst, iwst, N, rbt);
4546 this.transform(nrws, _, nrwst, niwst, N, rbt);
4547
4548 for (var i = 0; i < N; i++) {
4549 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
4550 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
4551 rwst[i] = rx;
4552 }
4553
4554 this.conjugate(rwst, iwst, N);
4555 this.transform(rwst, iwst, rmws, _, N, rbt);
4556 this.conjugate(rmws, _, N);
4557 this.normalize13b(rmws, N);
4558
4559 out.negative = x.negative ^ y.negative;
4560 out.length = x.length + y.length;
4561 return out.strip();
4562 };
4563
4564 // Multiply `this` by `num`
4565 BN.prototype.mul = function mul (num) {
4566 var out = new BN(null);
4567 out.words = new Array(this.length + num.length);
4568 return this.mulTo(num, out);
4569 };
4570
4571 // Multiply employing FFT
4572 BN.prototype.mulf = function mulf (num) {
4573 var out = new BN(null);
4574 out.words = new Array(this.length + num.length);
4575 return jumboMulTo(this, num, out);
4576 };
4577
4578 // In-place Multiplication
4579 BN.prototype.imul = function imul (num) {
4580 return this.clone().mulTo(num, this);
4581 };
4582
4583 BN.prototype.imuln = function imuln (num) {
4584 assert(typeof num === 'number');
4585 assert(num < 0x4000000);
4586
4587 // Carry
4588 var carry = 0;
4589 for (var i = 0; i < this.length; i++) {
4590 var w = (this.words[i] | 0) * num;
4591 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
4592 carry >>= 26;
4593 carry += (w / 0x4000000) | 0;
4594 // NOTE: lo is 27bit maximum
4595 carry += lo >>> 26;
4596 this.words[i] = lo & 0x3ffffff;
4597 }
4598
4599 if (carry !== 0) {
4600 this.words[i] = carry;
4601 this.length++;
4602 }
4603
4604 return this;
4605 };
4606
4607 BN.prototype.muln = function muln (num) {
4608 return this.clone().imuln(num);
4609 };
4610
4611 // `this` * `this`
4612 BN.prototype.sqr = function sqr () {
4613 return this.mul(this);
4614 };
4615
4616 // `this` * `this` in-place
4617 BN.prototype.isqr = function isqr () {
4618 return this.imul(this.clone());
4619 };
4620
4621 // Math.pow(`this`, `num`)
4622 BN.prototype.pow = function pow (num) {
4623 var w = toBitArray(num);
4624 if (w.length === 0) return new BN(1);
4625
4626 // Skip leading zeroes
4627 var res = this;
4628 for (var i = 0; i < w.length; i++, res = res.sqr()) {
4629 if (w[i] !== 0) break;
4630 }
4631
4632 if (++i < w.length) {
4633 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
4634 if (w[i] === 0) continue;
4635
4636 res = res.mul(q);
4637 }
4638 }
4639
4640 return res;
4641 };
4642
4643 // Shift-left in-place
4644 BN.prototype.iushln = function iushln (bits) {
4645 assert(typeof bits === 'number' && bits >= 0);
4646 var r = bits % 26;
4647 var s = (bits - r) / 26;
4648 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
4649 var i;
4650
4651 if (r !== 0) {
4652 var carry = 0;
4653
4654 for (i = 0; i < this.length; i++) {
4655 var newCarry = this.words[i] & carryMask;
4656 var c = ((this.words[i] | 0) - newCarry) << r;
4657 this.words[i] = c | carry;
4658 carry = newCarry >>> (26 - r);
4659 }
4660
4661 if (carry) {
4662 this.words[i] = carry;
4663 this.length++;
4664 }
4665 }
4666
4667 if (s !== 0) {
4668 for (i = this.length - 1; i >= 0; i--) {
4669 this.words[i + s] = this.words[i];
4670 }
4671
4672 for (i = 0; i < s; i++) {
4673 this.words[i] = 0;
4674 }
4675
4676 this.length += s;
4677 }
4678
4679 return this.strip();
4680 };
4681
4682 BN.prototype.ishln = function ishln (bits) {
4683 // TODO(indutny): implement me
4684 assert(this.negative === 0);
4685 return this.iushln(bits);
4686 };
4687
4688 // Shift-right in-place
4689 // NOTE: `hint` is a lowest bit before trailing zeroes
4690 // NOTE: if `extended` is present - it will be filled with destroyed bits
4691 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
4692 assert(typeof bits === 'number' && bits >= 0);
4693 var h;
4694 if (hint) {
4695 h = (hint - (hint % 26)) / 26;
4696 } else {
4697 h = 0;
4698 }
4699
4700 var r = bits % 26;
4701 var s = Math.min((bits - r) / 26, this.length);
4702 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
4703 var maskedWords = extended;
4704
4705 h -= s;
4706 h = Math.max(0, h);
4707
4708 // Extended mode, copy masked part
4709 if (maskedWords) {
4710 for (var i = 0; i < s; i++) {
4711 maskedWords.words[i] = this.words[i];
4712 }
4713 maskedWords.length = s;
4714 }
4715
4716 if (s === 0) {
4717 // No-op, we should not move anything at all
4718 } else if (this.length > s) {
4719 this.length -= s;
4720 for (i = 0; i < this.length; i++) {
4721 this.words[i] = this.words[i + s];
4722 }
4723 } else {
4724 this.words[0] = 0;
4725 this.length = 1;
4726 }
4727
4728 var carry = 0;
4729 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
4730 var word = this.words[i] | 0;
4731 this.words[i] = (carry << (26 - r)) | (word >>> r);
4732 carry = word & mask;
4733 }
4734
4735 // Push carried bits as a mask
4736 if (maskedWords && carry !== 0) {
4737 maskedWords.words[maskedWords.length++] = carry;
4738 }
4739
4740 if (this.length === 0) {
4741 this.words[0] = 0;
4742 this.length = 1;
4743 }
4744
4745 return this.strip();
4746 };
4747
4748 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
4749 // TODO(indutny): implement me
4750 assert(this.negative === 0);
4751 return this.iushrn(bits, hint, extended);
4752 };
4753
4754 // Shift-left
4755 BN.prototype.shln = function shln (bits) {
4756 return this.clone().ishln(bits);
4757 };
4758
4759 BN.prototype.ushln = function ushln (bits) {
4760 return this.clone().iushln(bits);
4761 };
4762
4763 // Shift-right
4764 BN.prototype.shrn = function shrn (bits) {
4765 return this.clone().ishrn(bits);
4766 };
4767
4768 BN.prototype.ushrn = function ushrn (bits) {
4769 return this.clone().iushrn(bits);
4770 };
4771
4772 // Test if n bit is set
4773 BN.prototype.testn = function testn (bit) {
4774 assert(typeof bit === 'number' && bit >= 0);
4775 var r = bit % 26;
4776 var s = (bit - r) / 26;
4777 var q = 1 << r;
4778
4779 // Fast case: bit is much higher than all existing words
4780 if (this.length <= s) return false;
4781
4782 // Check bit and return
4783 var w = this.words[s];
4784
4785 return !!(w & q);
4786 };
4787
4788 // Return only lowers bits of number (in-place)
4789 BN.prototype.imaskn = function imaskn (bits) {
4790 assert(typeof bits === 'number' && bits >= 0);
4791 var r = bits % 26;
4792 var s = (bits - r) / 26;
4793
4794 assert(this.negative === 0, 'imaskn works only with positive numbers');
4795
4796 if (this.length <= s) {
4797 return this;
4798 }
4799
4800 if (r !== 0) {
4801 s++;
4802 }
4803 this.length = Math.min(s, this.length);
4804
4805 if (r !== 0) {
4806 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
4807 this.words[this.length - 1] &= mask;
4808 }
4809
4810 return this.strip();
4811 };
4812
4813 // Return only lowers bits of number
4814 BN.prototype.maskn = function maskn (bits) {
4815 return this.clone().imaskn(bits);
4816 };
4817
4818 // Add plain number `num` to `this`
4819 BN.prototype.iaddn = function iaddn (num) {
4820 assert(typeof num === 'number');
4821 assert(num < 0x4000000);
4822 if (num < 0) return this.isubn(-num);
4823
4824 // Possible sign change
4825 if (this.negative !== 0) {
4826 if (this.length === 1 && (this.words[0] | 0) < num) {
4827 this.words[0] = num - (this.words[0] | 0);
4828 this.negative = 0;
4829 return this;
4830 }
4831
4832 this.negative = 0;
4833 this.isubn(num);
4834 this.negative = 1;
4835 return this;
4836 }
4837
4838 // Add without checks
4839 return this._iaddn(num);
4840 };
4841
4842 BN.prototype._iaddn = function _iaddn (num) {
4843 this.words[0] += num;
4844
4845 // Carry
4846 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
4847 this.words[i] -= 0x4000000;
4848 if (i === this.length - 1) {
4849 this.words[i + 1] = 1;
4850 } else {
4851 this.words[i + 1]++;
4852 }
4853 }
4854 this.length = Math.max(this.length, i + 1);
4855
4856 return this;
4857 };
4858
4859 // Subtract plain number `num` from `this`
4860 BN.prototype.isubn = function isubn (num) {
4861 assert(typeof num === 'number');
4862 assert(num < 0x4000000);
4863 if (num < 0) return this.iaddn(-num);
4864
4865 if (this.negative !== 0) {
4866 this.negative = 0;
4867 this.iaddn(num);
4868 this.negative = 1;
4869 return this;
4870 }
4871
4872 this.words[0] -= num;
4873
4874 if (this.length === 1 && this.words[0] < 0) {
4875 this.words[0] = -this.words[0];
4876 this.negative = 1;
4877 } else {
4878 // Carry
4879 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
4880 this.words[i] += 0x4000000;
4881 this.words[i + 1] -= 1;
4882 }
4883 }
4884
4885 return this.strip();
4886 };
4887
4888 BN.prototype.addn = function addn (num) {
4889 return this.clone().iaddn(num);
4890 };
4891
4892 BN.prototype.subn = function subn (num) {
4893 return this.clone().isubn(num);
4894 };
4895
4896 BN.prototype.iabs = function iabs () {
4897 this.negative = 0;
4898
4899 return this;
4900 };
4901
4902 BN.prototype.abs = function abs () {
4903 return this.clone().iabs();
4904 };
4905
4906 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
4907 var len = num.length + shift;
4908 var i;
4909
4910 this._expand(len);
4911
4912 var w;
4913 var carry = 0;
4914 for (i = 0; i < num.length; i++) {
4915 w = (this.words[i + shift] | 0) + carry;
4916 var right = (num.words[i] | 0) * mul;
4917 w -= right & 0x3ffffff;
4918 carry = (w >> 26) - ((right / 0x4000000) | 0);
4919 this.words[i + shift] = w & 0x3ffffff;
4920 }
4921 for (; i < this.length - shift; i++) {
4922 w = (this.words[i + shift] | 0) + carry;
4923 carry = w >> 26;
4924 this.words[i + shift] = w & 0x3ffffff;
4925 }
4926
4927 if (carry === 0) return this.strip();
4928
4929 // Subtraction overflow
4930 assert(carry === -1);
4931 carry = 0;
4932 for (i = 0; i < this.length; i++) {
4933 w = -(this.words[i] | 0) + carry;
4934 carry = w >> 26;
4935 this.words[i] = w & 0x3ffffff;
4936 }
4937 this.negative = 1;
4938
4939 return this.strip();
4940 };
4941
4942 BN.prototype._wordDiv = function _wordDiv (num, mode) {
4943 var shift = this.length - num.length;
4944
4945 var a = this.clone();
4946 var b = num;
4947
4948 // Normalize
4949 var bhi = b.words[b.length - 1] | 0;
4950 var bhiBits = this._countBits(bhi);
4951 shift = 26 - bhiBits;
4952 if (shift !== 0) {
4953 b = b.ushln(shift);
4954 a.iushln(shift);
4955 bhi = b.words[b.length - 1] | 0;
4956 }
4957
4958 // Initialize quotient
4959 var m = a.length - b.length;
4960 var q;
4961
4962 if (mode !== 'mod') {
4963 q = new BN(null);
4964 q.length = m + 1;
4965 q.words = new Array(q.length);
4966 for (var i = 0; i < q.length; i++) {
4967 q.words[i] = 0;
4968 }
4969 }
4970
4971 var diff = a.clone()._ishlnsubmul(b, 1, m);
4972 if (diff.negative === 0) {
4973 a = diff;
4974 if (q) {
4975 q.words[m] = 1;
4976 }
4977 }
4978
4979 for (var j = m - 1; j >= 0; j--) {
4980 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
4981 (a.words[b.length + j - 1] | 0);
4982
4983 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
4984 // (0x7ffffff)
4985 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
4986
4987 a._ishlnsubmul(b, qj, j);
4988 while (a.negative !== 0) {
4989 qj--;
4990 a.negative = 0;
4991 a._ishlnsubmul(b, 1, j);
4992 if (!a.isZero()) {
4993 a.negative ^= 1;
4994 }
4995 }
4996 if (q) {
4997 q.words[j] = qj;
4998 }
4999 }
5000 if (q) {
5001 q.strip();
5002 }
5003 a.strip();
5004
5005 // Denormalize
5006 if (mode !== 'div' && shift !== 0) {
5007 a.iushrn(shift);
5008 }
5009
5010 return {
5011 div: q || null,
5012 mod: a
5013 };
5014 };
5015
5016 // NOTE: 1) `mode` can be set to `mod` to request mod only,
5017 // to `div` to request div only, or be absent to
5018 // request both div & mod
5019 // 2) `positive` is true if unsigned mod is requested
5020 BN.prototype.divmod = function divmod (num, mode, positive) {
5021 assert(!num.isZero());
5022
5023 if (this.isZero()) {
5024 return {
5025 div: new BN(0),
5026 mod: new BN(0)
5027 };
5028 }
5029
5030 var div, mod, res;
5031 if (this.negative !== 0 && num.negative === 0) {
5032 res = this.neg().divmod(num, mode);
5033
5034 if (mode !== 'mod') {
5035 div = res.div.neg();
5036 }
5037
5038 if (mode !== 'div') {
5039 mod = res.mod.neg();
5040 if (positive && mod.negative !== 0) {
5041 mod.iadd(num);
5042 }
5043 }
5044
5045 return {
5046 div: div,
5047 mod: mod
5048 };
5049 }
5050
5051 if (this.negative === 0 && num.negative !== 0) {
5052 res = this.divmod(num.neg(), mode);
5053
5054 if (mode !== 'mod') {
5055 div = res.div.neg();
5056 }
5057
5058 return {
5059 div: div,
5060 mod: res.mod
5061 };
5062 }
5063
5064 if ((this.negative & num.negative) !== 0) {
5065 res = this.neg().divmod(num.neg(), mode);
5066
5067 if (mode !== 'div') {
5068 mod = res.mod.neg();
5069 if (positive && mod.negative !== 0) {
5070 mod.isub(num);
5071 }
5072 }
5073
5074 return {
5075 div: res.div,
5076 mod: mod
5077 };
5078 }
5079
5080 // Both numbers are positive at this point
5081
5082 // Strip both numbers to approximate shift value
5083 if (num.length > this.length || this.cmp(num) < 0) {
5084 return {
5085 div: new BN(0),
5086 mod: this
5087 };
5088 }
5089
5090 // Very short reduction
5091 if (num.length === 1) {
5092 if (mode === 'div') {
5093 return {
5094 div: this.divn(num.words[0]),
5095 mod: null
5096 };
5097 }
5098
5099 if (mode === 'mod') {
5100 return {
5101 div: null,
5102 mod: new BN(this.modn(num.words[0]))
5103 };
5104 }
5105
5106 return {
5107 div: this.divn(num.words[0]),
5108 mod: new BN(this.modn(num.words[0]))
5109 };
5110 }
5111
5112 return this._wordDiv(num, mode);
5113 };
5114
5115 // Find `this` / `num`
5116 BN.prototype.div = function div (num) {
5117 return this.divmod(num, 'div', false).div;
5118 };
5119
5120 // Find `this` % `num`
5121 BN.prototype.mod = function mod (num) {
5122 return this.divmod(num, 'mod', false).mod;
5123 };
5124
5125 BN.prototype.umod = function umod (num) {
5126 return this.divmod(num, 'mod', true).mod;
5127 };
5128
5129 // Find Round(`this` / `num`)
5130 BN.prototype.divRound = function divRound (num) {
5131 var dm = this.divmod(num);
5132
5133 // Fast case - exact division
5134 if (dm.mod.isZero()) return dm.div;
5135
5136 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
5137
5138 var half = num.ushrn(1);
5139 var r2 = num.andln(1);
5140 var cmp = mod.cmp(half);
5141
5142 // Round down
5143 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
5144
5145 // Round up
5146 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
5147 };
5148
5149 BN.prototype.modn = function modn (num) {
5150 assert(num <= 0x3ffffff);
5151 var p = (1 << 26) % num;
5152
5153 var acc = 0;
5154 for (var i = this.length - 1; i >= 0; i--) {
5155 acc = (p * acc + (this.words[i] | 0)) % num;
5156 }
5157
5158 return acc;
5159 };
5160
5161 // In-place division by number
5162 BN.prototype.idivn = function idivn (num) {
5163 assert(num <= 0x3ffffff);
5164
5165 var carry = 0;
5166 for (var i = this.length - 1; i >= 0; i--) {
5167 var w = (this.words[i] | 0) + carry * 0x4000000;
5168 this.words[i] = (w / num) | 0;
5169 carry = w % num;
5170 }
5171
5172 return this.strip();
5173 };
5174
5175 BN.prototype.divn = function divn (num) {
5176 return this.clone().idivn(num);
5177 };
5178
5179 BN.prototype.egcd = function egcd (p) {
5180 assert(p.negative === 0);
5181 assert(!p.isZero());
5182
5183 var x = this;
5184 var y = p.clone();
5185
5186 if (x.negative !== 0) {
5187 x = x.umod(p);
5188 } else {
5189 x = x.clone();
5190 }
5191
5192 // A * x + B * y = x
5193 var A = new BN(1);
5194 var B = new BN(0);
5195
5196 // C * x + D * y = y
5197 var C = new BN(0);
5198 var D = new BN(1);
5199
5200 var g = 0;
5201
5202 while (x.isEven() && y.isEven()) {
5203 x.iushrn(1);
5204 y.iushrn(1);
5205 ++g;
5206 }
5207
5208 var yp = y.clone();
5209 var xp = x.clone();
5210
5211 while (!x.isZero()) {
5212 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
5213 if (i > 0) {
5214 x.iushrn(i);
5215 while (i-- > 0) {
5216 if (A.isOdd() || B.isOdd()) {
5217 A.iadd(yp);
5218 B.isub(xp);
5219 }
5220
5221 A.iushrn(1);
5222 B.iushrn(1);
5223 }
5224 }
5225
5226 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
5227 if (j > 0) {
5228 y.iushrn(j);
5229 while (j-- > 0) {
5230 if (C.isOdd() || D.isOdd()) {
5231 C.iadd(yp);
5232 D.isub(xp);
5233 }
5234
5235 C.iushrn(1);
5236 D.iushrn(1);
5237 }
5238 }
5239
5240 if (x.cmp(y) >= 0) {
5241 x.isub(y);
5242 A.isub(C);
5243 B.isub(D);
5244 } else {
5245 y.isub(x);
5246 C.isub(A);
5247 D.isub(B);
5248 }
5249 }
5250
5251 return {
5252 a: C,
5253 b: D,
5254 gcd: y.iushln(g)
5255 };
5256 };
5257
5258 // This is reduced incarnation of the binary EEA
5259 // above, designated to invert members of the
5260 // _prime_ fields F(p) at a maximal speed
5261 BN.prototype._invmp = function _invmp (p) {
5262 assert(p.negative === 0);
5263 assert(!p.isZero());
5264
5265 var a = this;
5266 var b = p.clone();
5267
5268 if (a.negative !== 0) {
5269 a = a.umod(p);
5270 } else {
5271 a = a.clone();
5272 }
5273
5274 var x1 = new BN(1);
5275 var x2 = new BN(0);
5276
5277 var delta = b.clone();
5278
5279 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
5280 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
5281 if (i > 0) {
5282 a.iushrn(i);
5283 while (i-- > 0) {
5284 if (x1.isOdd()) {
5285 x1.iadd(delta);
5286 }
5287
5288 x1.iushrn(1);
5289 }
5290 }
5291
5292 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
5293 if (j > 0) {
5294 b.iushrn(j);
5295 while (j-- > 0) {
5296 if (x2.isOdd()) {
5297 x2.iadd(delta);
5298 }
5299
5300 x2.iushrn(1);
5301 }
5302 }
5303
5304 if (a.cmp(b) >= 0) {
5305 a.isub(b);
5306 x1.isub(x2);
5307 } else {
5308 b.isub(a);
5309 x2.isub(x1);
5310 }
5311 }
5312
5313 var res;
5314 if (a.cmpn(1) === 0) {
5315 res = x1;
5316 } else {
5317 res = x2;
5318 }
5319
5320 if (res.cmpn(0) < 0) {
5321 res.iadd(p);
5322 }
5323
5324 return res;
5325 };
5326
5327 BN.prototype.gcd = function gcd (num) {
5328 if (this.isZero()) return num.abs();
5329 if (num.isZero()) return this.abs();
5330
5331 var a = this.clone();
5332 var b = num.clone();
5333 a.negative = 0;
5334 b.negative = 0;
5335
5336 // Remove common factor of two
5337 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
5338 a.iushrn(1);
5339 b.iushrn(1);
5340 }
5341
5342 do {
5343 while (a.isEven()) {
5344 a.iushrn(1);
5345 }
5346 while (b.isEven()) {
5347 b.iushrn(1);
5348 }
5349
5350 var r = a.cmp(b);
5351 if (r < 0) {
5352 // Swap `a` and `b` to make `a` always bigger than `b`
5353 var t = a;
5354 a = b;
5355 b = t;
5356 } else if (r === 0 || b.cmpn(1) === 0) {
5357 break;
5358 }
5359
5360 a.isub(b);
5361 } while (true);
5362
5363 return b.iushln(shift);
5364 };
5365
5366 // Invert number in the field F(num)
5367 BN.prototype.invm = function invm (num) {
5368 return this.egcd(num).a.umod(num);
5369 };
5370
5371 BN.prototype.isEven = function isEven () {
5372 return (this.words[0] & 1) === 0;
5373 };
5374
5375 BN.prototype.isOdd = function isOdd () {
5376 return (this.words[0] & 1) === 1;
5377 };
5378
5379 // And first word and num
5380 BN.prototype.andln = function andln (num) {
5381 return this.words[0] & num;
5382 };
5383
5384 // Increment at the bit position in-line
5385 BN.prototype.bincn = function bincn (bit) {
5386 assert(typeof bit === 'number');
5387 var r = bit % 26;
5388 var s = (bit - r) / 26;
5389 var q = 1 << r;
5390
5391 // Fast case: bit is much higher than all existing words
5392 if (this.length <= s) {
5393 this._expand(s + 1);
5394 this.words[s] |= q;
5395 return this;
5396 }
5397
5398 // Add bit and propagate, if needed
5399 var carry = q;
5400 for (var i = s; carry !== 0 && i < this.length; i++) {
5401 var w = this.words[i] | 0;
5402 w += carry;
5403 carry = w >>> 26;
5404 w &= 0x3ffffff;
5405 this.words[i] = w;
5406 }
5407 if (carry !== 0) {
5408 this.words[i] = carry;
5409 this.length++;
5410 }
5411 return this;
5412 };
5413
5414 BN.prototype.isZero = function isZero () {
5415 return this.length === 1 && this.words[0] === 0;
5416 };
5417
5418 BN.prototype.cmpn = function cmpn (num) {
5419 var negative = num < 0;
5420
5421 if (this.negative !== 0 && !negative) return -1;
5422 if (this.negative === 0 && negative) return 1;
5423
5424 this.strip();
5425
5426 var res;
5427 if (this.length > 1) {
5428 res = 1;
5429 } else {
5430 if (negative) {
5431 num = -num;
5432 }
5433
5434 assert(num <= 0x3ffffff, 'Number is too big');
5435
5436 var w = this.words[0] | 0;
5437 res = w === num ? 0 : w < num ? -1 : 1;
5438 }
5439 if (this.negative !== 0) return -res | 0;
5440 return res;
5441 };
5442
5443 // Compare two numbers and return:
5444 // 1 - if `this` > `num`
5445 // 0 - if `this` == `num`
5446 // -1 - if `this` < `num`
5447 BN.prototype.cmp = function cmp (num) {
5448 if (this.negative !== 0 && num.negative === 0) return -1;
5449 if (this.negative === 0 && num.negative !== 0) return 1;
5450
5451 var res = this.ucmp(num);
5452 if (this.negative !== 0) return -res | 0;
5453 return res;
5454 };
5455
5456 // Unsigned comparison
5457 BN.prototype.ucmp = function ucmp (num) {
5458 // At this point both numbers have the same sign
5459 if (this.length > num.length) return 1;
5460 if (this.length < num.length) return -1;
5461
5462 var res = 0;
5463 for (var i = this.length - 1; i >= 0; i--) {
5464 var a = this.words[i] | 0;
5465 var b = num.words[i] | 0;
5466
5467 if (a === b) continue;
5468 if (a < b) {
5469 res = -1;
5470 } else if (a > b) {
5471 res = 1;
5472 }
5473 break;
5474 }
5475 return res;
5476 };
5477
5478 BN.prototype.gtn = function gtn (num) {
5479 return this.cmpn(num) === 1;
5480 };
5481
5482 BN.prototype.gt = function gt (num) {
5483 return this.cmp(num) === 1;
5484 };
5485
5486 BN.prototype.gten = function gten (num) {
5487 return this.cmpn(num) >= 0;
5488 };
5489
5490 BN.prototype.gte = function gte (num) {
5491 return this.cmp(num) >= 0;
5492 };
5493
5494 BN.prototype.ltn = function ltn (num) {
5495 return this.cmpn(num) === -1;
5496 };
5497
5498 BN.prototype.lt = function lt (num) {
5499 return this.cmp(num) === -1;
5500 };
5501
5502 BN.prototype.lten = function lten (num) {
5503 return this.cmpn(num) <= 0;
5504 };
5505
5506 BN.prototype.lte = function lte (num) {
5507 return this.cmp(num) <= 0;
5508 };
5509
5510 BN.prototype.eqn = function eqn (num) {
5511 return this.cmpn(num) === 0;
5512 };
5513
5514 BN.prototype.eq = function eq (num) {
5515 return this.cmp(num) === 0;
5516 };
5517
5518 //
5519 // A reduce context, could be using montgomery or something better, depending
5520 // on the `m` itself.
5521 //
5522 BN.red = function red (num) {
5523 return new Red(num);
5524 };
5525
5526 BN.prototype.toRed = function toRed (ctx) {
5527 assert(!this.red, 'Already a number in reduction context');
5528 assert(this.negative === 0, 'red works only with positives');
5529 return ctx.convertTo(this)._forceRed(ctx);
5530 };
5531
5532 BN.prototype.fromRed = function fromRed () {
5533 assert(this.red, 'fromRed works only with numbers in reduction context');
5534 return this.red.convertFrom(this);
5535 };
5536
5537 BN.prototype._forceRed = function _forceRed (ctx) {
5538 this.red = ctx;
5539 return this;
5540 };
5541
5542 BN.prototype.forceRed = function forceRed (ctx) {
5543 assert(!this.red, 'Already a number in reduction context');
5544 return this._forceRed(ctx);
5545 };
5546
5547 BN.prototype.redAdd = function redAdd (num) {
5548 assert(this.red, 'redAdd works only with red numbers');
5549 return this.red.add(this, num);
5550 };
5551
5552 BN.prototype.redIAdd = function redIAdd (num) {
5553 assert(this.red, 'redIAdd works only with red numbers');
5554 return this.red.iadd(this, num);
5555 };
5556
5557 BN.prototype.redSub = function redSub (num) {
5558 assert(this.red, 'redSub works only with red numbers');
5559 return this.red.sub(this, num);
5560 };
5561
5562 BN.prototype.redISub = function redISub (num) {
5563 assert(this.red, 'redISub works only with red numbers');
5564 return this.red.isub(this, num);
5565 };
5566
5567 BN.prototype.redShl = function redShl (num) {
5568 assert(this.red, 'redShl works only with red numbers');
5569 return this.red.shl(this, num);
5570 };
5571
5572 BN.prototype.redMul = function redMul (num) {
5573 assert(this.red, 'redMul works only with red numbers');
5574 this.red._verify2(this, num);
5575 return this.red.mul(this, num);
5576 };
5577
5578 BN.prototype.redIMul = function redIMul (num) {
5579 assert(this.red, 'redMul works only with red numbers');
5580 this.red._verify2(this, num);
5581 return this.red.imul(this, num);
5582 };
5583
5584 BN.prototype.redSqr = function redSqr () {
5585 assert(this.red, 'redSqr works only with red numbers');
5586 this.red._verify1(this);
5587 return this.red.sqr(this);
5588 };
5589
5590 BN.prototype.redISqr = function redISqr () {
5591 assert(this.red, 'redISqr works only with red numbers');
5592 this.red._verify1(this);
5593 return this.red.isqr(this);
5594 };
5595
5596 // Square root over p
5597 BN.prototype.redSqrt = function redSqrt () {
5598 assert(this.red, 'redSqrt works only with red numbers');
5599 this.red._verify1(this);
5600 return this.red.sqrt(this);
5601 };
5602
5603 BN.prototype.redInvm = function redInvm () {
5604 assert(this.red, 'redInvm works only with red numbers');
5605 this.red._verify1(this);
5606 return this.red.invm(this);
5607 };
5608
5609 // Return negative clone of `this` % `red modulo`
5610 BN.prototype.redNeg = function redNeg () {
5611 assert(this.red, 'redNeg works only with red numbers');
5612 this.red._verify1(this);
5613 return this.red.neg(this);
5614 };
5615
5616 BN.prototype.redPow = function redPow (num) {
5617 assert(this.red && !num.red, 'redPow(normalNum)');
5618 this.red._verify1(this);
5619 return this.red.pow(this, num);
5620 };
5621
5622 // Prime numbers with efficient reduction
5623 var primes = {
5624 k256: null,
5625 p224: null,
5626 p192: null,
5627 p25519: null
5628 };
5629
5630 // Pseudo-Mersenne prime
5631 function MPrime (name, p) {
5632 // P = 2 ^ N - K
5633 this.name = name;
5634 this.p = new BN(p, 16);
5635 this.n = this.p.bitLength();
5636 this.k = new BN(1).iushln(this.n).isub(this.p);
5637
5638 this.tmp = this._tmp();
5639 }
5640
5641 MPrime.prototype._tmp = function _tmp () {
5642 var tmp = new BN(null);
5643 tmp.words = new Array(Math.ceil(this.n / 13));
5644 return tmp;
5645 };
5646
5647 MPrime.prototype.ireduce = function ireduce (num) {
5648 // Assumes that `num` is less than `P^2`
5649 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
5650 var r = num;
5651 var rlen;
5652
5653 do {
5654 this.split(r, this.tmp);
5655 r = this.imulK(r);
5656 r = r.iadd(this.tmp);
5657 rlen = r.bitLength();
5658 } while (rlen > this.n);
5659
5660 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
5661 if (cmp === 0) {
5662 r.words[0] = 0;
5663 r.length = 1;
5664 } else if (cmp > 0) {
5665 r.isub(this.p);
5666 } else {
5667 if (r.strip !== undefined) {
5668 // r is BN v4 instance
5669 r.strip();
5670 } else {
5671 // r is BN v5 instance
5672 r._strip();
5673 }
5674 }
5675
5676 return r;
5677 };
5678
5679 MPrime.prototype.split = function split (input, out) {
5680 input.iushrn(this.n, 0, out);
5681 };
5682
5683 MPrime.prototype.imulK = function imulK (num) {
5684 return num.imul(this.k);
5685 };
5686
5687 function K256 () {
5688 MPrime.call(
5689 this,
5690 'k256',
5691 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
5692 }
5693 inherits(K256, MPrime);
5694
5695 K256.prototype.split = function split (input, output) {
5696 // 256 = 9 * 26 + 22
5697 var mask = 0x3fffff;
5698
5699 var outLen = Math.min(input.length, 9);
5700 for (var i = 0; i < outLen; i++) {
5701 output.words[i] = input.words[i];
5702 }
5703 output.length = outLen;
5704
5705 if (input.length <= 9) {
5706 input.words[0] = 0;
5707 input.length = 1;
5708 return;
5709 }
5710
5711 // Shift by 9 limbs
5712 var prev = input.words[9];
5713 output.words[output.length++] = prev & mask;
5714
5715 for (i = 10; i < input.length; i++) {
5716 var next = input.words[i] | 0;
5717 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
5718 prev = next;
5719 }
5720 prev >>>= 22;
5721 input.words[i - 10] = prev;
5722 if (prev === 0 && input.length > 10) {
5723 input.length -= 10;
5724 } else {
5725 input.length -= 9;
5726 }
5727 };
5728
5729 K256.prototype.imulK = function imulK (num) {
5730 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
5731 num.words[num.length] = 0;
5732 num.words[num.length + 1] = 0;
5733 num.length += 2;
5734
5735 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
5736 var lo = 0;
5737 for (var i = 0; i < num.length; i++) {
5738 var w = num.words[i] | 0;
5739 lo += w * 0x3d1;
5740 num.words[i] = lo & 0x3ffffff;
5741 lo = w * 0x40 + ((lo / 0x4000000) | 0);
5742 }
5743
5744 // Fast length reduction
5745 if (num.words[num.length - 1] === 0) {
5746 num.length--;
5747 if (num.words[num.length - 1] === 0) {
5748 num.length--;
5749 }
5750 }
5751 return num;
5752 };
5753
5754 function P224 () {
5755 MPrime.call(
5756 this,
5757 'p224',
5758 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
5759 }
5760 inherits(P224, MPrime);
5761
5762 function P192 () {
5763 MPrime.call(
5764 this,
5765 'p192',
5766 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
5767 }
5768 inherits(P192, MPrime);
5769
5770 function P25519 () {
5771 // 2 ^ 255 - 19
5772 MPrime.call(
5773 this,
5774 '25519',
5775 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
5776 }
5777 inherits(P25519, MPrime);
5778
5779 P25519.prototype.imulK = function imulK (num) {
5780 // K = 0x13
5781 var carry = 0;
5782 for (var i = 0; i < num.length; i++) {
5783 var hi = (num.words[i] | 0) * 0x13 + carry;
5784 var lo = hi & 0x3ffffff;
5785 hi >>>= 26;
5786
5787 num.words[i] = lo;
5788 carry = hi;
5789 }
5790 if (carry !== 0) {
5791 num.words[num.length++] = carry;
5792 }
5793 return num;
5794 };
5795
5796 // Exported mostly for testing purposes, use plain name instead
5797 BN._prime = function prime (name) {
5798 // Cached version of prime
5799 if (primes[name]) return primes[name];
5800
5801 var prime;
5802 if (name === 'k256') {
5803 prime = new K256();
5804 } else if (name === 'p224') {
5805 prime = new P224();
5806 } else if (name === 'p192') {
5807 prime = new P192();
5808 } else if (name === 'p25519') {
5809 prime = new P25519();
5810 } else {
5811 throw new Error('Unknown prime ' + name);
5812 }
5813 primes[name] = prime;
5814
5815 return prime;
5816 };
5817
5818 //
5819 // Base reduction engine
5820 //
5821 function Red (m) {
5822 if (typeof m === 'string') {
5823 var prime = BN._prime(m);
5824 this.m = prime.p;
5825 this.prime = prime;
5826 } else {
5827 assert(m.gtn(1), 'modulus must be greater than 1');
5828 this.m = m;
5829 this.prime = null;
5830 }
5831 }
5832
5833 Red.prototype._verify1 = function _verify1 (a) {
5834 assert(a.negative === 0, 'red works only with positives');
5835 assert(a.red, 'red works only with red numbers');
5836 };
5837
5838 Red.prototype._verify2 = function _verify2 (a, b) {
5839 assert((a.negative | b.negative) === 0, 'red works only with positives');
5840 assert(a.red && a.red === b.red,
5841 'red works only with red numbers');
5842 };
5843
5844 Red.prototype.imod = function imod (a) {
5845 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
5846 return a.umod(this.m)._forceRed(this);
5847 };
5848
5849 Red.prototype.neg = function neg (a) {
5850 if (a.isZero()) {
5851 return a.clone();
5852 }
5853
5854 return this.m.sub(a)._forceRed(this);
5855 };
5856
5857 Red.prototype.add = function add (a, b) {
5858 this._verify2(a, b);
5859
5860 var res = a.add(b);
5861 if (res.cmp(this.m) >= 0) {
5862 res.isub(this.m);
5863 }
5864 return res._forceRed(this);
5865 };
5866
5867 Red.prototype.iadd = function iadd (a, b) {
5868 this._verify2(a, b);
5869
5870 var res = a.iadd(b);
5871 if (res.cmp(this.m) >= 0) {
5872 res.isub(this.m);
5873 }
5874 return res;
5875 };
5876
5877 Red.prototype.sub = function sub (a, b) {
5878 this._verify2(a, b);
5879
5880 var res = a.sub(b);
5881 if (res.cmpn(0) < 0) {
5882 res.iadd(this.m);
5883 }
5884 return res._forceRed(this);
5885 };
5886
5887 Red.prototype.isub = function isub (a, b) {
5888 this._verify2(a, b);
5889
5890 var res = a.isub(b);
5891 if (res.cmpn(0) < 0) {
5892 res.iadd(this.m);
5893 }
5894 return res;
5895 };
5896
5897 Red.prototype.shl = function shl (a, num) {
5898 this._verify1(a);
5899 return this.imod(a.ushln(num));
5900 };
5901
5902 Red.prototype.imul = function imul (a, b) {
5903 this._verify2(a, b);
5904 return this.imod(a.imul(b));
5905 };
5906
5907 Red.prototype.mul = function mul (a, b) {
5908 this._verify2(a, b);
5909 return this.imod(a.mul(b));
5910 };
5911
5912 Red.prototype.isqr = function isqr (a) {
5913 return this.imul(a, a.clone());
5914 };
5915
5916 Red.prototype.sqr = function sqr (a) {
5917 return this.mul(a, a);
5918 };
5919
5920 Red.prototype.sqrt = function sqrt (a) {
5921 if (a.isZero()) return a.clone();
5922
5923 var mod3 = this.m.andln(3);
5924 assert(mod3 % 2 === 1);
5925
5926 // Fast case
5927 if (mod3 === 3) {
5928 var pow = this.m.add(new BN(1)).iushrn(2);
5929 return this.pow(a, pow);
5930 }
5931
5932 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
5933 //
5934 // Find Q and S, that Q * 2 ^ S = (P - 1)
5935 var q = this.m.subn(1);
5936 var s = 0;
5937 while (!q.isZero() && q.andln(1) === 0) {
5938 s++;
5939 q.iushrn(1);
5940 }
5941 assert(!q.isZero());
5942
5943 var one = new BN(1).toRed(this);
5944 var nOne = one.redNeg();
5945
5946 // Find quadratic non-residue
5947 // NOTE: Max is such because of generalized Riemann hypothesis.
5948 var lpow = this.m.subn(1).iushrn(1);
5949 var z = this.m.bitLength();
5950 z = new BN(2 * z * z).toRed(this);
5951
5952 while (this.pow(z, lpow).cmp(nOne) !== 0) {
5953 z.redIAdd(nOne);
5954 }
5955
5956 var c = this.pow(z, q);
5957 var r = this.pow(a, q.addn(1).iushrn(1));
5958 var t = this.pow(a, q);
5959 var m = s;
5960 while (t.cmp(one) !== 0) {
5961 var tmp = t;
5962 for (var i = 0; tmp.cmp(one) !== 0; i++) {
5963 tmp = tmp.redSqr();
5964 }
5965 assert(i < m);
5966 var b = this.pow(c, new BN(1).iushln(m - i - 1));
5967
5968 r = r.redMul(b);
5969 c = b.redSqr();
5970 t = t.redMul(c);
5971 m = i;
5972 }
5973
5974 return r;
5975 };
5976
5977 Red.prototype.invm = function invm (a) {
5978 var inv = a._invmp(this.m);
5979 if (inv.negative !== 0) {
5980 inv.negative = 0;
5981 return this.imod(inv).redNeg();
5982 } else {
5983 return this.imod(inv);
5984 }
5985 };
5986
5987 Red.prototype.pow = function pow (a, num) {
5988 if (num.isZero()) return new BN(1).toRed(this);
5989 if (num.cmpn(1) === 0) return a.clone();
5990
5991 var windowSize = 4;
5992 var wnd = new Array(1 << windowSize);
5993 wnd[0] = new BN(1).toRed(this);
5994 wnd[1] = a;
5995 for (var i = 2; i < wnd.length; i++) {
5996 wnd[i] = this.mul(wnd[i - 1], a);
5997 }
5998
5999 var res = wnd[0];
6000 var current = 0;
6001 var currentLen = 0;
6002 var start = num.bitLength() % 26;
6003 if (start === 0) {
6004 start = 26;
6005 }
6006
6007 for (i = num.length - 1; i >= 0; i--) {
6008 var word = num.words[i];
6009 for (var j = start - 1; j >= 0; j--) {
6010 var bit = (word >> j) & 1;
6011 if (res !== wnd[0]) {
6012 res = this.sqr(res);
6013 }
6014
6015 if (bit === 0 && current === 0) {
6016 currentLen = 0;
6017 continue;
6018 }
6019
6020 current <<= 1;
6021 current |= bit;
6022 currentLen++;
6023 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
6024
6025 res = this.mul(res, wnd[current]);
6026 currentLen = 0;
6027 current = 0;
6028 }
6029 start = 26;
6030 }
6031
6032 return res;
6033 };
6034
6035 Red.prototype.convertTo = function convertTo (num) {
6036 var r = num.umod(this.m);
6037
6038 return r === num ? r.clone() : r;
6039 };
6040
6041 Red.prototype.convertFrom = function convertFrom (num) {
6042 var res = num.clone();
6043 res.red = null;
6044 return res;
6045 };
6046
6047 //
6048 // Montgomery method engine
6049 //
6050
6051 BN.mont = function mont (num) {
6052 return new Mont(num);
6053 };
6054
6055 function Mont (m) {
6056 Red.call(this, m);
6057
6058 this.shift = this.m.bitLength();
6059 if (this.shift % 26 !== 0) {
6060 this.shift += 26 - (this.shift % 26);
6061 }
6062
6063 this.r = new BN(1).iushln(this.shift);
6064 this.r2 = this.imod(this.r.sqr());
6065 this.rinv = this.r._invmp(this.m);
6066
6067 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
6068 this.minv = this.minv.umod(this.r);
6069 this.minv = this.r.sub(this.minv);
6070 }
6071 inherits(Mont, Red);
6072
6073 Mont.prototype.convertTo = function convertTo (num) {
6074 return this.imod(num.ushln(this.shift));
6075 };
6076
6077 Mont.prototype.convertFrom = function convertFrom (num) {
6078 var r = this.imod(num.mul(this.rinv));
6079 r.red = null;
6080 return r;
6081 };
6082
6083 Mont.prototype.imul = function imul (a, b) {
6084 if (a.isZero() || b.isZero()) {
6085 a.words[0] = 0;
6086 a.length = 1;
6087 return a;
6088 }
6089
6090 var t = a.imul(b);
6091 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
6092 var u = t.isub(c).iushrn(this.shift);
6093 var res = u;
6094
6095 if (u.cmp(this.m) >= 0) {
6096 res = u.isub(this.m);
6097 } else if (u.cmpn(0) < 0) {
6098 res = u.iadd(this.m);
6099 }
6100
6101 return res._forceRed(this);
6102 };
6103
6104 Mont.prototype.mul = function mul (a, b) {
6105 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
6106
6107 var t = a.mul(b);
6108 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
6109 var u = t.isub(c).iushrn(this.shift);
6110 var res = u;
6111 if (u.cmp(this.m) >= 0) {
6112 res = u.isub(this.m);
6113 } else if (u.cmpn(0) < 0) {
6114 res = u.iadd(this.m);
6115 }
6116
6117 return res._forceRed(this);
6118 };
6119
6120 Mont.prototype.invm = function invm (a) {
6121 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
6122 var res = this.imod(a._invmp(this.m).mul(this.r2));
6123 return res._forceRed(this);
6124 };
6125})(typeof module === 'undefined' || module, this);
6126
6127},{"buffer":33}],22:[function(require,module,exports){
6128(function (global){(function (){
6129'use strict';
6130
6131var objectAssign = require('object-assign');
6132
6133// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
6134// original notice:
6135
6136/*!
6137 * The buffer module from node.js, for the browser.
6138 *
6139 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
6140 * @license MIT
6141 */
6142function compare(a, b) {
6143 if (a === b) {
6144 return 0;
6145 }
6146
6147 var x = a.length;
6148 var y = b.length;
6149
6150 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
6151 if (a[i] !== b[i]) {
6152 x = a[i];
6153 y = b[i];
6154 break;
6155 }
6156 }
6157
6158 if (x < y) {
6159 return -1;
6160 }
6161 if (y < x) {
6162 return 1;
6163 }
6164 return 0;
6165}
6166function isBuffer(b) {
6167 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
6168 return global.Buffer.isBuffer(b);
6169 }
6170 return !!(b != null && b._isBuffer);
6171}
6172
6173// based on node assert, original notice:
6174// NB: The URL to the CommonJS spec is kept just for tradition.
6175// node-assert has evolved a lot since then, both in API and behavior.
6176
6177// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
6178//
6179// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
6180//
6181// Originally from narwhal.js (http://narwhaljs.org)
6182// Copyright (c) 2009 Thomas Robinson <280north.com>
6183//
6184// Permission is hereby granted, free of charge, to any person obtaining a copy
6185// of this software and associated documentation files (the 'Software'), to
6186// deal in the Software without restriction, including without limitation the
6187// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
6188// sell copies of the Software, and to permit persons to whom the Software is
6189// furnished to do so, subject to the following conditions:
6190//
6191// The above copyright notice and this permission notice shall be included in
6192// all copies or substantial portions of the Software.
6193//
6194// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6195// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6196// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
6197// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
6198// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
6199// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6200
6201var util = require('util/');
6202var hasOwn = Object.prototype.hasOwnProperty;
6203var pSlice = Array.prototype.slice;
6204var functionsHaveNames = (function () {
6205 return function foo() {}.name === 'foo';
6206}());
6207function pToString (obj) {
6208 return Object.prototype.toString.call(obj);
6209}
6210function isView(arrbuf) {
6211 if (isBuffer(arrbuf)) {
6212 return false;
6213 }
6214 if (typeof global.ArrayBuffer !== 'function') {
6215 return false;
6216 }
6217 if (typeof ArrayBuffer.isView === 'function') {
6218 return ArrayBuffer.isView(arrbuf);
6219 }
6220 if (!arrbuf) {
6221 return false;
6222 }
6223 if (arrbuf instanceof DataView) {
6224 return true;
6225 }
6226 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
6227 return true;
6228 }
6229 return false;
6230}
6231// 1. The assert module provides functions that throw
6232// AssertionError's when particular conditions are not met. The
6233// assert module must conform to the following interface.
6234
6235var assert = module.exports = ok;
6236
6237// 2. The AssertionError is defined in assert.
6238// new assert.AssertionError({ message: message,
6239// actual: actual,
6240// expected: expected })
6241
6242var regex = /\s*function\s+([^\(\s]*)\s*/;
6243// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
6244function getName(func) {
6245 if (!util.isFunction(func)) {
6246 return;
6247 }
6248 if (functionsHaveNames) {
6249 return func.name;
6250 }
6251 var str = func.toString();
6252 var match = str.match(regex);
6253 return match && match[1];
6254}
6255assert.AssertionError = function AssertionError(options) {
6256 this.name = 'AssertionError';
6257 this.actual = options.actual;
6258 this.expected = options.expected;
6259 this.operator = options.operator;
6260 if (options.message) {
6261 this.message = options.message;
6262 this.generatedMessage = false;
6263 } else {
6264 this.message = getMessage(this);
6265 this.generatedMessage = true;
6266 }
6267 var stackStartFunction = options.stackStartFunction || fail;
6268 if (Error.captureStackTrace) {
6269 Error.captureStackTrace(this, stackStartFunction);
6270 } else {
6271 // non v8 browsers so we can have a stacktrace
6272 var err = new Error();
6273 if (err.stack) {
6274 var out = err.stack;
6275
6276 // try to strip useless frames
6277 var fn_name = getName(stackStartFunction);
6278 var idx = out.indexOf('\n' + fn_name);
6279 if (idx >= 0) {
6280 // once we have located the function frame
6281 // we need to strip out everything before it (and its line)
6282 var next_line = out.indexOf('\n', idx + 1);
6283 out = out.substring(next_line + 1);
6284 }
6285
6286 this.stack = out;
6287 }
6288 }
6289};
6290
6291// assert.AssertionError instanceof Error
6292util.inherits(assert.AssertionError, Error);
6293
6294function truncate(s, n) {
6295 if (typeof s === 'string') {
6296 return s.length < n ? s : s.slice(0, n);
6297 } else {
6298 return s;
6299 }
6300}
6301function inspect(something) {
6302 if (functionsHaveNames || !util.isFunction(something)) {
6303 return util.inspect(something);
6304 }
6305 var rawname = getName(something);
6306 var name = rawname ? ': ' + rawname : '';
6307 return '[Function' + name + ']';
6308}
6309function getMessage(self) {
6310 return truncate(inspect(self.actual), 128) + ' ' +
6311 self.operator + ' ' +
6312 truncate(inspect(self.expected), 128);
6313}
6314
6315// At present only the three keys mentioned above are used and
6316// understood by the spec. Implementations or sub modules can pass
6317// other keys to the AssertionError's constructor - they will be
6318// ignored.
6319
6320// 3. All of the following functions must throw an AssertionError
6321// when a corresponding condition is not met, with a message that
6322// may be undefined if not provided. All assertion methods provide
6323// both the actual and expected values to the assertion error for
6324// display purposes.
6325
6326function fail(actual, expected, message, operator, stackStartFunction) {
6327 throw new assert.AssertionError({
6328 message: message,
6329 actual: actual,
6330 expected: expected,
6331 operator: operator,
6332 stackStartFunction: stackStartFunction
6333 });
6334}
6335
6336// EXTENSION! allows for well behaved errors defined elsewhere.
6337assert.fail = fail;
6338
6339// 4. Pure assertion tests whether a value is truthy, as determined
6340// by !!guard.
6341// assert.ok(guard, message_opt);
6342// This statement is equivalent to assert.equal(true, !!guard,
6343// message_opt);. To test strictly for the value true, use
6344// assert.strictEqual(true, guard, message_opt);.
6345
6346function ok(value, message) {
6347 if (!value) fail(value, true, message, '==', assert.ok);
6348}
6349assert.ok = ok;
6350
6351// 5. The equality assertion tests shallow, coercive equality with
6352// ==.
6353// assert.equal(actual, expected, message_opt);
6354
6355assert.equal = function equal(actual, expected, message) {
6356 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
6357};
6358
6359// 6. The non-equality assertion tests for whether two objects are not equal
6360// with != assert.notEqual(actual, expected, message_opt);
6361
6362assert.notEqual = function notEqual(actual, expected, message) {
6363 if (actual == expected) {
6364 fail(actual, expected, message, '!=', assert.notEqual);
6365 }
6366};
6367
6368// 7. The equivalence assertion tests a deep equality relation.
6369// assert.deepEqual(actual, expected, message_opt);
6370
6371assert.deepEqual = function deepEqual(actual, expected, message) {
6372 if (!_deepEqual(actual, expected, false)) {
6373 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
6374 }
6375};
6376
6377assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
6378 if (!_deepEqual(actual, expected, true)) {
6379 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
6380 }
6381};
6382
6383function _deepEqual(actual, expected, strict, memos) {
6384 // 7.1. All identical values are equivalent, as determined by ===.
6385 if (actual === expected) {
6386 return true;
6387 } else if (isBuffer(actual) && isBuffer(expected)) {
6388 return compare(actual, expected) === 0;
6389
6390 // 7.2. If the expected value is a Date object, the actual value is
6391 // equivalent if it is also a Date object that refers to the same time.
6392 } else if (util.isDate(actual) && util.isDate(expected)) {
6393 return actual.getTime() === expected.getTime();
6394
6395 // 7.3 If the expected value is a RegExp object, the actual value is
6396 // equivalent if it is also a RegExp object with the same source and
6397 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
6398 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
6399 return actual.source === expected.source &&
6400 actual.global === expected.global &&
6401 actual.multiline === expected.multiline &&
6402 actual.lastIndex === expected.lastIndex &&
6403 actual.ignoreCase === expected.ignoreCase;
6404
6405 // 7.4. Other pairs that do not both pass typeof value == 'object',
6406 // equivalence is determined by ==.
6407 } else if ((actual === null || typeof actual !== 'object') &&
6408 (expected === null || typeof expected !== 'object')) {
6409 return strict ? actual === expected : actual == expected;
6410
6411 // If both values are instances of typed arrays, wrap their underlying
6412 // ArrayBuffers in a Buffer each to increase performance
6413 // This optimization requires the arrays to have the same type as checked by
6414 // Object.prototype.toString (aka pToString). Never perform binary
6415 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
6416 // bit patterns are not identical.
6417 } else if (isView(actual) && isView(expected) &&
6418 pToString(actual) === pToString(expected) &&
6419 !(actual instanceof Float32Array ||
6420 actual instanceof Float64Array)) {
6421 return compare(new Uint8Array(actual.buffer),
6422 new Uint8Array(expected.buffer)) === 0;
6423
6424 // 7.5 For all other Object pairs, including Array objects, equivalence is
6425 // determined by having the same number of owned properties (as verified
6426 // with Object.prototype.hasOwnProperty.call), the same set of keys
6427 // (although not necessarily the same order), equivalent values for every
6428 // corresponding key, and an identical 'prototype' property. Note: this
6429 // accounts for both named and indexed properties on Arrays.
6430 } else if (isBuffer(actual) !== isBuffer(expected)) {
6431 return false;
6432 } else {
6433 memos = memos || {actual: [], expected: []};
6434
6435 var actualIndex = memos.actual.indexOf(actual);
6436 if (actualIndex !== -1) {
6437 if (actualIndex === memos.expected.indexOf(expected)) {
6438 return true;
6439 }
6440 }
6441
6442 memos.actual.push(actual);
6443 memos.expected.push(expected);
6444
6445 return objEquiv(actual, expected, strict, memos);
6446 }
6447}
6448
6449function isArguments(object) {
6450 return Object.prototype.toString.call(object) == '[object Arguments]';
6451}
6452
6453function objEquiv(a, b, strict, actualVisitedObjects) {
6454 if (a === null || a === undefined || b === null || b === undefined)
6455 return false;
6456 // if one is a primitive, the other must be same
6457 if (util.isPrimitive(a) || util.isPrimitive(b))
6458 return a === b;
6459 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
6460 return false;
6461 var aIsArgs = isArguments(a);
6462 var bIsArgs = isArguments(b);
6463 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
6464 return false;
6465 if (aIsArgs) {
6466 a = pSlice.call(a);
6467 b = pSlice.call(b);
6468 return _deepEqual(a, b, strict);
6469 }
6470 var ka = objectKeys(a);
6471 var kb = objectKeys(b);
6472 var key, i;
6473 // having the same number of owned properties (keys incorporates
6474 // hasOwnProperty)
6475 if (ka.length !== kb.length)
6476 return false;
6477 //the same set of keys (although not necessarily the same order),
6478 ka.sort();
6479 kb.sort();
6480 //~~~cheap key test
6481 for (i = ka.length - 1; i >= 0; i--) {
6482 if (ka[i] !== kb[i])
6483 return false;
6484 }
6485 //equivalent values for every corresponding key, and
6486 //~~~possibly expensive deep test
6487 for (i = ka.length - 1; i >= 0; i--) {
6488 key = ka[i];
6489 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
6490 return false;
6491 }
6492 return true;
6493}
6494
6495// 8. The non-equivalence assertion tests for any deep inequality.
6496// assert.notDeepEqual(actual, expected, message_opt);
6497
6498assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
6499 if (_deepEqual(actual, expected, false)) {
6500 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
6501 }
6502};
6503
6504assert.notDeepStrictEqual = notDeepStrictEqual;
6505function notDeepStrictEqual(actual, expected, message) {
6506 if (_deepEqual(actual, expected, true)) {
6507 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
6508 }
6509}
6510
6511
6512// 9. The strict equality assertion tests strict equality, as determined by ===.
6513// assert.strictEqual(actual, expected, message_opt);
6514
6515assert.strictEqual = function strictEqual(actual, expected, message) {
6516 if (actual !== expected) {
6517 fail(actual, expected, message, '===', assert.strictEqual);
6518 }
6519};
6520
6521// 10. The strict non-equality assertion tests for strict inequality, as
6522// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
6523
6524assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
6525 if (actual === expected) {
6526 fail(actual, expected, message, '!==', assert.notStrictEqual);
6527 }
6528};
6529
6530function expectedException(actual, expected) {
6531 if (!actual || !expected) {
6532 return false;
6533 }
6534
6535 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
6536 return expected.test(actual);
6537 }
6538
6539 try {
6540 if (actual instanceof expected) {
6541 return true;
6542 }
6543 } catch (e) {
6544 // Ignore. The instanceof check doesn't work for arrow functions.
6545 }
6546
6547 if (Error.isPrototypeOf(expected)) {
6548 return false;
6549 }
6550
6551 return expected.call({}, actual) === true;
6552}
6553
6554function _tryBlock(block) {
6555 var error;
6556 try {
6557 block();
6558 } catch (e) {
6559 error = e;
6560 }
6561 return error;
6562}
6563
6564function _throws(shouldThrow, block, expected, message) {
6565 var actual;
6566
6567 if (typeof block !== 'function') {
6568 throw new TypeError('"block" argument must be a function');
6569 }
6570
6571 if (typeof expected === 'string') {
6572 message = expected;
6573 expected = null;
6574 }
6575
6576 actual = _tryBlock(block);
6577
6578 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
6579 (message ? ' ' + message : '.');
6580
6581 if (shouldThrow && !actual) {
6582 fail(actual, expected, 'Missing expected exception' + message);
6583 }
6584
6585 var userProvidedMessage = typeof message === 'string';
6586 var isUnwantedException = !shouldThrow && util.isError(actual);
6587 var isUnexpectedException = !shouldThrow && actual && !expected;
6588
6589 if ((isUnwantedException &&
6590 userProvidedMessage &&
6591 expectedException(actual, expected)) ||
6592 isUnexpectedException) {
6593 fail(actual, expected, 'Got unwanted exception' + message);
6594 }
6595
6596 if ((shouldThrow && actual && expected &&
6597 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
6598 throw actual;
6599 }
6600}
6601
6602// 11. Expected to throw an error:
6603// assert.throws(block, Error_opt, message_opt);
6604
6605assert.throws = function(block, /*optional*/error, /*optional*/message) {
6606 _throws(true, block, error, message);
6607};
6608
6609// EXTENSION! This is annoying to write outside this module.
6610assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
6611 _throws(false, block, error, message);
6612};
6613
6614assert.ifError = function(err) { if (err) throw err; };
6615
6616// Expose a strict only variant of assert
6617function strict(value, message) {
6618 if (!value) fail(value, true, message, '==', strict);
6619}
6620assert.strict = objectAssign(strict, assert, {
6621 equal: assert.strictEqual,
6622 deepEqual: assert.deepStrictEqual,
6623 notEqual: assert.notStrictEqual,
6624 notDeepEqual: assert.notDeepStrictEqual
6625});
6626assert.strict.strict = assert.strict;
6627
6628var objectKeys = Object.keys || function (obj) {
6629 var keys = [];
6630 for (var key in obj) {
6631 if (hasOwn.call(obj, key)) keys.push(key);
6632 }
6633 return keys;
6634};
6635
6636}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6637},{"object-assign":161,"util/":25}],23:[function(require,module,exports){
6638if (typeof Object.create === 'function') {
6639 // implementation from standard node.js 'util' module
6640 module.exports = function inherits(ctor, superCtor) {
6641 ctor.super_ = superCtor
6642 ctor.prototype = Object.create(superCtor.prototype, {
6643 constructor: {
6644 value: ctor,
6645 enumerable: false,
6646 writable: true,
6647 configurable: true
6648 }
6649 });
6650 };
6651} else {
6652 // old school shim for old browsers
6653 module.exports = function inherits(ctor, superCtor) {
6654 ctor.super_ = superCtor
6655 var TempCtor = function () {}
6656 TempCtor.prototype = superCtor.prototype
6657 ctor.prototype = new TempCtor()
6658 ctor.prototype.constructor = ctor
6659 }
6660}
6661
6662},{}],24:[function(require,module,exports){
6663module.exports = function isBuffer(arg) {
6664 return arg && typeof arg === 'object'
6665 && typeof arg.copy === 'function'
6666 && typeof arg.fill === 'function'
6667 && typeof arg.readUInt8 === 'function';
6668}
6669},{}],25:[function(require,module,exports){
6670(function (process,global){(function (){
6671// Copyright Joyent, Inc. and other Node contributors.
6672//
6673// Permission is hereby granted, free of charge, to any person obtaining a
6674// copy of this software and associated documentation files (the
6675// "Software"), to deal in the Software without restriction, including
6676// without limitation the rights to use, copy, modify, merge, publish,
6677// distribute, sublicense, and/or sell copies of the Software, and to permit
6678// persons to whom the Software is furnished to do so, subject to the
6679// following conditions:
6680//
6681// The above copyright notice and this permission notice shall be included
6682// in all copies or substantial portions of the Software.
6683//
6684// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6685// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6686// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6687// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6688// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6689// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6690// USE OR OTHER DEALINGS IN THE SOFTWARE.
6691
6692var formatRegExp = /%[sdj%]/g;
6693exports.format = function(f) {
6694 if (!isString(f)) {
6695 var objects = [];
6696 for (var i = 0; i < arguments.length; i++) {
6697 objects.push(inspect(arguments[i]));
6698 }
6699 return objects.join(' ');
6700 }
6701
6702 var i = 1;
6703 var args = arguments;
6704 var len = args.length;
6705 var str = String(f).replace(formatRegExp, function(x) {
6706 if (x === '%%') return '%';
6707 if (i >= len) return x;
6708 switch (x) {
6709 case '%s': return String(args[i++]);
6710 case '%d': return Number(args[i++]);
6711 case '%j':
6712 try {
6713 return JSON.stringify(args[i++]);
6714 } catch (_) {
6715 return '[Circular]';
6716 }
6717 default:
6718 return x;
6719 }
6720 });
6721 for (var x = args[i]; i < len; x = args[++i]) {
6722 if (isNull(x) || !isObject(x)) {
6723 str += ' ' + x;
6724 } else {
6725 str += ' ' + inspect(x);
6726 }
6727 }
6728 return str;
6729};
6730
6731
6732// Mark that a method should not be used.
6733// Returns a modified function which warns once by default.
6734// If --no-deprecation is set, then it is a no-op.
6735exports.deprecate = function(fn, msg) {
6736 // Allow for deprecating things in the process of starting up.
6737 if (isUndefined(global.process)) {
6738 return function() {
6739 return exports.deprecate(fn, msg).apply(this, arguments);
6740 };
6741 }
6742
6743 if (process.noDeprecation === true) {
6744 return fn;
6745 }
6746
6747 var warned = false;
6748 function deprecated() {
6749 if (!warned) {
6750 if (process.throwDeprecation) {
6751 throw new Error(msg);
6752 } else if (process.traceDeprecation) {
6753 console.trace(msg);
6754 } else {
6755 console.error(msg);
6756 }
6757 warned = true;
6758 }
6759 return fn.apply(this, arguments);
6760 }
6761
6762 return deprecated;
6763};
6764
6765
6766var debugs = {};
6767var debugEnviron;
6768exports.debuglog = function(set) {
6769 if (isUndefined(debugEnviron))
6770 debugEnviron = process.env.NODE_DEBUG || '';
6771 set = set.toUpperCase();
6772 if (!debugs[set]) {
6773 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
6774 var pid = process.pid;
6775 debugs[set] = function() {
6776 var msg = exports.format.apply(exports, arguments);
6777 console.error('%s %d: %s', set, pid, msg);
6778 };
6779 } else {
6780 debugs[set] = function() {};
6781 }
6782 }
6783 return debugs[set];
6784};
6785
6786
6787/**
6788 * Echos the value of a value. Trys to print the value out
6789 * in the best way possible given the different types.
6790 *
6791 * @param {Object} obj The object to print out.
6792 * @param {Object} opts Optional options object that alters the output.
6793 */
6794/* legacy: obj, showHidden, depth, colors*/
6795function inspect(obj, opts) {
6796 // default options
6797 var ctx = {
6798 seen: [],
6799 stylize: stylizeNoColor
6800 };
6801 // legacy...
6802 if (arguments.length >= 3) ctx.depth = arguments[2];
6803 if (arguments.length >= 4) ctx.colors = arguments[3];
6804 if (isBoolean(opts)) {
6805 // legacy...
6806 ctx.showHidden = opts;
6807 } else if (opts) {
6808 // got an "options" object
6809 exports._extend(ctx, opts);
6810 }
6811 // set default options
6812 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
6813 if (isUndefined(ctx.depth)) ctx.depth = 2;
6814 if (isUndefined(ctx.colors)) ctx.colors = false;
6815 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
6816 if (ctx.colors) ctx.stylize = stylizeWithColor;
6817 return formatValue(ctx, obj, ctx.depth);
6818}
6819exports.inspect = inspect;
6820
6821
6822// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
6823inspect.colors = {
6824 'bold' : [1, 22],
6825 'italic' : [3, 23],
6826 'underline' : [4, 24],
6827 'inverse' : [7, 27],
6828 'white' : [37, 39],
6829 'grey' : [90, 39],
6830 'black' : [30, 39],
6831 'blue' : [34, 39],
6832 'cyan' : [36, 39],
6833 'green' : [32, 39],
6834 'magenta' : [35, 39],
6835 'red' : [31, 39],
6836 'yellow' : [33, 39]
6837};
6838
6839// Don't use 'blue' not visible on cmd.exe
6840inspect.styles = {
6841 'special': 'cyan',
6842 'number': 'yellow',
6843 'boolean': 'yellow',
6844 'undefined': 'grey',
6845 'null': 'bold',
6846 'string': 'green',
6847 'date': 'magenta',
6848 // "name": intentionally not styling
6849 'regexp': 'red'
6850};
6851
6852
6853function stylizeWithColor(str, styleType) {
6854 var style = inspect.styles[styleType];
6855
6856 if (style) {
6857 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
6858 '\u001b[' + inspect.colors[style][1] + 'm';
6859 } else {
6860 return str;
6861 }
6862}
6863
6864
6865function stylizeNoColor(str, styleType) {
6866 return str;
6867}
6868
6869
6870function arrayToHash(array) {
6871 var hash = {};
6872
6873 array.forEach(function(val, idx) {
6874 hash[val] = true;
6875 });
6876
6877 return hash;
6878}
6879
6880
6881function formatValue(ctx, value, recurseTimes) {
6882 // Provide a hook for user-specified inspect functions.
6883 // Check that value is an object with an inspect function on it
6884 if (ctx.customInspect &&
6885 value &&
6886 isFunction(value.inspect) &&
6887 // Filter out the util module, it's inspect function is special
6888 value.inspect !== exports.inspect &&
6889 // Also filter out any prototype objects using the circular check.
6890 !(value.constructor && value.constructor.prototype === value)) {
6891 var ret = value.inspect(recurseTimes, ctx);
6892 if (!isString(ret)) {
6893 ret = formatValue(ctx, ret, recurseTimes);
6894 }
6895 return ret;
6896 }
6897
6898 // Primitive types cannot have properties
6899 var primitive = formatPrimitive(ctx, value);
6900 if (primitive) {
6901 return primitive;
6902 }
6903
6904 // Look up the keys of the object.
6905 var keys = Object.keys(value);
6906 var visibleKeys = arrayToHash(keys);
6907
6908 if (ctx.showHidden) {
6909 keys = Object.getOwnPropertyNames(value);
6910 }
6911
6912 // IE doesn't make error fields non-enumerable
6913 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
6914 if (isError(value)
6915 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
6916 return formatError(value);
6917 }
6918
6919 // Some type of object without properties can be shortcutted.
6920 if (keys.length === 0) {
6921 if (isFunction(value)) {
6922 var name = value.name ? ': ' + value.name : '';
6923 return ctx.stylize('[Function' + name + ']', 'special');
6924 }
6925 if (isRegExp(value)) {
6926 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6927 }
6928 if (isDate(value)) {
6929 return ctx.stylize(Date.prototype.toString.call(value), 'date');
6930 }
6931 if (isError(value)) {
6932 return formatError(value);
6933 }
6934 }
6935
6936 var base = '', array = false, braces = ['{', '}'];
6937
6938 // Make Array say that they are Array
6939 if (isArray(value)) {
6940 array = true;
6941 braces = ['[', ']'];
6942 }
6943
6944 // Make functions say that they are functions
6945 if (isFunction(value)) {
6946 var n = value.name ? ': ' + value.name : '';
6947 base = ' [Function' + n + ']';
6948 }
6949
6950 // Make RegExps say that they are RegExps
6951 if (isRegExp(value)) {
6952 base = ' ' + RegExp.prototype.toString.call(value);
6953 }
6954
6955 // Make dates with properties first say the date
6956 if (isDate(value)) {
6957 base = ' ' + Date.prototype.toUTCString.call(value);
6958 }
6959
6960 // Make error with message first say the error
6961 if (isError(value)) {
6962 base = ' ' + formatError(value);
6963 }
6964
6965 if (keys.length === 0 && (!array || value.length == 0)) {
6966 return braces[0] + base + braces[1];
6967 }
6968
6969 if (recurseTimes < 0) {
6970 if (isRegExp(value)) {
6971 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6972 } else {
6973 return ctx.stylize('[Object]', 'special');
6974 }
6975 }
6976
6977 ctx.seen.push(value);
6978
6979 var output;
6980 if (array) {
6981 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
6982 } else {
6983 output = keys.map(function(key) {
6984 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
6985 });
6986 }
6987
6988 ctx.seen.pop();
6989
6990 return reduceToSingleString(output, base, braces);
6991}
6992
6993
6994function formatPrimitive(ctx, value) {
6995 if (isUndefined(value))
6996 return ctx.stylize('undefined', 'undefined');
6997 if (isString(value)) {
6998 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
6999 .replace(/'/g, "\\'")
7000 .replace(/\\"/g, '"') + '\'';
7001 return ctx.stylize(simple, 'string');
7002 }
7003 if (isNumber(value))
7004 return ctx.stylize('' + value, 'number');
7005 if (isBoolean(value))
7006 return ctx.stylize('' + value, 'boolean');
7007 // For some reason typeof null is "object", so special case here.
7008 if (isNull(value))
7009 return ctx.stylize('null', 'null');
7010}
7011
7012
7013function formatError(value) {
7014 return '[' + Error.prototype.toString.call(value) + ']';
7015}
7016
7017
7018function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
7019 var output = [];
7020 for (var i = 0, l = value.length; i < l; ++i) {
7021 if (hasOwnProperty(value, String(i))) {
7022 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7023 String(i), true));
7024 } else {
7025 output.push('');
7026 }
7027 }
7028 keys.forEach(function(key) {
7029 if (!key.match(/^\d+$/)) {
7030 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7031 key, true));
7032 }
7033 });
7034 return output;
7035}
7036
7037
7038function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
7039 var name, str, desc;
7040 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
7041 if (desc.get) {
7042 if (desc.set) {
7043 str = ctx.stylize('[Getter/Setter]', 'special');
7044 } else {
7045 str = ctx.stylize('[Getter]', 'special');
7046 }
7047 } else {
7048 if (desc.set) {
7049 str = ctx.stylize('[Setter]', 'special');
7050 }
7051 }
7052 if (!hasOwnProperty(visibleKeys, key)) {
7053 name = '[' + key + ']';
7054 }
7055 if (!str) {
7056 if (ctx.seen.indexOf(desc.value) < 0) {
7057 if (isNull(recurseTimes)) {
7058 str = formatValue(ctx, desc.value, null);
7059 } else {
7060 str = formatValue(ctx, desc.value, recurseTimes - 1);
7061 }
7062 if (str.indexOf('\n') > -1) {
7063 if (array) {
7064 str = str.split('\n').map(function(line) {
7065 return ' ' + line;
7066 }).join('\n').substr(2);
7067 } else {
7068 str = '\n' + str.split('\n').map(function(line) {
7069 return ' ' + line;
7070 }).join('\n');
7071 }
7072 }
7073 } else {
7074 str = ctx.stylize('[Circular]', 'special');
7075 }
7076 }
7077 if (isUndefined(name)) {
7078 if (array && key.match(/^\d+$/)) {
7079 return str;
7080 }
7081 name = JSON.stringify('' + key);
7082 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
7083 name = name.substr(1, name.length - 2);
7084 name = ctx.stylize(name, 'name');
7085 } else {
7086 name = name.replace(/'/g, "\\'")
7087 .replace(/\\"/g, '"')
7088 .replace(/(^"|"$)/g, "'");
7089 name = ctx.stylize(name, 'string');
7090 }
7091 }
7092
7093 return name + ': ' + str;
7094}
7095
7096
7097function reduceToSingleString(output, base, braces) {
7098 var numLinesEst = 0;
7099 var length = output.reduce(function(prev, cur) {
7100 numLinesEst++;
7101 if (cur.indexOf('\n') >= 0) numLinesEst++;
7102 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
7103 }, 0);
7104
7105 if (length > 60) {
7106 return braces[0] +
7107 (base === '' ? '' : base + '\n ') +
7108 ' ' +
7109 output.join(',\n ') +
7110 ' ' +
7111 braces[1];
7112 }
7113
7114 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
7115}
7116
7117
7118// NOTE: These type checking functions intentionally don't use `instanceof`
7119// because it is fragile and can be easily faked with `Object.create()`.
7120function isArray(ar) {
7121 return Array.isArray(ar);
7122}
7123exports.isArray = isArray;
7124
7125function isBoolean(arg) {
7126 return typeof arg === 'boolean';
7127}
7128exports.isBoolean = isBoolean;
7129
7130function isNull(arg) {
7131 return arg === null;
7132}
7133exports.isNull = isNull;
7134
7135function isNullOrUndefined(arg) {
7136 return arg == null;
7137}
7138exports.isNullOrUndefined = isNullOrUndefined;
7139
7140function isNumber(arg) {
7141 return typeof arg === 'number';
7142}
7143exports.isNumber = isNumber;
7144
7145function isString(arg) {
7146 return typeof arg === 'string';
7147}
7148exports.isString = isString;
7149
7150function isSymbol(arg) {
7151 return typeof arg === 'symbol';
7152}
7153exports.isSymbol = isSymbol;
7154
7155function isUndefined(arg) {
7156 return arg === void 0;
7157}
7158exports.isUndefined = isUndefined;
7159
7160function isRegExp(re) {
7161 return isObject(re) && objectToString(re) === '[object RegExp]';
7162}
7163exports.isRegExp = isRegExp;
7164
7165function isObject(arg) {
7166 return typeof arg === 'object' && arg !== null;
7167}
7168exports.isObject = isObject;
7169
7170function isDate(d) {
7171 return isObject(d) && objectToString(d) === '[object Date]';
7172}
7173exports.isDate = isDate;
7174
7175function isError(e) {
7176 return isObject(e) &&
7177 (objectToString(e) === '[object Error]' || e instanceof Error);
7178}
7179exports.isError = isError;
7180
7181function isFunction(arg) {
7182 return typeof arg === 'function';
7183}
7184exports.isFunction = isFunction;
7185
7186function isPrimitive(arg) {
7187 return arg === null ||
7188 typeof arg === 'boolean' ||
7189 typeof arg === 'number' ||
7190 typeof arg === 'string' ||
7191 typeof arg === 'symbol' || // ES6 symbol
7192 typeof arg === 'undefined';
7193}
7194exports.isPrimitive = isPrimitive;
7195
7196exports.isBuffer = require('./support/isBuffer');
7197
7198function objectToString(o) {
7199 return Object.prototype.toString.call(o);
7200}
7201
7202
7203function pad(n) {
7204 return n < 10 ? '0' + n.toString(10) : n.toString(10);
7205}
7206
7207
7208var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7209 'Oct', 'Nov', 'Dec'];
7210
7211// 26 Feb 16:19:34
7212function timestamp() {
7213 var d = new Date();
7214 var time = [pad(d.getHours()),
7215 pad(d.getMinutes()),
7216 pad(d.getSeconds())].join(':');
7217 return [d.getDate(), months[d.getMonth()], time].join(' ');
7218}
7219
7220
7221// log is just a thin wrapper to console.log that prepends a timestamp
7222exports.log = function() {
7223 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
7224};
7225
7226
7227/**
7228 * Inherit the prototype methods from one constructor into another.
7229 *
7230 * The Function.prototype.inherits from lang.js rewritten as a standalone
7231 * function (not on Function.prototype). NOTE: If this file is to be loaded
7232 * during bootstrapping this function needs to be rewritten using some native
7233 * functions as prototype setup using normal JavaScript does not work as
7234 * expected during bootstrapping (see mirror.js in r114903).
7235 *
7236 * @param {function} ctor Constructor function which needs to inherit the
7237 * prototype.
7238 * @param {function} superCtor Constructor function to inherit prototype from.
7239 */
7240exports.inherits = require('inherits');
7241
7242exports._extend = function(origin, add) {
7243 // Don't do anything if add isn't an object
7244 if (!add || !isObject(add)) return origin;
7245
7246 var keys = Object.keys(add);
7247 var i = keys.length;
7248 while (i--) {
7249 origin[keys[i]] = add[keys[i]];
7250 }
7251 return origin;
7252};
7253
7254function hasOwnProperty(obj, prop) {
7255 return Object.prototype.hasOwnProperty.call(obj, prop);
7256}
7257
7258}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7259},{"./support/isBuffer":24,"_process":174,"inherits":23}],26:[function(require,module,exports){
7260'use strict'
7261
7262exports.byteLength = byteLength
7263exports.toByteArray = toByteArray
7264exports.fromByteArray = fromByteArray
7265
7266var lookup = []
7267var revLookup = []
7268var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
7269
7270var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
7271for (var i = 0, len = code.length; i < len; ++i) {
7272 lookup[i] = code[i]
7273 revLookup[code.charCodeAt(i)] = i
7274}
7275
7276// Support decoding URL-safe base64 strings, as Node.js does.
7277// See: https://en.wikipedia.org/wiki/Base64#URL_applications
7278revLookup['-'.charCodeAt(0)] = 62
7279revLookup['_'.charCodeAt(0)] = 63
7280
7281function getLens (b64) {
7282 var len = b64.length
7283
7284 if (len % 4 > 0) {
7285 throw new Error('Invalid string. Length must be a multiple of 4')
7286 }
7287
7288 // Trim off extra bytes after placeholder bytes are found
7289 // See: https://github.com/beatgammit/base64-js/issues/42
7290 var validLen = b64.indexOf('=')
7291 if (validLen === -1) validLen = len
7292
7293 var placeHoldersLen = validLen === len
7294 ? 0
7295 : 4 - (validLen % 4)
7296
7297 return [validLen, placeHoldersLen]
7298}
7299
7300// base64 is 4/3 + up to two characters of the original data
7301function byteLength (b64) {
7302 var lens = getLens(b64)
7303 var validLen = lens[0]
7304 var placeHoldersLen = lens[1]
7305 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
7306}
7307
7308function _byteLength (b64, validLen, placeHoldersLen) {
7309 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
7310}
7311
7312function toByteArray (b64) {
7313 var tmp
7314 var lens = getLens(b64)
7315 var validLen = lens[0]
7316 var placeHoldersLen = lens[1]
7317
7318 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
7319
7320 var curByte = 0
7321
7322 // if there are placeholders, only get up to the last complete 4 chars
7323 var len = placeHoldersLen > 0
7324 ? validLen - 4
7325 : validLen
7326
7327 var i
7328 for (i = 0; i < len; i += 4) {
7329 tmp =
7330 (revLookup[b64.charCodeAt(i)] << 18) |
7331 (revLookup[b64.charCodeAt(i + 1)] << 12) |
7332 (revLookup[b64.charCodeAt(i + 2)] << 6) |
7333 revLookup[b64.charCodeAt(i + 3)]
7334 arr[curByte++] = (tmp >> 16) & 0xFF
7335 arr[curByte++] = (tmp >> 8) & 0xFF
7336 arr[curByte++] = tmp & 0xFF
7337 }
7338
7339 if (placeHoldersLen === 2) {
7340 tmp =
7341 (revLookup[b64.charCodeAt(i)] << 2) |
7342 (revLookup[b64.charCodeAt(i + 1)] >> 4)
7343 arr[curByte++] = tmp & 0xFF
7344 }
7345
7346 if (placeHoldersLen === 1) {
7347 tmp =
7348 (revLookup[b64.charCodeAt(i)] << 10) |
7349 (revLookup[b64.charCodeAt(i + 1)] << 4) |
7350 (revLookup[b64.charCodeAt(i + 2)] >> 2)
7351 arr[curByte++] = (tmp >> 8) & 0xFF
7352 arr[curByte++] = tmp & 0xFF
7353 }
7354
7355 return arr
7356}
7357
7358function tripletToBase64 (num) {
7359 return lookup[num >> 18 & 0x3F] +
7360 lookup[num >> 12 & 0x3F] +
7361 lookup[num >> 6 & 0x3F] +
7362 lookup[num & 0x3F]
7363}
7364
7365function encodeChunk (uint8, start, end) {
7366 var tmp
7367 var output = []
7368 for (var i = start; i < end; i += 3) {
7369 tmp =
7370 ((uint8[i] << 16) & 0xFF0000) +
7371 ((uint8[i + 1] << 8) & 0xFF00) +
7372 (uint8[i + 2] & 0xFF)
7373 output.push(tripletToBase64(tmp))
7374 }
7375 return output.join('')
7376}
7377
7378function fromByteArray (uint8) {
7379 var tmp
7380 var len = uint8.length
7381 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
7382 var parts = []
7383 var maxChunkLength = 16383 // must be multiple of 3
7384
7385 // go through the array every three bytes, we'll deal with trailing stuff later
7386 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
7387 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
7388 }
7389
7390 // pad the end with zeros, but make sure to not forget the extra bytes
7391 if (extraBytes === 1) {
7392 tmp = uint8[len - 1]
7393 parts.push(
7394 lookup[tmp >> 2] +
7395 lookup[(tmp << 4) & 0x3F] +
7396 '=='
7397 )
7398 } else if (extraBytes === 2) {
7399 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
7400 parts.push(
7401 lookup[tmp >> 10] +
7402 lookup[(tmp >> 4) & 0x3F] +
7403 lookup[(tmp << 2) & 0x3F] +
7404 '='
7405 )
7406 }
7407
7408 return parts.join('')
7409}
7410
7411},{}],27:[function(require,module,exports){
7412// (public) Constructor
7413function BigInteger(a, b, c) {
7414 if (!(this instanceof BigInteger))
7415 return new BigInteger(a, b, c)
7416
7417 if (a != null) {
7418 if ("number" == typeof a) this.fromNumber(a, b, c)
7419 else if (b == null && "string" != typeof a) this.fromString(a, 256)
7420 else this.fromString(a, b)
7421 }
7422}
7423
7424var proto = BigInteger.prototype
7425
7426// duck-typed isBigInteger
7427proto.__bigi = require('../package.json').version
7428BigInteger.isBigInteger = function (obj, check_ver) {
7429 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
7430}
7431
7432// Bits per digit
7433var dbits
7434
7435// am: Compute w_j += (x*this_i), propagate carries,
7436// c is initial carry, returns final carry.
7437// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
7438// We need to select the fastest one that works in this environment.
7439
7440// am1: use a single mult and divide to get the high bits,
7441// max digit bits should be 26 because
7442// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
7443function am1(i, x, w, j, c, n) {
7444 while (--n >= 0) {
7445 var v = x * this[i++] + w[j] + c
7446 c = Math.floor(v / 0x4000000)
7447 w[j++] = v & 0x3ffffff
7448 }
7449 return c
7450}
7451// am2 avoids a big mult-and-extract completely.
7452// Max digit bits should be <= 30 because we do bitwise ops
7453// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
7454function am2(i, x, w, j, c, n) {
7455 var xl = x & 0x7fff,
7456 xh = x >> 15
7457 while (--n >= 0) {
7458 var l = this[i] & 0x7fff
7459 var h = this[i++] >> 15
7460 var m = xh * l + h * xl
7461 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
7462 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
7463 w[j++] = l & 0x3fffffff
7464 }
7465 return c
7466}
7467// Alternately, set max digit bits to 28 since some
7468// browsers slow down when dealing with 32-bit numbers.
7469function am3(i, x, w, j, c, n) {
7470 var xl = x & 0x3fff,
7471 xh = x >> 14
7472 while (--n >= 0) {
7473 var l = this[i] & 0x3fff
7474 var h = this[i++] >> 14
7475 var m = xh * l + h * xl
7476 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
7477 c = (l >> 28) + (m >> 14) + xh * h
7478 w[j++] = l & 0xfffffff
7479 }
7480 return c
7481}
7482
7483// wtf?
7484BigInteger.prototype.am = am1
7485dbits = 26
7486
7487BigInteger.prototype.DB = dbits
7488BigInteger.prototype.DM = ((1 << dbits) - 1)
7489var DV = BigInteger.prototype.DV = (1 << dbits)
7490
7491var BI_FP = 52
7492BigInteger.prototype.FV = Math.pow(2, BI_FP)
7493BigInteger.prototype.F1 = BI_FP - dbits
7494BigInteger.prototype.F2 = 2 * dbits - BI_FP
7495
7496// Digit conversions
7497var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
7498var BI_RC = new Array()
7499var rr, vv
7500rr = "0".charCodeAt(0)
7501for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
7502rr = "a".charCodeAt(0)
7503for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
7504rr = "A".charCodeAt(0)
7505for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
7506
7507function int2char(n) {
7508 return BI_RM.charAt(n)
7509}
7510
7511function intAt(s, i) {
7512 var c = BI_RC[s.charCodeAt(i)]
7513 return (c == null) ? -1 : c
7514}
7515
7516// (protected) copy this to r
7517function bnpCopyTo(r) {
7518 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
7519 r.t = this.t
7520 r.s = this.s
7521}
7522
7523// (protected) set from integer value x, -DV <= x < DV
7524function bnpFromInt(x) {
7525 this.t = 1
7526 this.s = (x < 0) ? -1 : 0
7527 if (x > 0) this[0] = x
7528 else if (x < -1) this[0] = x + DV
7529 else this.t = 0
7530}
7531
7532// return bigint initialized to value
7533function nbv(i) {
7534 var r = new BigInteger()
7535 r.fromInt(i)
7536 return r
7537}
7538
7539// (protected) set from string and radix
7540function bnpFromString(s, b) {
7541 var self = this
7542
7543 var k
7544 if (b == 16) k = 4
7545 else if (b == 8) k = 3
7546 else if (b == 256) k = 8; // byte array
7547 else if (b == 2) k = 1
7548 else if (b == 32) k = 5
7549 else if (b == 4) k = 2
7550 else {
7551 self.fromRadix(s, b)
7552 return
7553 }
7554 self.t = 0
7555 self.s = 0
7556 var i = s.length,
7557 mi = false,
7558 sh = 0
7559 while (--i >= 0) {
7560 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
7561 if (x < 0) {
7562 if (s.charAt(i) == "-") mi = true
7563 continue
7564 }
7565 mi = false
7566 if (sh == 0)
7567 self[self.t++] = x
7568 else if (sh + k > self.DB) {
7569 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
7570 self[self.t++] = (x >> (self.DB - sh))
7571 } else
7572 self[self.t - 1] |= x << sh
7573 sh += k
7574 if (sh >= self.DB) sh -= self.DB
7575 }
7576 if (k == 8 && (s[0] & 0x80) != 0) {
7577 self.s = -1
7578 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
7579 }
7580 self.clamp()
7581 if (mi) BigInteger.ZERO.subTo(self, self)
7582}
7583
7584// (protected) clamp off excess high words
7585function bnpClamp() {
7586 var c = this.s & this.DM
7587 while (this.t > 0 && this[this.t - 1] == c)--this.t
7588}
7589
7590// (public) return string representation in given radix
7591function bnToString(b) {
7592 var self = this
7593 if (self.s < 0) return "-" + self.negate()
7594 .toString(b)
7595 var k
7596 if (b == 16) k = 4
7597 else if (b == 8) k = 3
7598 else if (b == 2) k = 1
7599 else if (b == 32) k = 5
7600 else if (b == 4) k = 2
7601 else return self.toRadix(b)
7602 var km = (1 << k) - 1,
7603 d, m = false,
7604 r = "",
7605 i = self.t
7606 var p = self.DB - (i * self.DB) % k
7607 if (i-- > 0) {
7608 if (p < self.DB && (d = self[i] >> p) > 0) {
7609 m = true
7610 r = int2char(d)
7611 }
7612 while (i >= 0) {
7613 if (p < k) {
7614 d = (self[i] & ((1 << p) - 1)) << (k - p)
7615 d |= self[--i] >> (p += self.DB - k)
7616 } else {
7617 d = (self[i] >> (p -= k)) & km
7618 if (p <= 0) {
7619 p += self.DB
7620 --i
7621 }
7622 }
7623 if (d > 0) m = true
7624 if (m) r += int2char(d)
7625 }
7626 }
7627 return m ? r : "0"
7628}
7629
7630// (public) -this
7631function bnNegate() {
7632 var r = new BigInteger()
7633 BigInteger.ZERO.subTo(this, r)
7634 return r
7635}
7636
7637// (public) |this|
7638function bnAbs() {
7639 return (this.s < 0) ? this.negate() : this
7640}
7641
7642// (public) return + if this > a, - if this < a, 0 if equal
7643function bnCompareTo(a) {
7644 var r = this.s - a.s
7645 if (r != 0) return r
7646 var i = this.t
7647 r = i - a.t
7648 if (r != 0) return (this.s < 0) ? -r : r
7649 while (--i >= 0)
7650 if ((r = this[i] - a[i]) != 0) return r
7651 return 0
7652}
7653
7654// returns bit length of the integer x
7655function nbits(x) {
7656 var r = 1,
7657 t
7658 if ((t = x >>> 16) != 0) {
7659 x = t
7660 r += 16
7661 }
7662 if ((t = x >> 8) != 0) {
7663 x = t
7664 r += 8
7665 }
7666 if ((t = x >> 4) != 0) {
7667 x = t
7668 r += 4
7669 }
7670 if ((t = x >> 2) != 0) {
7671 x = t
7672 r += 2
7673 }
7674 if ((t = x >> 1) != 0) {
7675 x = t
7676 r += 1
7677 }
7678 return r
7679}
7680
7681// (public) return the number of bits in "this"
7682function bnBitLength() {
7683 if (this.t <= 0) return 0
7684 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
7685}
7686
7687// (public) return the number of bytes in "this"
7688function bnByteLength() {
7689 return this.bitLength() >> 3
7690}
7691
7692// (protected) r = this << n*DB
7693function bnpDLShiftTo(n, r) {
7694 var i
7695 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
7696 for (i = n - 1; i >= 0; --i) r[i] = 0
7697 r.t = this.t + n
7698 r.s = this.s
7699}
7700
7701// (protected) r = this >> n*DB
7702function bnpDRShiftTo(n, r) {
7703 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
7704 r.t = Math.max(this.t - n, 0)
7705 r.s = this.s
7706}
7707
7708// (protected) r = this << n
7709function bnpLShiftTo(n, r) {
7710 var self = this
7711 var bs = n % self.DB
7712 var cbs = self.DB - bs
7713 var bm = (1 << cbs) - 1
7714 var ds = Math.floor(n / self.DB),
7715 c = (self.s << bs) & self.DM,
7716 i
7717 for (i = self.t - 1; i >= 0; --i) {
7718 r[i + ds + 1] = (self[i] >> cbs) | c
7719 c = (self[i] & bm) << bs
7720 }
7721 for (i = ds - 1; i >= 0; --i) r[i] = 0
7722 r[ds] = c
7723 r.t = self.t + ds + 1
7724 r.s = self.s
7725 r.clamp()
7726}
7727
7728// (protected) r = this >> n
7729function bnpRShiftTo(n, r) {
7730 var self = this
7731 r.s = self.s
7732 var ds = Math.floor(n / self.DB)
7733 if (ds >= self.t) {
7734 r.t = 0
7735 return
7736 }
7737 var bs = n % self.DB
7738 var cbs = self.DB - bs
7739 var bm = (1 << bs) - 1
7740 r[0] = self[ds] >> bs
7741 for (var i = ds + 1; i < self.t; ++i) {
7742 r[i - ds - 1] |= (self[i] & bm) << cbs
7743 r[i - ds] = self[i] >> bs
7744 }
7745 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
7746 r.t = self.t - ds
7747 r.clamp()
7748}
7749
7750// (protected) r = this - a
7751function bnpSubTo(a, r) {
7752 var self = this
7753 var i = 0,
7754 c = 0,
7755 m = Math.min(a.t, self.t)
7756 while (i < m) {
7757 c += self[i] - a[i]
7758 r[i++] = c & self.DM
7759 c >>= self.DB
7760 }
7761 if (a.t < self.t) {
7762 c -= a.s
7763 while (i < self.t) {
7764 c += self[i]
7765 r[i++] = c & self.DM
7766 c >>= self.DB
7767 }
7768 c += self.s
7769 } else {
7770 c += self.s
7771 while (i < a.t) {
7772 c -= a[i]
7773 r[i++] = c & self.DM
7774 c >>= self.DB
7775 }
7776 c -= a.s
7777 }
7778 r.s = (c < 0) ? -1 : 0
7779 if (c < -1) r[i++] = self.DV + c
7780 else if (c > 0) r[i++] = c
7781 r.t = i
7782 r.clamp()
7783}
7784
7785// (protected) r = this * a, r != this,a (HAC 14.12)
7786// "this" should be the larger one if appropriate.
7787function bnpMultiplyTo(a, r) {
7788 var x = this.abs(),
7789 y = a.abs()
7790 var i = x.t
7791 r.t = i + y.t
7792 while (--i >= 0) r[i] = 0
7793 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
7794 r.s = 0
7795 r.clamp()
7796 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
7797}
7798
7799// (protected) r = this^2, r != this (HAC 14.16)
7800function bnpSquareTo(r) {
7801 var x = this.abs()
7802 var i = r.t = 2 * x.t
7803 while (--i >= 0) r[i] = 0
7804 for (i = 0; i < x.t - 1; ++i) {
7805 var c = x.am(i, x[i], r, 2 * i, 0, 1)
7806 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
7807 r[i + x.t] -= x.DV
7808 r[i + x.t + 1] = 1
7809 }
7810 }
7811 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
7812 r.s = 0
7813 r.clamp()
7814}
7815
7816// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
7817// r != q, this != m. q or r may be null.
7818function bnpDivRemTo(m, q, r) {
7819 var self = this
7820 var pm = m.abs()
7821 if (pm.t <= 0) return
7822 var pt = self.abs()
7823 if (pt.t < pm.t) {
7824 if (q != null) q.fromInt(0)
7825 if (r != null) self.copyTo(r)
7826 return
7827 }
7828 if (r == null) r = new BigInteger()
7829 var y = new BigInteger(),
7830 ts = self.s,
7831 ms = m.s
7832 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
7833 if (nsh > 0) {
7834 pm.lShiftTo(nsh, y)
7835 pt.lShiftTo(nsh, r)
7836 } else {
7837 pm.copyTo(y)
7838 pt.copyTo(r)
7839 }
7840 var ys = y.t
7841 var y0 = y[ys - 1]
7842 if (y0 == 0) return
7843 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
7844 var d1 = self.FV / yt,
7845 d2 = (1 << self.F1) / yt,
7846 e = 1 << self.F2
7847 var i = r.t,
7848 j = i - ys,
7849 t = (q == null) ? new BigInteger() : q
7850 y.dlShiftTo(j, t)
7851 if (r.compareTo(t) >= 0) {
7852 r[r.t++] = 1
7853 r.subTo(t, r)
7854 }
7855 BigInteger.ONE.dlShiftTo(ys, t)
7856 t.subTo(y, y); // "negative" y so we can replace sub with am later
7857 while (y.t < ys) y[y.t++] = 0
7858 while (--j >= 0) {
7859 // Estimate quotient digit
7860 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
7861 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
7862 y.dlShiftTo(j, t)
7863 r.subTo(t, r)
7864 while (r[i] < --qd) r.subTo(t, r)
7865 }
7866 }
7867 if (q != null) {
7868 r.drShiftTo(ys, q)
7869 if (ts != ms) BigInteger.ZERO.subTo(q, q)
7870 }
7871 r.t = ys
7872 r.clamp()
7873 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
7874 if (ts < 0) BigInteger.ZERO.subTo(r, r)
7875}
7876
7877// (public) this mod a
7878function bnMod(a) {
7879 var r = new BigInteger()
7880 this.abs()
7881 .divRemTo(a, null, r)
7882 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
7883 return r
7884}
7885
7886// Modular reduction using "classic" algorithm
7887function Classic(m) {
7888 this.m = m
7889}
7890
7891function cConvert(x) {
7892 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
7893 else return x
7894}
7895
7896function cRevert(x) {
7897 return x
7898}
7899
7900function cReduce(x) {
7901 x.divRemTo(this.m, null, x)
7902}
7903
7904function cMulTo(x, y, r) {
7905 x.multiplyTo(y, r)
7906 this.reduce(r)
7907}
7908
7909function cSqrTo(x, r) {
7910 x.squareTo(r)
7911 this.reduce(r)
7912}
7913
7914Classic.prototype.convert = cConvert
7915Classic.prototype.revert = cRevert
7916Classic.prototype.reduce = cReduce
7917Classic.prototype.mulTo = cMulTo
7918Classic.prototype.sqrTo = cSqrTo
7919
7920// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
7921// justification:
7922// xy == 1 (mod m)
7923// xy = 1+km
7924// xy(2-xy) = (1+km)(1-km)
7925// x[y(2-xy)] = 1-k^2m^2
7926// x[y(2-xy)] == 1 (mod m^2)
7927// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
7928// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
7929// JS multiply "overflows" differently from C/C++, so care is needed here.
7930function bnpInvDigit() {
7931 if (this.t < 1) return 0
7932 var x = this[0]
7933 if ((x & 1) == 0) return 0
7934 var y = x & 3; // y == 1/x mod 2^2
7935 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
7936 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
7937 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
7938 // last step - calculate inverse mod DV directly
7939 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
7940 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
7941 // we really want the negative inverse, and -DV < y < DV
7942 return (y > 0) ? this.DV - y : -y
7943}
7944
7945// Montgomery reduction
7946function Montgomery(m) {
7947 this.m = m
7948 this.mp = m.invDigit()
7949 this.mpl = this.mp & 0x7fff
7950 this.mph = this.mp >> 15
7951 this.um = (1 << (m.DB - 15)) - 1
7952 this.mt2 = 2 * m.t
7953}
7954
7955// xR mod m
7956function montConvert(x) {
7957 var r = new BigInteger()
7958 x.abs()
7959 .dlShiftTo(this.m.t, r)
7960 r.divRemTo(this.m, null, r)
7961 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
7962 return r
7963}
7964
7965// x/R mod m
7966function montRevert(x) {
7967 var r = new BigInteger()
7968 x.copyTo(r)
7969 this.reduce(r)
7970 return r
7971}
7972
7973// x = x/R mod m (HAC 14.32)
7974function montReduce(x) {
7975 while (x.t <= this.mt2) // pad x so am has enough room later
7976 x[x.t++] = 0
7977 for (var i = 0; i < this.m.t; ++i) {
7978 // faster way of calculating u0 = x[i]*mp mod DV
7979 var j = x[i] & 0x7fff
7980 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
7981 // use am to combine the multiply-shift-add into one call
7982 j = i + this.m.t
7983 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
7984 // propagate carry
7985 while (x[j] >= x.DV) {
7986 x[j] -= x.DV
7987 x[++j]++
7988 }
7989 }
7990 x.clamp()
7991 x.drShiftTo(this.m.t, x)
7992 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
7993}
7994
7995// r = "x^2/R mod m"; x != r
7996function montSqrTo(x, r) {
7997 x.squareTo(r)
7998 this.reduce(r)
7999}
8000
8001// r = "xy/R mod m"; x,y != r
8002function montMulTo(x, y, r) {
8003 x.multiplyTo(y, r)
8004 this.reduce(r)
8005}
8006
8007Montgomery.prototype.convert = montConvert
8008Montgomery.prototype.revert = montRevert
8009Montgomery.prototype.reduce = montReduce
8010Montgomery.prototype.mulTo = montMulTo
8011Montgomery.prototype.sqrTo = montSqrTo
8012
8013// (protected) true iff this is even
8014function bnpIsEven() {
8015 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
8016}
8017
8018// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
8019function bnpExp(e, z) {
8020 if (e > 0xffffffff || e < 1) return BigInteger.ONE
8021 var r = new BigInteger(),
8022 r2 = new BigInteger(),
8023 g = z.convert(this),
8024 i = nbits(e) - 1
8025 g.copyTo(r)
8026 while (--i >= 0) {
8027 z.sqrTo(r, r2)
8028 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
8029 else {
8030 var t = r
8031 r = r2
8032 r2 = t
8033 }
8034 }
8035 return z.revert(r)
8036}
8037
8038// (public) this^e % m, 0 <= e < 2^32
8039function bnModPowInt(e, m) {
8040 var z
8041 if (e < 256 || m.isEven()) z = new Classic(m)
8042 else z = new Montgomery(m)
8043 return this.exp(e, z)
8044}
8045
8046// protected
8047proto.copyTo = bnpCopyTo
8048proto.fromInt = bnpFromInt
8049proto.fromString = bnpFromString
8050proto.clamp = bnpClamp
8051proto.dlShiftTo = bnpDLShiftTo
8052proto.drShiftTo = bnpDRShiftTo
8053proto.lShiftTo = bnpLShiftTo
8054proto.rShiftTo = bnpRShiftTo
8055proto.subTo = bnpSubTo
8056proto.multiplyTo = bnpMultiplyTo
8057proto.squareTo = bnpSquareTo
8058proto.divRemTo = bnpDivRemTo
8059proto.invDigit = bnpInvDigit
8060proto.isEven = bnpIsEven
8061proto.exp = bnpExp
8062
8063// public
8064proto.toString = bnToString
8065proto.negate = bnNegate
8066proto.abs = bnAbs
8067proto.compareTo = bnCompareTo
8068proto.bitLength = bnBitLength
8069proto.byteLength = bnByteLength
8070proto.mod = bnMod
8071proto.modPowInt = bnModPowInt
8072
8073// (public)
8074function bnClone() {
8075 var r = new BigInteger()
8076 this.copyTo(r)
8077 return r
8078}
8079
8080// (public) return value as integer
8081function bnIntValue() {
8082 if (this.s < 0) {
8083 if (this.t == 1) return this[0] - this.DV
8084 else if (this.t == 0) return -1
8085 } else if (this.t == 1) return this[0]
8086 else if (this.t == 0) return 0
8087 // assumes 16 < DB < 32
8088 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
8089}
8090
8091// (public) return value as byte
8092function bnByteValue() {
8093 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
8094}
8095
8096// (public) return value as short (assumes DB>=16)
8097function bnShortValue() {
8098 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
8099}
8100
8101// (protected) return x s.t. r^x < DV
8102function bnpChunkSize(r) {
8103 return Math.floor(Math.LN2 * this.DB / Math.log(r))
8104}
8105
8106// (public) 0 if this == 0, 1 if this > 0
8107function bnSigNum() {
8108 if (this.s < 0) return -1
8109 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
8110 else return 1
8111}
8112
8113// (protected) convert to radix string
8114function bnpToRadix(b) {
8115 if (b == null) b = 10
8116 if (this.signum() == 0 || b < 2 || b > 36) return "0"
8117 var cs = this.chunkSize(b)
8118 var a = Math.pow(b, cs)
8119 var d = nbv(a),
8120 y = new BigInteger(),
8121 z = new BigInteger(),
8122 r = ""
8123 this.divRemTo(d, y, z)
8124 while (y.signum() > 0) {
8125 r = (a + z.intValue())
8126 .toString(b)
8127 .substr(1) + r
8128 y.divRemTo(d, y, z)
8129 }
8130 return z.intValue()
8131 .toString(b) + r
8132}
8133
8134// (protected) convert from radix string
8135function bnpFromRadix(s, b) {
8136 var self = this
8137 self.fromInt(0)
8138 if (b == null) b = 10
8139 var cs = self.chunkSize(b)
8140 var d = Math.pow(b, cs),
8141 mi = false,
8142 j = 0,
8143 w = 0
8144 for (var i = 0; i < s.length; ++i) {
8145 var x = intAt(s, i)
8146 if (x < 0) {
8147 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
8148 continue
8149 }
8150 w = b * w + x
8151 if (++j >= cs) {
8152 self.dMultiply(d)
8153 self.dAddOffset(w, 0)
8154 j = 0
8155 w = 0
8156 }
8157 }
8158 if (j > 0) {
8159 self.dMultiply(Math.pow(b, j))
8160 self.dAddOffset(w, 0)
8161 }
8162 if (mi) BigInteger.ZERO.subTo(self, self)
8163}
8164
8165// (protected) alternate constructor
8166function bnpFromNumber(a, b, c) {
8167 var self = this
8168 if ("number" == typeof b) {
8169 // new BigInteger(int,int,RNG)
8170 if (a < 2) self.fromInt(1)
8171 else {
8172 self.fromNumber(a, c)
8173 if (!self.testBit(a - 1)) // force MSB set
8174 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
8175 if (self.isEven()) self.dAddOffset(1, 0); // force odd
8176 while (!self.isProbablePrime(b)) {
8177 self.dAddOffset(2, 0)
8178 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
8179 }
8180 }
8181 } else {
8182 // new BigInteger(int,RNG)
8183 var x = new Array(),
8184 t = a & 7
8185 x.length = (a >> 3) + 1
8186 b.nextBytes(x)
8187 if (t > 0) x[0] &= ((1 << t) - 1)
8188 else x[0] = 0
8189 self.fromString(x, 256)
8190 }
8191}
8192
8193// (public) convert to bigendian byte array
8194function bnToByteArray() {
8195 var self = this
8196 var i = self.t,
8197 r = new Array()
8198 r[0] = self.s
8199 var p = self.DB - (i * self.DB) % 8,
8200 d, k = 0
8201 if (i-- > 0) {
8202 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
8203 r[k++] = d | (self.s << (self.DB - p))
8204 while (i >= 0) {
8205 if (p < 8) {
8206 d = (self[i] & ((1 << p) - 1)) << (8 - p)
8207 d |= self[--i] >> (p += self.DB - 8)
8208 } else {
8209 d = (self[i] >> (p -= 8)) & 0xff
8210 if (p <= 0) {
8211 p += self.DB
8212 --i
8213 }
8214 }
8215 if ((d & 0x80) != 0) d |= -256
8216 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
8217 if (k > 0 || d != self.s) r[k++] = d
8218 }
8219 }
8220 return r
8221}
8222
8223function bnEquals(a) {
8224 return (this.compareTo(a) == 0)
8225}
8226
8227function bnMin(a) {
8228 return (this.compareTo(a) < 0) ? this : a
8229}
8230
8231function bnMax(a) {
8232 return (this.compareTo(a) > 0) ? this : a
8233}
8234
8235// (protected) r = this op a (bitwise)
8236function bnpBitwiseTo(a, op, r) {
8237 var self = this
8238 var i, f, m = Math.min(a.t, self.t)
8239 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
8240 if (a.t < self.t) {
8241 f = a.s & self.DM
8242 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
8243 r.t = self.t
8244 } else {
8245 f = self.s & self.DM
8246 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
8247 r.t = a.t
8248 }
8249 r.s = op(self.s, a.s)
8250 r.clamp()
8251}
8252
8253// (public) this & a
8254function op_and(x, y) {
8255 return x & y
8256}
8257
8258function bnAnd(a) {
8259 var r = new BigInteger()
8260 this.bitwiseTo(a, op_and, r)
8261 return r
8262}
8263
8264// (public) this | a
8265function op_or(x, y) {
8266 return x | y
8267}
8268
8269function bnOr(a) {
8270 var r = new BigInteger()
8271 this.bitwiseTo(a, op_or, r)
8272 return r
8273}
8274
8275// (public) this ^ a
8276function op_xor(x, y) {
8277 return x ^ y
8278}
8279
8280function bnXor(a) {
8281 var r = new BigInteger()
8282 this.bitwiseTo(a, op_xor, r)
8283 return r
8284}
8285
8286// (public) this & ~a
8287function op_andnot(x, y) {
8288 return x & ~y
8289}
8290
8291function bnAndNot(a) {
8292 var r = new BigInteger()
8293 this.bitwiseTo(a, op_andnot, r)
8294 return r
8295}
8296
8297// (public) ~this
8298function bnNot() {
8299 var r = new BigInteger()
8300 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
8301 r.t = this.t
8302 r.s = ~this.s
8303 return r
8304}
8305
8306// (public) this << n
8307function bnShiftLeft(n) {
8308 var r = new BigInteger()
8309 if (n < 0) this.rShiftTo(-n, r)
8310 else this.lShiftTo(n, r)
8311 return r
8312}
8313
8314// (public) this >> n
8315function bnShiftRight(n) {
8316 var r = new BigInteger()
8317 if (n < 0) this.lShiftTo(-n, r)
8318 else this.rShiftTo(n, r)
8319 return r
8320}
8321
8322// return index of lowest 1-bit in x, x < 2^31
8323function lbit(x) {
8324 if (x == 0) return -1
8325 var r = 0
8326 if ((x & 0xffff) == 0) {
8327 x >>= 16
8328 r += 16
8329 }
8330 if ((x & 0xff) == 0) {
8331 x >>= 8
8332 r += 8
8333 }
8334 if ((x & 0xf) == 0) {
8335 x >>= 4
8336 r += 4
8337 }
8338 if ((x & 3) == 0) {
8339 x >>= 2
8340 r += 2
8341 }
8342 if ((x & 1) == 0)++r
8343 return r
8344}
8345
8346// (public) returns index of lowest 1-bit (or -1 if none)
8347function bnGetLowestSetBit() {
8348 for (var i = 0; i < this.t; ++i)
8349 if (this[i] != 0) return i * this.DB + lbit(this[i])
8350 if (this.s < 0) return this.t * this.DB
8351 return -1
8352}
8353
8354// return number of 1 bits in x
8355function cbit(x) {
8356 var r = 0
8357 while (x != 0) {
8358 x &= x - 1
8359 ++r
8360 }
8361 return r
8362}
8363
8364// (public) return number of set bits
8365function bnBitCount() {
8366 var r = 0,
8367 x = this.s & this.DM
8368 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
8369 return r
8370}
8371
8372// (public) true iff nth bit is set
8373function bnTestBit(n) {
8374 var j = Math.floor(n / this.DB)
8375 if (j >= this.t) return (this.s != 0)
8376 return ((this[j] & (1 << (n % this.DB))) != 0)
8377}
8378
8379// (protected) this op (1<<n)
8380function bnpChangeBit(n, op) {
8381 var r = BigInteger.ONE.shiftLeft(n)
8382 this.bitwiseTo(r, op, r)
8383 return r
8384}
8385
8386// (public) this | (1<<n)
8387function bnSetBit(n) {
8388 return this.changeBit(n, op_or)
8389}
8390
8391// (public) this & ~(1<<n)
8392function bnClearBit(n) {
8393 return this.changeBit(n, op_andnot)
8394}
8395
8396// (public) this ^ (1<<n)
8397function bnFlipBit(n) {
8398 return this.changeBit(n, op_xor)
8399}
8400
8401// (protected) r = this + a
8402function bnpAddTo(a, r) {
8403 var self = this
8404
8405 var i = 0,
8406 c = 0,
8407 m = Math.min(a.t, self.t)
8408 while (i < m) {
8409 c += self[i] + a[i]
8410 r[i++] = c & self.DM
8411 c >>= self.DB
8412 }
8413 if (a.t < self.t) {
8414 c += a.s
8415 while (i < self.t) {
8416 c += self[i]
8417 r[i++] = c & self.DM
8418 c >>= self.DB
8419 }
8420 c += self.s
8421 } else {
8422 c += self.s
8423 while (i < a.t) {
8424 c += a[i]
8425 r[i++] = c & self.DM
8426 c >>= self.DB
8427 }
8428 c += a.s
8429 }
8430 r.s = (c < 0) ? -1 : 0
8431 if (c > 0) r[i++] = c
8432 else if (c < -1) r[i++] = self.DV + c
8433 r.t = i
8434 r.clamp()
8435}
8436
8437// (public) this + a
8438function bnAdd(a) {
8439 var r = new BigInteger()
8440 this.addTo(a, r)
8441 return r
8442}
8443
8444// (public) this - a
8445function bnSubtract(a) {
8446 var r = new BigInteger()
8447 this.subTo(a, r)
8448 return r
8449}
8450
8451// (public) this * a
8452function bnMultiply(a) {
8453 var r = new BigInteger()
8454 this.multiplyTo(a, r)
8455 return r
8456}
8457
8458// (public) this^2
8459function bnSquare() {
8460 var r = new BigInteger()
8461 this.squareTo(r)
8462 return r
8463}
8464
8465// (public) this / a
8466function bnDivide(a) {
8467 var r = new BigInteger()
8468 this.divRemTo(a, r, null)
8469 return r
8470}
8471
8472// (public) this % a
8473function bnRemainder(a) {
8474 var r = new BigInteger()
8475 this.divRemTo(a, null, r)
8476 return r
8477}
8478
8479// (public) [this/a,this%a]
8480function bnDivideAndRemainder(a) {
8481 var q = new BigInteger(),
8482 r = new BigInteger()
8483 this.divRemTo(a, q, r)
8484 return new Array(q, r)
8485}
8486
8487// (protected) this *= n, this >= 0, 1 < n < DV
8488function bnpDMultiply(n) {
8489 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
8490 ++this.t
8491 this.clamp()
8492}
8493
8494// (protected) this += n << w words, this >= 0
8495function bnpDAddOffset(n, w) {
8496 if (n == 0) return
8497 while (this.t <= w) this[this.t++] = 0
8498 this[w] += n
8499 while (this[w] >= this.DV) {
8500 this[w] -= this.DV
8501 if (++w >= this.t) this[this.t++] = 0
8502 ++this[w]
8503 }
8504}
8505
8506// A "null" reducer
8507function NullExp() {}
8508
8509function nNop(x) {
8510 return x
8511}
8512
8513function nMulTo(x, y, r) {
8514 x.multiplyTo(y, r)
8515}
8516
8517function nSqrTo(x, r) {
8518 x.squareTo(r)
8519}
8520
8521NullExp.prototype.convert = nNop
8522NullExp.prototype.revert = nNop
8523NullExp.prototype.mulTo = nMulTo
8524NullExp.prototype.sqrTo = nSqrTo
8525
8526// (public) this^e
8527function bnPow(e) {
8528 return this.exp(e, new NullExp())
8529}
8530
8531// (protected) r = lower n words of "this * a", a.t <= n
8532// "this" should be the larger one if appropriate.
8533function bnpMultiplyLowerTo(a, n, r) {
8534 var i = Math.min(this.t + a.t, n)
8535 r.s = 0; // assumes a,this >= 0
8536 r.t = i
8537 while (i > 0) r[--i] = 0
8538 var j
8539 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
8540 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
8541 r.clamp()
8542}
8543
8544// (protected) r = "this * a" without lower n words, n > 0
8545// "this" should be the larger one if appropriate.
8546function bnpMultiplyUpperTo(a, n, r) {
8547 --n
8548 var i = r.t = this.t + a.t - n
8549 r.s = 0; // assumes a,this >= 0
8550 while (--i >= 0) r[i] = 0
8551 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
8552 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
8553 r.clamp()
8554 r.drShiftTo(1, r)
8555}
8556
8557// Barrett modular reduction
8558function Barrett(m) {
8559 // setup Barrett
8560 this.r2 = new BigInteger()
8561 this.q3 = new BigInteger()
8562 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
8563 this.mu = this.r2.divide(m)
8564 this.m = m
8565}
8566
8567function barrettConvert(x) {
8568 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
8569 else if (x.compareTo(this.m) < 0) return x
8570 else {
8571 var r = new BigInteger()
8572 x.copyTo(r)
8573 this.reduce(r)
8574 return r
8575 }
8576}
8577
8578function barrettRevert(x) {
8579 return x
8580}
8581
8582// x = x mod m (HAC 14.42)
8583function barrettReduce(x) {
8584 var self = this
8585 x.drShiftTo(self.m.t - 1, self.r2)
8586 if (x.t > self.m.t + 1) {
8587 x.t = self.m.t + 1
8588 x.clamp()
8589 }
8590 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
8591 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
8592 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
8593 x.subTo(self.r2, x)
8594 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
8595}
8596
8597// r = x^2 mod m; x != r
8598function barrettSqrTo(x, r) {
8599 x.squareTo(r)
8600 this.reduce(r)
8601}
8602
8603// r = x*y mod m; x,y != r
8604function barrettMulTo(x, y, r) {
8605 x.multiplyTo(y, r)
8606 this.reduce(r)
8607}
8608
8609Barrett.prototype.convert = barrettConvert
8610Barrett.prototype.revert = barrettRevert
8611Barrett.prototype.reduce = barrettReduce
8612Barrett.prototype.mulTo = barrettMulTo
8613Barrett.prototype.sqrTo = barrettSqrTo
8614
8615// (public) this^e % m (HAC 14.85)
8616function bnModPow(e, m) {
8617 var i = e.bitLength(),
8618 k, r = nbv(1),
8619 z
8620 if (i <= 0) return r
8621 else if (i < 18) k = 1
8622 else if (i < 48) k = 3
8623 else if (i < 144) k = 4
8624 else if (i < 768) k = 5
8625 else k = 6
8626 if (i < 8)
8627 z = new Classic(m)
8628 else if (m.isEven())
8629 z = new Barrett(m)
8630 else
8631 z = new Montgomery(m)
8632
8633 // precomputation
8634 var g = new Array(),
8635 n = 3,
8636 k1 = k - 1,
8637 km = (1 << k) - 1
8638 g[1] = z.convert(this)
8639 if (k > 1) {
8640 var g2 = new BigInteger()
8641 z.sqrTo(g[1], g2)
8642 while (n <= km) {
8643 g[n] = new BigInteger()
8644 z.mulTo(g2, g[n - 2], g[n])
8645 n += 2
8646 }
8647 }
8648
8649 var j = e.t - 1,
8650 w, is1 = true,
8651 r2 = new BigInteger(),
8652 t
8653 i = nbits(e[j]) - 1
8654 while (j >= 0) {
8655 if (i >= k1) w = (e[j] >> (i - k1)) & km
8656 else {
8657 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
8658 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
8659 }
8660
8661 n = k
8662 while ((w & 1) == 0) {
8663 w >>= 1
8664 --n
8665 }
8666 if ((i -= n) < 0) {
8667 i += this.DB
8668 --j
8669 }
8670 if (is1) { // ret == 1, don't bother squaring or multiplying it
8671 g[w].copyTo(r)
8672 is1 = false
8673 } else {
8674 while (n > 1) {
8675 z.sqrTo(r, r2)
8676 z.sqrTo(r2, r)
8677 n -= 2
8678 }
8679 if (n > 0) z.sqrTo(r, r2)
8680 else {
8681 t = r
8682 r = r2
8683 r2 = t
8684 }
8685 z.mulTo(r2, g[w], r)
8686 }
8687
8688 while (j >= 0 && (e[j] & (1 << i)) == 0) {
8689 z.sqrTo(r, r2)
8690 t = r
8691 r = r2
8692 r2 = t
8693 if (--i < 0) {
8694 i = this.DB - 1
8695 --j
8696 }
8697 }
8698 }
8699 return z.revert(r)
8700}
8701
8702// (public) gcd(this,a) (HAC 14.54)
8703function bnGCD(a) {
8704 var x = (this.s < 0) ? this.negate() : this.clone()
8705 var y = (a.s < 0) ? a.negate() : a.clone()
8706 if (x.compareTo(y) < 0) {
8707 var t = x
8708 x = y
8709 y = t
8710 }
8711 var i = x.getLowestSetBit(),
8712 g = y.getLowestSetBit()
8713 if (g < 0) return x
8714 if (i < g) g = i
8715 if (g > 0) {
8716 x.rShiftTo(g, x)
8717 y.rShiftTo(g, y)
8718 }
8719 while (x.signum() > 0) {
8720 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
8721 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
8722 if (x.compareTo(y) >= 0) {
8723 x.subTo(y, x)
8724 x.rShiftTo(1, x)
8725 } else {
8726 y.subTo(x, y)
8727 y.rShiftTo(1, y)
8728 }
8729 }
8730 if (g > 0) y.lShiftTo(g, y)
8731 return y
8732}
8733
8734// (protected) this % n, n < 2^26
8735function bnpModInt(n) {
8736 if (n <= 0) return 0
8737 var d = this.DV % n,
8738 r = (this.s < 0) ? n - 1 : 0
8739 if (this.t > 0)
8740 if (d == 0) r = this[0] % n
8741 else
8742 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
8743 return r
8744}
8745
8746// (public) 1/this % m (HAC 14.61)
8747function bnModInverse(m) {
8748 var ac = m.isEven()
8749 if (this.signum() === 0) throw new Error('division by zero')
8750 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
8751 var u = m.clone(),
8752 v = this.clone()
8753 var a = nbv(1),
8754 b = nbv(0),
8755 c = nbv(0),
8756 d = nbv(1)
8757 while (u.signum() != 0) {
8758 while (u.isEven()) {
8759 u.rShiftTo(1, u)
8760 if (ac) {
8761 if (!a.isEven() || !b.isEven()) {
8762 a.addTo(this, a)
8763 b.subTo(m, b)
8764 }
8765 a.rShiftTo(1, a)
8766 } else if (!b.isEven()) b.subTo(m, b)
8767 b.rShiftTo(1, b)
8768 }
8769 while (v.isEven()) {
8770 v.rShiftTo(1, v)
8771 if (ac) {
8772 if (!c.isEven() || !d.isEven()) {
8773 c.addTo(this, c)
8774 d.subTo(m, d)
8775 }
8776 c.rShiftTo(1, c)
8777 } else if (!d.isEven()) d.subTo(m, d)
8778 d.rShiftTo(1, d)
8779 }
8780 if (u.compareTo(v) >= 0) {
8781 u.subTo(v, u)
8782 if (ac) a.subTo(c, a)
8783 b.subTo(d, b)
8784 } else {
8785 v.subTo(u, v)
8786 if (ac) c.subTo(a, c)
8787 d.subTo(b, d)
8788 }
8789 }
8790 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
8791 while (d.compareTo(m) >= 0) d.subTo(m, d)
8792 while (d.signum() < 0) d.addTo(m, d)
8793 return d
8794}
8795
8796var lowprimes = [
8797 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
8798 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
8799 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
8800 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
8801 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
8802 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
8803 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
8804 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
8805 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
8806 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
8807 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
8808]
8809
8810var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
8811
8812// (public) test primality with certainty >= 1-.5^t
8813function bnIsProbablePrime(t) {
8814 var i, x = this.abs()
8815 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
8816 for (i = 0; i < lowprimes.length; ++i)
8817 if (x[0] == lowprimes[i]) return true
8818 return false
8819 }
8820 if (x.isEven()) return false
8821 i = 1
8822 while (i < lowprimes.length) {
8823 var m = lowprimes[i],
8824 j = i + 1
8825 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
8826 m = x.modInt(m)
8827 while (i < j) if (m % lowprimes[i++] == 0) return false
8828 }
8829 return x.millerRabin(t)
8830}
8831
8832// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
8833function bnpMillerRabin(t) {
8834 var n1 = this.subtract(BigInteger.ONE)
8835 var k = n1.getLowestSetBit()
8836 if (k <= 0) return false
8837 var r = n1.shiftRight(k)
8838 t = (t + 1) >> 1
8839 if (t > lowprimes.length) t = lowprimes.length
8840 var a = new BigInteger(null)
8841 var j, bases = []
8842 for (var i = 0; i < t; ++i) {
8843 for (;;) {
8844 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
8845 if (bases.indexOf(j) == -1) break
8846 }
8847 bases.push(j)
8848 a.fromInt(j)
8849 var y = a.modPow(r, this)
8850 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
8851 var j = 1
8852 while (j++ < k && y.compareTo(n1) != 0) {
8853 y = y.modPowInt(2, this)
8854 if (y.compareTo(BigInteger.ONE) == 0) return false
8855 }
8856 if (y.compareTo(n1) != 0) return false
8857 }
8858 }
8859 return true
8860}
8861
8862// protected
8863proto.chunkSize = bnpChunkSize
8864proto.toRadix = bnpToRadix
8865proto.fromRadix = bnpFromRadix
8866proto.fromNumber = bnpFromNumber
8867proto.bitwiseTo = bnpBitwiseTo
8868proto.changeBit = bnpChangeBit
8869proto.addTo = bnpAddTo
8870proto.dMultiply = bnpDMultiply
8871proto.dAddOffset = bnpDAddOffset
8872proto.multiplyLowerTo = bnpMultiplyLowerTo
8873proto.multiplyUpperTo = bnpMultiplyUpperTo
8874proto.modInt = bnpModInt
8875proto.millerRabin = bnpMillerRabin
8876
8877// public
8878proto.clone = bnClone
8879proto.intValue = bnIntValue
8880proto.byteValue = bnByteValue
8881proto.shortValue = bnShortValue
8882proto.signum = bnSigNum
8883proto.toByteArray = bnToByteArray
8884proto.equals = bnEquals
8885proto.min = bnMin
8886proto.max = bnMax
8887proto.and = bnAnd
8888proto.or = bnOr
8889proto.xor = bnXor
8890proto.andNot = bnAndNot
8891proto.not = bnNot
8892proto.shiftLeft = bnShiftLeft
8893proto.shiftRight = bnShiftRight
8894proto.getLowestSetBit = bnGetLowestSetBit
8895proto.bitCount = bnBitCount
8896proto.testBit = bnTestBit
8897proto.setBit = bnSetBit
8898proto.clearBit = bnClearBit
8899proto.flipBit = bnFlipBit
8900proto.add = bnAdd
8901proto.subtract = bnSubtract
8902proto.multiply = bnMultiply
8903proto.divide = bnDivide
8904proto.remainder = bnRemainder
8905proto.divideAndRemainder = bnDivideAndRemainder
8906proto.modPow = bnModPow
8907proto.modInverse = bnModInverse
8908proto.pow = bnPow
8909proto.gcd = bnGCD
8910proto.isProbablePrime = bnIsProbablePrime
8911
8912// JSBN-specific extension
8913proto.square = bnSquare
8914
8915// constants
8916BigInteger.ZERO = nbv(0)
8917BigInteger.ONE = nbv(1)
8918BigInteger.valueOf = nbv
8919
8920module.exports = BigInteger
8921
8922},{"../package.json":30}],28:[function(require,module,exports){
8923(function (Buffer){(function (){
8924// FIXME: Kind of a weird way to throw exceptions, consider removing
8925var assert = require('assert')
8926var BigInteger = require('./bigi')
8927
8928/**
8929 * Turns a byte array into a big integer.
8930 *
8931 * This function will interpret a byte array as a big integer in big
8932 * endian notation.
8933 */
8934BigInteger.fromByteArrayUnsigned = function(byteArray) {
8935 // BigInteger expects a DER integer conformant byte array
8936 if (byteArray[0] & 0x80) {
8937 return new BigInteger([0].concat(byteArray))
8938 }
8939
8940 return new BigInteger(byteArray)
8941}
8942
8943/**
8944 * Returns a byte array representation of the big integer.
8945 *
8946 * This returns the absolute of the contained value in big endian
8947 * form. A value of zero results in an empty array.
8948 */
8949BigInteger.prototype.toByteArrayUnsigned = function() {
8950 var byteArray = this.toByteArray()
8951 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
8952}
8953
8954BigInteger.fromDERInteger = function(byteArray) {
8955 return new BigInteger(byteArray)
8956}
8957
8958/*
8959 * Converts BigInteger to a DER integer representation.
8960 *
8961 * The format for this value uses the most significant bit as a sign
8962 * bit. If the most significant bit is already set and the integer is
8963 * positive, a 0x00 is prepended.
8964 *
8965 * Examples:
8966 *
8967 * 0 => 0x00
8968 * 1 => 0x01
8969 * -1 => 0xff
8970 * 127 => 0x7f
8971 * -127 => 0x81
8972 * 128 => 0x0080
8973 * -128 => 0x80
8974 * 255 => 0x00ff
8975 * -255 => 0xff01
8976 * 16300 => 0x3fac
8977 * -16300 => 0xc054
8978 * 62300 => 0x00f35c
8979 * -62300 => 0xff0ca4
8980*/
8981BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
8982
8983BigInteger.fromBuffer = function(buffer) {
8984 // BigInteger expects a DER integer conformant byte array
8985 if (buffer[0] & 0x80) {
8986 var byteArray = Array.prototype.slice.call(buffer)
8987
8988 return new BigInteger([0].concat(byteArray))
8989 }
8990
8991 return new BigInteger(buffer)
8992}
8993
8994BigInteger.fromHex = function(hex) {
8995 if (hex === '') return BigInteger.ZERO
8996
8997 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
8998 assert.equal(hex.length % 2, 0, 'Incomplete hex')
8999 return new BigInteger(hex, 16)
9000}
9001
9002BigInteger.prototype.toBuffer = function(size) {
9003 var byteArray = this.toByteArrayUnsigned()
9004 var zeros = []
9005
9006 var padding = size - byteArray.length
9007 while (zeros.length < padding) zeros.push(0)
9008
9009 return new Buffer(zeros.concat(byteArray))
9010}
9011
9012BigInteger.prototype.toHex = function(size) {
9013 return this.toBuffer(size).toString('hex')
9014}
9015
9016}).call(this)}).call(this,require("buffer").Buffer)
9017},{"./bigi":27,"assert":22,"buffer":77}],29:[function(require,module,exports){
9018var BigInteger = require('./bigi')
9019
9020//addons
9021require('./convert')
9022
9023module.exports = BigInteger
9024},{"./bigi":27,"./convert":28}],30:[function(require,module,exports){
9025module.exports={
9026 "_args": [
9027 [
9028 "bigi@1.4.2",
9029 "/home/user/git/blindsecp256k1-js"
9030 ]
9031 ],
9032 "_from": "bigi@1.4.2",
9033 "_id": "bigi@1.4.2",
9034 "_inBundle": false,
9035 "_integrity": "sha1-nGZalfiLiwj8Bc/XMfVhhZ1yWCU=",
9036 "_location": "/bigi",
9037 "_phantomChildren": {},
9038 "_requested": {
9039 "type": "version",
9040 "registry": true,
9041 "raw": "bigi@1.4.2",
9042 "name": "bigi",
9043 "escapedName": "bigi",
9044 "rawSpec": "1.4.2",
9045 "saveSpec": null,
9046 "fetchSpec": "1.4.2"
9047 },
9048 "_requiredBy": [
9049 "/",
9050 "/ecurve"
9051 ],
9052 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
9053 "_spec": "1.4.2",
9054 "_where": "/home/user/git/blindsecp256k1-js",
9055 "bugs": {
9056 "url": "https://github.com/cryptocoinjs/bigi/issues"
9057 },
9058 "dependencies": {},
9059 "description": "Big integers.",
9060 "devDependencies": {
9061 "coveralls": "^2.11.2",
9062 "istanbul": "^0.3.5",
9063 "jshint": "^2.5.1",
9064 "mocha": "^2.1.0",
9065 "mochify": "^2.1.0"
9066 },
9067 "homepage": "https://github.com/cryptocoinjs/bigi#readme",
9068 "keywords": [
9069 "cryptography",
9070 "math",
9071 "bitcoin",
9072 "arbitrary",
9073 "precision",
9074 "arithmetic",
9075 "big",
9076 "integer",
9077 "int",
9078 "number",
9079 "biginteger",
9080 "bigint",
9081 "bignumber",
9082 "decimal",
9083 "float"
9084 ],
9085 "main": "./lib/index.js",
9086 "name": "bigi",
9087 "repository": {
9088 "url": "git+https://github.com/cryptocoinjs/bigi.git",
9089 "type": "git"
9090 },
9091 "scripts": {
9092 "browser-test": "mochify --wd -R spec",
9093 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
9094 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info",
9095 "jshint": "jshint --config jshint.json lib/*.js ; true",
9096 "test": "_mocha -- test/*.js",
9097 "unit": "mocha"
9098 },
9099 "testling": {
9100 "files": "test/*.js",
9101 "harness": "mocha",
9102 "browsers": [
9103 "ie/9..latest",
9104 "firefox/latest",
9105 "chrome/latest",
9106 "safari/6.0..latest",
9107 "iphone/6.0..latest",
9108 "android-browser/4.2..latest"
9109 ]
9110 },
9111 "version": "1.4.2"
9112}
9113
9114},{}],31:[function(require,module,exports){
9115(function (module, exports) {
9116 'use strict';
9117
9118 // Utils
9119 function assert (val, msg) {
9120 if (!val) throw new Error(msg || 'Assertion failed');
9121 }
9122
9123 // Could use `inherits` module, but don't want to move from single file
9124 // architecture yet.
9125 function inherits (ctor, superCtor) {
9126 ctor.super_ = superCtor;
9127 var TempCtor = function () {};
9128 TempCtor.prototype = superCtor.prototype;
9129 ctor.prototype = new TempCtor();
9130 ctor.prototype.constructor = ctor;
9131 }
9132
9133 // BN
9134
9135 function BN (number, base, endian) {
9136 if (BN.isBN(number)) {
9137 return number;
9138 }
9139
9140 this.negative = 0;
9141 this.words = null;
9142 this.length = 0;
9143
9144 // Reduction context
9145 this.red = null;
9146
9147 if (number !== null) {
9148 if (base === 'le' || base === 'be') {
9149 endian = base;
9150 base = 10;
9151 }
9152
9153 this._init(number || 0, base || 10, endian || 'be');
9154 }
9155 }
9156 if (typeof module === 'object') {
9157 module.exports = BN;
9158 } else {
9159 exports.BN = BN;
9160 }
9161
9162 BN.BN = BN;
9163 BN.wordSize = 26;
9164
9165 var Buffer;
9166 try {
9167 Buffer = require('buffer').Buffer;
9168 } catch (e) {
9169 }
9170
9171 BN.isBN = function isBN (num) {
9172 if (num instanceof BN) {
9173 return true;
9174 }
9175
9176 return num !== null && typeof num === 'object' &&
9177 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
9178 };
9179
9180 BN.max = function max (left, right) {
9181 if (left.cmp(right) > 0) return left;
9182 return right;
9183 };
9184
9185 BN.min = function min (left, right) {
9186 if (left.cmp(right) < 0) return left;
9187 return right;
9188 };
9189
9190 BN.prototype._init = function init (number, base, endian) {
9191 if (typeof number === 'number') {
9192 return this._initNumber(number, base, endian);
9193 }
9194
9195 if (typeof number === 'object') {
9196 return this._initArray(number, base, endian);
9197 }
9198
9199 if (base === 'hex') {
9200 base = 16;
9201 }
9202 assert(base === (base | 0) && base >= 2 && base <= 36);
9203
9204 number = number.toString().replace(/\s+/g, '');
9205 var start = 0;
9206 if (number[0] === '-') {
9207 start++;
9208 }
9209
9210 if (base === 16) {
9211 this._parseHex(number, start);
9212 } else {
9213 this._parseBase(number, base, start);
9214 }
9215
9216 if (number[0] === '-') {
9217 this.negative = 1;
9218 }
9219
9220 this._strip();
9221
9222 if (endian !== 'le') return;
9223
9224 this._initArray(this.toArray(), base, endian);
9225 };
9226
9227 BN.prototype._initNumber = function _initNumber (number, base, endian) {
9228 if (number < 0) {
9229 this.negative = 1;
9230 number = -number;
9231 }
9232 if (number < 0x4000000) {
9233 this.words = [number & 0x3ffffff];
9234 this.length = 1;
9235 } else if (number < 0x10000000000000) {
9236 this.words = [
9237 number & 0x3ffffff,
9238 (number / 0x4000000) & 0x3ffffff
9239 ];
9240 this.length = 2;
9241 } else {
9242 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
9243 this.words = [
9244 number & 0x3ffffff,
9245 (number / 0x4000000) & 0x3ffffff,
9246 1
9247 ];
9248 this.length = 3;
9249 }
9250
9251 if (endian !== 'le') return;
9252
9253 // Reverse the bytes
9254 this._initArray(this.toArray(), base, endian);
9255 };
9256
9257 BN.prototype._initArray = function _initArray (number, base, endian) {
9258 // Perhaps a Uint8Array
9259 assert(typeof number.length === 'number');
9260 if (number.length <= 0) {
9261 this.words = [0];
9262 this.length = 1;
9263 return this;
9264 }
9265
9266 this.length = Math.ceil(number.length / 3);
9267 this.words = new Array(this.length);
9268 for (var i = 0; i < this.length; i++) {
9269 this.words[i] = 0;
9270 }
9271
9272 var j, w;
9273 var off = 0;
9274 if (endian === 'be') {
9275 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
9276 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
9277 this.words[j] |= (w << off) & 0x3ffffff;
9278 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
9279 off += 24;
9280 if (off >= 26) {
9281 off -= 26;
9282 j++;
9283 }
9284 }
9285 } else if (endian === 'le') {
9286 for (i = 0, j = 0; i < number.length; i += 3) {
9287 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
9288 this.words[j] |= (w << off) & 0x3ffffff;
9289 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
9290 off += 24;
9291 if (off >= 26) {
9292 off -= 26;
9293 j++;
9294 }
9295 }
9296 }
9297 return this._strip();
9298 };
9299
9300 function parseHex (str, start, end) {
9301 var r = 0;
9302 var len = Math.min(str.length, end);
9303 var z = 0;
9304 for (var i = start; i < len; i++) {
9305 var c = str.charCodeAt(i) - 48;
9306
9307 r <<= 4;
9308
9309 var b;
9310
9311 // 'a' - 'f'
9312 if (c >= 49 && c <= 54) {
9313 b = c - 49 + 0xa;
9314
9315 // 'A' - 'F'
9316 } else if (c >= 17 && c <= 22) {
9317 b = c - 17 + 0xa;
9318
9319 // '0' - '9'
9320 } else {
9321 b = c;
9322 }
9323
9324 r |= b;
9325 z |= b;
9326 }
9327
9328 assert(!(z & 0xf0), 'Invalid character in ' + str);
9329 return r;
9330 }
9331
9332 BN.prototype._parseHex = function _parseHex (number, start) {
9333 // Create possibly bigger array to ensure that it fits the number
9334 this.length = Math.ceil((number.length - start) / 6);
9335 this.words = new Array(this.length);
9336 for (var i = 0; i < this.length; i++) {
9337 this.words[i] = 0;
9338 }
9339
9340 var j, w;
9341 // Scan 24-bit chunks and add them to the number
9342 var off = 0;
9343 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
9344 w = parseHex(number, i, i + 6);
9345 this.words[j] |= (w << off) & 0x3ffffff;
9346 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
9347 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
9348 off += 24;
9349 if (off >= 26) {
9350 off -= 26;
9351 j++;
9352 }
9353 }
9354 if (i + 6 !== start) {
9355 w = parseHex(number, start, i + 6);
9356 this.words[j] |= (w << off) & 0x3ffffff;
9357 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
9358 }
9359 this._strip();
9360 };
9361
9362 function parseBase (str, start, end, mul) {
9363 var r = 0;
9364 var b = 0;
9365 var len = Math.min(str.length, end);
9366 for (var i = start; i < len; i++) {
9367 var c = str.charCodeAt(i) - 48;
9368
9369 r *= mul;
9370
9371 // 'a'
9372 if (c >= 49) {
9373 b = c - 49 + 0xa;
9374
9375 // 'A'
9376 } else if (c >= 17) {
9377 b = c - 17 + 0xa;
9378
9379 // '0' - '9'
9380 } else {
9381 b = c;
9382 }
9383 assert(c >= 0 && b < mul, 'Invalid character');
9384 r += b;
9385 }
9386 return r;
9387 }
9388
9389 BN.prototype._parseBase = function _parseBase (number, base, start) {
9390 // Initialize as zero
9391 this.words = [0];
9392 this.length = 1;
9393
9394 // Find length of limb in base
9395 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
9396 limbLen++;
9397 }
9398 limbLen--;
9399 limbPow = (limbPow / base) | 0;
9400
9401 var total = number.length - start;
9402 var mod = total % limbLen;
9403 var end = Math.min(total, total - mod) + start;
9404
9405 var word = 0;
9406 for (var i = start; i < end; i += limbLen) {
9407 word = parseBase(number, i, i + limbLen, base);
9408
9409 this.imuln(limbPow);
9410 if (this.words[0] + word < 0x4000000) {
9411 this.words[0] += word;
9412 } else {
9413 this._iaddn(word);
9414 }
9415 }
9416
9417 if (mod !== 0) {
9418 var pow = 1;
9419 word = parseBase(number, i, number.length, base);
9420
9421 for (i = 0; i < mod; i++) {
9422 pow *= base;
9423 }
9424
9425 this.imuln(pow);
9426 if (this.words[0] + word < 0x4000000) {
9427 this.words[0] += word;
9428 } else {
9429 this._iaddn(word);
9430 }
9431 }
9432 };
9433
9434 BN.prototype.copy = function copy (dest) {
9435 dest.words = new Array(this.length);
9436 for (var i = 0; i < this.length; i++) {
9437 dest.words[i] = this.words[i];
9438 }
9439 dest.length = this.length;
9440 dest.negative = this.negative;
9441 dest.red = this.red;
9442 };
9443
9444 function move (dest, src) {
9445 dest.words = src.words;
9446 dest.length = src.length;
9447 dest.negative = src.negative;
9448 dest.red = src.red;
9449 }
9450
9451 BN.prototype._move = function _move (dest) {
9452 move(dest, this);
9453 };
9454
9455 BN.prototype.clone = function clone () {
9456 var r = new BN(null);
9457 this.copy(r);
9458 return r;
9459 };
9460
9461 BN.prototype._expand = function _expand (size) {
9462 while (this.length < size) {
9463 this.words[this.length++] = 0;
9464 }
9465 return this;
9466 };
9467
9468 // Remove leading `0` from `this`
9469 BN.prototype._strip = function strip () {
9470 while (this.length > 1 && this.words[this.length - 1] === 0) {
9471 this.length--;
9472 }
9473 return this._normSign();
9474 };
9475
9476 BN.prototype._normSign = function _normSign () {
9477 // -0 = 0
9478 if (this.length === 1 && this.words[0] === 0) {
9479 this.negative = 0;
9480 }
9481 return this;
9482 };
9483
9484 // Check Symbol.for because not everywhere where Symbol defined
9485 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
9486 if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
9487 try {
9488 BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
9489 } catch (e) {
9490 BN.prototype.inspect = inspect;
9491 }
9492 } else {
9493 BN.prototype.inspect = inspect;
9494 }
9495
9496 function inspect () {
9497 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
9498 }
9499
9500 /*
9501
9502 var zeros = [];
9503 var groupSizes = [];
9504 var groupBases = [];
9505
9506 var s = '';
9507 var i = -1;
9508 while (++i < BN.wordSize) {
9509 zeros[i] = s;
9510 s += '0';
9511 }
9512 groupSizes[0] = 0;
9513 groupSizes[1] = 0;
9514 groupBases[0] = 0;
9515 groupBases[1] = 0;
9516 var base = 2 - 1;
9517 while (++base < 36 + 1) {
9518 var groupSize = 0;
9519 var groupBase = 1;
9520 while (groupBase < (1 << BN.wordSize) / base) {
9521 groupBase *= base;
9522 groupSize += 1;
9523 }
9524 groupSizes[base] = groupSize;
9525 groupBases[base] = groupBase;
9526 }
9527
9528 */
9529
9530 var zeros = [
9531 '',
9532 '0',
9533 '00',
9534 '000',
9535 '0000',
9536 '00000',
9537 '000000',
9538 '0000000',
9539 '00000000',
9540 '000000000',
9541 '0000000000',
9542 '00000000000',
9543 '000000000000',
9544 '0000000000000',
9545 '00000000000000',
9546 '000000000000000',
9547 '0000000000000000',
9548 '00000000000000000',
9549 '000000000000000000',
9550 '0000000000000000000',
9551 '00000000000000000000',
9552 '000000000000000000000',
9553 '0000000000000000000000',
9554 '00000000000000000000000',
9555 '000000000000000000000000',
9556 '0000000000000000000000000'
9557 ];
9558
9559 var groupSizes = [
9560 0, 0,
9561 25, 16, 12, 11, 10, 9, 8,
9562 8, 7, 7, 7, 7, 6, 6,
9563 6, 6, 6, 6, 6, 5, 5,
9564 5, 5, 5, 5, 5, 5, 5,
9565 5, 5, 5, 5, 5, 5, 5
9566 ];
9567
9568 var groupBases = [
9569 0, 0,
9570 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
9571 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
9572 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
9573 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
9574 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
9575 ];
9576
9577 BN.prototype.toString = function toString (base, padding) {
9578 base = base || 10;
9579 padding = padding | 0 || 1;
9580
9581 var out;
9582 if (base === 16 || base === 'hex') {
9583 out = '';
9584 var off = 0;
9585 var carry = 0;
9586 for (var i = 0; i < this.length; i++) {
9587 var w = this.words[i];
9588 var word = (((w << off) | carry) & 0xffffff).toString(16);
9589 carry = (w >>> (24 - off)) & 0xffffff;
9590 if (carry !== 0 || i !== this.length - 1) {
9591 out = zeros[6 - word.length] + word + out;
9592 } else {
9593 out = word + out;
9594 }
9595 off += 2;
9596 if (off >= 26) {
9597 off -= 26;
9598 i--;
9599 }
9600 }
9601 if (carry !== 0) {
9602 out = carry.toString(16) + out;
9603 }
9604 while (out.length % padding !== 0) {
9605 out = '0' + out;
9606 }
9607 if (this.negative !== 0) {
9608 out = '-' + out;
9609 }
9610 return out;
9611 }
9612
9613 if (base === (base | 0) && base >= 2 && base <= 36) {
9614 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
9615 var groupSize = groupSizes[base];
9616 // var groupBase = Math.pow(base, groupSize);
9617 var groupBase = groupBases[base];
9618 out = '';
9619 var c = this.clone();
9620 c.negative = 0;
9621 while (!c.isZero()) {
9622 var r = c.modrn(groupBase).toString(base);
9623 c = c.idivn(groupBase);
9624
9625 if (!c.isZero()) {
9626 out = zeros[groupSize - r.length] + r + out;
9627 } else {
9628 out = r + out;
9629 }
9630 }
9631 if (this.isZero()) {
9632 out = '0' + out;
9633 }
9634 while (out.length % padding !== 0) {
9635 out = '0' + out;
9636 }
9637 if (this.negative !== 0) {
9638 out = '-' + out;
9639 }
9640 return out;
9641 }
9642
9643 assert(false, 'Base should be between 2 and 36');
9644 };
9645
9646 BN.prototype.toNumber = function toNumber () {
9647 var ret = this.words[0];
9648 if (this.length === 2) {
9649 ret += this.words[1] * 0x4000000;
9650 } else if (this.length === 3 && this.words[2] === 0x01) {
9651 // NOTE: at this stage it is known that the top bit is set
9652 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
9653 } else if (this.length > 2) {
9654 assert(false, 'Number can only safely store up to 53 bits');
9655 }
9656 return (this.negative !== 0) ? -ret : ret;
9657 };
9658
9659 BN.prototype.toJSON = function toJSON () {
9660 return this.toString(16, 2);
9661 };
9662
9663 if (Buffer) {
9664 BN.prototype.toBuffer = function toBuffer (endian, length) {
9665 return this.toArrayLike(Buffer, endian, length);
9666 };
9667 }
9668
9669 BN.prototype.toArray = function toArray (endian, length) {
9670 return this.toArrayLike(Array, endian, length);
9671 };
9672
9673 var allocate = function allocate (ArrayType, size) {
9674 if (ArrayType.allocUnsafe) {
9675 return ArrayType.allocUnsafe(size);
9676 }
9677 return new ArrayType(size);
9678 };
9679
9680 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
9681 this._strip();
9682
9683 var byteLength = this.byteLength();
9684 var reqLength = length || Math.max(1, byteLength);
9685 assert(byteLength <= reqLength, 'byte array longer than desired length');
9686 assert(reqLength > 0, 'Requested array length <= 0');
9687
9688 var res = allocate(ArrayType, reqLength);
9689 var postfix = endian === 'le' ? 'LE' : 'BE';
9690 this['_toArrayLike' + postfix](res, byteLength);
9691 return res;
9692 };
9693
9694 BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {
9695 var position = 0;
9696 var carry = 0;
9697
9698 for (var i = 0, shift = 0; i < this.length; i++) {
9699 var word = (this.words[i] << shift) | carry;
9700
9701 res[position++] = word & 0xff;
9702 if (position < res.length) {
9703 res[position++] = (word >> 8) & 0xff;
9704 }
9705 if (position < res.length) {
9706 res[position++] = (word >> 16) & 0xff;
9707 }
9708
9709 if (shift === 6) {
9710 if (position < res.length) {
9711 res[position++] = (word >> 24) & 0xff;
9712 }
9713 carry = 0;
9714 shift = 0;
9715 } else {
9716 carry = word >>> 24;
9717 shift += 2;
9718 }
9719 }
9720
9721 if (position < res.length) {
9722 res[position++] = carry;
9723
9724 while (position < res.length) {
9725 res[position++] = 0;
9726 }
9727 }
9728 };
9729
9730 BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {
9731 var position = res.length - 1;
9732 var carry = 0;
9733
9734 for (var i = 0, shift = 0; i < this.length; i++) {
9735 var word = (this.words[i] << shift) | carry;
9736
9737 res[position--] = word & 0xff;
9738 if (position >= 0) {
9739 res[position--] = (word >> 8) & 0xff;
9740 }
9741 if (position >= 0) {
9742 res[position--] = (word >> 16) & 0xff;
9743 }
9744
9745 if (shift === 6) {
9746 if (position >= 0) {
9747 res[position--] = (word >> 24) & 0xff;
9748 }
9749 carry = 0;
9750 shift = 0;
9751 } else {
9752 carry = word >>> 24;
9753 shift += 2;
9754 }
9755 }
9756
9757 if (position >= 0) {
9758 res[position--] = carry;
9759
9760 while (position >= 0) {
9761 res[position--] = 0;
9762 }
9763 }
9764 };
9765
9766 if (Math.clz32) {
9767 BN.prototype._countBits = function _countBits (w) {
9768 return 32 - Math.clz32(w);
9769 };
9770 } else {
9771 BN.prototype._countBits = function _countBits (w) {
9772 var t = w;
9773 var r = 0;
9774 if (t >= 0x1000) {
9775 r += 13;
9776 t >>>= 13;
9777 }
9778 if (t >= 0x40) {
9779 r += 7;
9780 t >>>= 7;
9781 }
9782 if (t >= 0x8) {
9783 r += 4;
9784 t >>>= 4;
9785 }
9786 if (t >= 0x02) {
9787 r += 2;
9788 t >>>= 2;
9789 }
9790 return r + t;
9791 };
9792 }
9793
9794 BN.prototype._zeroBits = function _zeroBits (w) {
9795 // Short-cut
9796 if (w === 0) return 26;
9797
9798 var t = w;
9799 var r = 0;
9800 if ((t & 0x1fff) === 0) {
9801 r += 13;
9802 t >>>= 13;
9803 }
9804 if ((t & 0x7f) === 0) {
9805 r += 7;
9806 t >>>= 7;
9807 }
9808 if ((t & 0xf) === 0) {
9809 r += 4;
9810 t >>>= 4;
9811 }
9812 if ((t & 0x3) === 0) {
9813 r += 2;
9814 t >>>= 2;
9815 }
9816 if ((t & 0x1) === 0) {
9817 r++;
9818 }
9819 return r;
9820 };
9821
9822 // Return number of used bits in a BN
9823 BN.prototype.bitLength = function bitLength () {
9824 var w = this.words[this.length - 1];
9825 var hi = this._countBits(w);
9826 return (this.length - 1) * 26 + hi;
9827 };
9828
9829 function toBitArray (num) {
9830 var w = new Array(num.bitLength());
9831
9832 for (var bit = 0; bit < w.length; bit++) {
9833 var off = (bit / 26) | 0;
9834 var wbit = bit % 26;
9835
9836 w[bit] = (num.words[off] >>> wbit) & 0x01;
9837 }
9838
9839 return w;
9840 }
9841
9842 // Number of trailing zero bits
9843 BN.prototype.zeroBits = function zeroBits () {
9844 if (this.isZero()) return 0;
9845
9846 var r = 0;
9847 for (var i = 0; i < this.length; i++) {
9848 var b = this._zeroBits(this.words[i]);
9849 r += b;
9850 if (b !== 26) break;
9851 }
9852 return r;
9853 };
9854
9855 BN.prototype.byteLength = function byteLength () {
9856 return Math.ceil(this.bitLength() / 8);
9857 };
9858
9859 BN.prototype.toTwos = function toTwos (width) {
9860 if (this.negative !== 0) {
9861 return this.abs().inotn(width).iaddn(1);
9862 }
9863 return this.clone();
9864 };
9865
9866 BN.prototype.fromTwos = function fromTwos (width) {
9867 if (this.testn(width - 1)) {
9868 return this.notn(width).iaddn(1).ineg();
9869 }
9870 return this.clone();
9871 };
9872
9873 BN.prototype.isNeg = function isNeg () {
9874 return this.negative !== 0;
9875 };
9876
9877 // Return negative clone of `this`
9878 BN.prototype.neg = function neg () {
9879 return this.clone().ineg();
9880 };
9881
9882 BN.prototype.ineg = function ineg () {
9883 if (!this.isZero()) {
9884 this.negative ^= 1;
9885 }
9886
9887 return this;
9888 };
9889
9890 // Or `num` with `this` in-place
9891 BN.prototype.iuor = function iuor (num) {
9892 while (this.length < num.length) {
9893 this.words[this.length++] = 0;
9894 }
9895
9896 for (var i = 0; i < num.length; i++) {
9897 this.words[i] = this.words[i] | num.words[i];
9898 }
9899
9900 return this._strip();
9901 };
9902
9903 BN.prototype.ior = function ior (num) {
9904 assert((this.negative | num.negative) === 0);
9905 return this.iuor(num);
9906 };
9907
9908 // Or `num` with `this`
9909 BN.prototype.or = function or (num) {
9910 if (this.length > num.length) return this.clone().ior(num);
9911 return num.clone().ior(this);
9912 };
9913
9914 BN.prototype.uor = function uor (num) {
9915 if (this.length > num.length) return this.clone().iuor(num);
9916 return num.clone().iuor(this);
9917 };
9918
9919 // And `num` with `this` in-place
9920 BN.prototype.iuand = function iuand (num) {
9921 // b = min-length(num, this)
9922 var b;
9923 if (this.length > num.length) {
9924 b = num;
9925 } else {
9926 b = this;
9927 }
9928
9929 for (var i = 0; i < b.length; i++) {
9930 this.words[i] = this.words[i] & num.words[i];
9931 }
9932
9933 this.length = b.length;
9934
9935 return this._strip();
9936 };
9937
9938 BN.prototype.iand = function iand (num) {
9939 assert((this.negative | num.negative) === 0);
9940 return this.iuand(num);
9941 };
9942
9943 // And `num` with `this`
9944 BN.prototype.and = function and (num) {
9945 if (this.length > num.length) return this.clone().iand(num);
9946 return num.clone().iand(this);
9947 };
9948
9949 BN.prototype.uand = function uand (num) {
9950 if (this.length > num.length) return this.clone().iuand(num);
9951 return num.clone().iuand(this);
9952 };
9953
9954 // Xor `num` with `this` in-place
9955 BN.prototype.iuxor = function iuxor (num) {
9956 // a.length > b.length
9957 var a;
9958 var b;
9959 if (this.length > num.length) {
9960 a = this;
9961 b = num;
9962 } else {
9963 a = num;
9964 b = this;
9965 }
9966
9967 for (var i = 0; i < b.length; i++) {
9968 this.words[i] = a.words[i] ^ b.words[i];
9969 }
9970
9971 if (this !== a) {
9972 for (; i < a.length; i++) {
9973 this.words[i] = a.words[i];
9974 }
9975 }
9976
9977 this.length = a.length;
9978
9979 return this._strip();
9980 };
9981
9982 BN.prototype.ixor = function ixor (num) {
9983 assert((this.negative | num.negative) === 0);
9984 return this.iuxor(num);
9985 };
9986
9987 // Xor `num` with `this`
9988 BN.prototype.xor = function xor (num) {
9989 if (this.length > num.length) return this.clone().ixor(num);
9990 return num.clone().ixor(this);
9991 };
9992
9993 BN.prototype.uxor = function uxor (num) {
9994 if (this.length > num.length) return this.clone().iuxor(num);
9995 return num.clone().iuxor(this);
9996 };
9997
9998 // Not ``this`` with ``width`` bitwidth
9999 BN.prototype.inotn = function inotn (width) {
10000 assert(typeof width === 'number' && width >= 0);
10001
10002 var bytesNeeded = Math.ceil(width / 26) | 0;
10003 var bitsLeft = width % 26;
10004
10005 // Extend the buffer with leading zeroes
10006 this._expand(bytesNeeded);
10007
10008 if (bitsLeft > 0) {
10009 bytesNeeded--;
10010 }
10011
10012 // Handle complete words
10013 for (var i = 0; i < bytesNeeded; i++) {
10014 this.words[i] = ~this.words[i] & 0x3ffffff;
10015 }
10016
10017 // Handle the residue
10018 if (bitsLeft > 0) {
10019 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
10020 }
10021
10022 // And remove leading zeroes
10023 return this._strip();
10024 };
10025
10026 BN.prototype.notn = function notn (width) {
10027 return this.clone().inotn(width);
10028 };
10029
10030 // Set `bit` of `this`
10031 BN.prototype.setn = function setn (bit, val) {
10032 assert(typeof bit === 'number' && bit >= 0);
10033
10034 var off = (bit / 26) | 0;
10035 var wbit = bit % 26;
10036
10037 this._expand(off + 1);
10038
10039 if (val) {
10040 this.words[off] = this.words[off] | (1 << wbit);
10041 } else {
10042 this.words[off] = this.words[off] & ~(1 << wbit);
10043 }
10044
10045 return this._strip();
10046 };
10047
10048 // Add `num` to `this` in-place
10049 BN.prototype.iadd = function iadd (num) {
10050 var r;
10051
10052 // negative + positive
10053 if (this.negative !== 0 && num.negative === 0) {
10054 this.negative = 0;
10055 r = this.isub(num);
10056 this.negative ^= 1;
10057 return this._normSign();
10058
10059 // positive + negative
10060 } else if (this.negative === 0 && num.negative !== 0) {
10061 num.negative = 0;
10062 r = this.isub(num);
10063 num.negative = 1;
10064 return r._normSign();
10065 }
10066
10067 // a.length > b.length
10068 var a, b;
10069 if (this.length > num.length) {
10070 a = this;
10071 b = num;
10072 } else {
10073 a = num;
10074 b = this;
10075 }
10076
10077 var carry = 0;
10078 for (var i = 0; i < b.length; i++) {
10079 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
10080 this.words[i] = r & 0x3ffffff;
10081 carry = r >>> 26;
10082 }
10083 for (; carry !== 0 && i < a.length; i++) {
10084 r = (a.words[i] | 0) + carry;
10085 this.words[i] = r & 0x3ffffff;
10086 carry = r >>> 26;
10087 }
10088
10089 this.length = a.length;
10090 if (carry !== 0) {
10091 this.words[this.length] = carry;
10092 this.length++;
10093 // Copy the rest of the words
10094 } else if (a !== this) {
10095 for (; i < a.length; i++) {
10096 this.words[i] = a.words[i];
10097 }
10098 }
10099
10100 return this;
10101 };
10102
10103 // Add `num` to `this`
10104 BN.prototype.add = function add (num) {
10105 var res;
10106 if (num.negative !== 0 && this.negative === 0) {
10107 num.negative = 0;
10108 res = this.sub(num);
10109 num.negative ^= 1;
10110 return res;
10111 } else if (num.negative === 0 && this.negative !== 0) {
10112 this.negative = 0;
10113 res = num.sub(this);
10114 this.negative = 1;
10115 return res;
10116 }
10117
10118 if (this.length > num.length) return this.clone().iadd(num);
10119
10120 return num.clone().iadd(this);
10121 };
10122
10123 // Subtract `num` from `this` in-place
10124 BN.prototype.isub = function isub (num) {
10125 // this - (-num) = this + num
10126 if (num.negative !== 0) {
10127 num.negative = 0;
10128 var r = this.iadd(num);
10129 num.negative = 1;
10130 return r._normSign();
10131
10132 // -this - num = -(this + num)
10133 } else if (this.negative !== 0) {
10134 this.negative = 0;
10135 this.iadd(num);
10136 this.negative = 1;
10137 return this._normSign();
10138 }
10139
10140 // At this point both numbers are positive
10141 var cmp = this.cmp(num);
10142
10143 // Optimization - zeroify
10144 if (cmp === 0) {
10145 this.negative = 0;
10146 this.length = 1;
10147 this.words[0] = 0;
10148 return this;
10149 }
10150
10151 // a > b
10152 var a, b;
10153 if (cmp > 0) {
10154 a = this;
10155 b = num;
10156 } else {
10157 a = num;
10158 b = this;
10159 }
10160
10161 var carry = 0;
10162 for (var i = 0; i < b.length; i++) {
10163 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
10164 carry = r >> 26;
10165 this.words[i] = r & 0x3ffffff;
10166 }
10167 for (; carry !== 0 && i < a.length; i++) {
10168 r = (a.words[i] | 0) + carry;
10169 carry = r >> 26;
10170 this.words[i] = r & 0x3ffffff;
10171 }
10172
10173 // Copy rest of the words
10174 if (carry === 0 && i < a.length && a !== this) {
10175 for (; i < a.length; i++) {
10176 this.words[i] = a.words[i];
10177 }
10178 }
10179
10180 this.length = Math.max(this.length, i);
10181
10182 if (a !== this) {
10183 this.negative = 1;
10184 }
10185
10186 return this._strip();
10187 };
10188
10189 // Subtract `num` from `this`
10190 BN.prototype.sub = function sub (num) {
10191 return this.clone().isub(num);
10192 };
10193
10194 function smallMulTo (self, num, out) {
10195 out.negative = num.negative ^ self.negative;
10196 var len = (self.length + num.length) | 0;
10197 out.length = len;
10198 len = (len - 1) | 0;
10199
10200 // Peel one iteration (compiler can't do it, because of code complexity)
10201 var a = self.words[0] | 0;
10202 var b = num.words[0] | 0;
10203 var r = a * b;
10204
10205 var lo = r & 0x3ffffff;
10206 var carry = (r / 0x4000000) | 0;
10207 out.words[0] = lo;
10208
10209 for (var k = 1; k < len; k++) {
10210 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
10211 // note that ncarry could be >= 0x3ffffff
10212 var ncarry = carry >>> 26;
10213 var rword = carry & 0x3ffffff;
10214 var maxJ = Math.min(k, num.length - 1);
10215 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
10216 var i = (k - j) | 0;
10217 a = self.words[i] | 0;
10218 b = num.words[j] | 0;
10219 r = a * b + rword;
10220 ncarry += (r / 0x4000000) | 0;
10221 rword = r & 0x3ffffff;
10222 }
10223 out.words[k] = rword | 0;
10224 carry = ncarry | 0;
10225 }
10226 if (carry !== 0) {
10227 out.words[k] = carry | 0;
10228 } else {
10229 out.length--;
10230 }
10231
10232 return out._strip();
10233 }
10234
10235 // TODO(indutny): it may be reasonable to omit it for users who don't need
10236 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
10237 // multiplication (like elliptic secp256k1).
10238 var comb10MulTo = function comb10MulTo (self, num, out) {
10239 var a = self.words;
10240 var b = num.words;
10241 var o = out.words;
10242 var c = 0;
10243 var lo;
10244 var mid;
10245 var hi;
10246 var a0 = a[0] | 0;
10247 var al0 = a0 & 0x1fff;
10248 var ah0 = a0 >>> 13;
10249 var a1 = a[1] | 0;
10250 var al1 = a1 & 0x1fff;
10251 var ah1 = a1 >>> 13;
10252 var a2 = a[2] | 0;
10253 var al2 = a2 & 0x1fff;
10254 var ah2 = a2 >>> 13;
10255 var a3 = a[3] | 0;
10256 var al3 = a3 & 0x1fff;
10257 var ah3 = a3 >>> 13;
10258 var a4 = a[4] | 0;
10259 var al4 = a4 & 0x1fff;
10260 var ah4 = a4 >>> 13;
10261 var a5 = a[5] | 0;
10262 var al5 = a5 & 0x1fff;
10263 var ah5 = a5 >>> 13;
10264 var a6 = a[6] | 0;
10265 var al6 = a6 & 0x1fff;
10266 var ah6 = a6 >>> 13;
10267 var a7 = a[7] | 0;
10268 var al7 = a7 & 0x1fff;
10269 var ah7 = a7 >>> 13;
10270 var a8 = a[8] | 0;
10271 var al8 = a8 & 0x1fff;
10272 var ah8 = a8 >>> 13;
10273 var a9 = a[9] | 0;
10274 var al9 = a9 & 0x1fff;
10275 var ah9 = a9 >>> 13;
10276 var b0 = b[0] | 0;
10277 var bl0 = b0 & 0x1fff;
10278 var bh0 = b0 >>> 13;
10279 var b1 = b[1] | 0;
10280 var bl1 = b1 & 0x1fff;
10281 var bh1 = b1 >>> 13;
10282 var b2 = b[2] | 0;
10283 var bl2 = b2 & 0x1fff;
10284 var bh2 = b2 >>> 13;
10285 var b3 = b[3] | 0;
10286 var bl3 = b3 & 0x1fff;
10287 var bh3 = b3 >>> 13;
10288 var b4 = b[4] | 0;
10289 var bl4 = b4 & 0x1fff;
10290 var bh4 = b4 >>> 13;
10291 var b5 = b[5] | 0;
10292 var bl5 = b5 & 0x1fff;
10293 var bh5 = b5 >>> 13;
10294 var b6 = b[6] | 0;
10295 var bl6 = b6 & 0x1fff;
10296 var bh6 = b6 >>> 13;
10297 var b7 = b[7] | 0;
10298 var bl7 = b7 & 0x1fff;
10299 var bh7 = b7 >>> 13;
10300 var b8 = b[8] | 0;
10301 var bl8 = b8 & 0x1fff;
10302 var bh8 = b8 >>> 13;
10303 var b9 = b[9] | 0;
10304 var bl9 = b9 & 0x1fff;
10305 var bh9 = b9 >>> 13;
10306
10307 out.negative = self.negative ^ num.negative;
10308 out.length = 19;
10309 /* k = 0 */
10310 lo = Math.imul(al0, bl0);
10311 mid = Math.imul(al0, bh0);
10312 mid = (mid + Math.imul(ah0, bl0)) | 0;
10313 hi = Math.imul(ah0, bh0);
10314 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10315 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
10316 w0 &= 0x3ffffff;
10317 /* k = 1 */
10318 lo = Math.imul(al1, bl0);
10319 mid = Math.imul(al1, bh0);
10320 mid = (mid + Math.imul(ah1, bl0)) | 0;
10321 hi = Math.imul(ah1, bh0);
10322 lo = (lo + Math.imul(al0, bl1)) | 0;
10323 mid = (mid + Math.imul(al0, bh1)) | 0;
10324 mid = (mid + Math.imul(ah0, bl1)) | 0;
10325 hi = (hi + Math.imul(ah0, bh1)) | 0;
10326 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10327 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
10328 w1 &= 0x3ffffff;
10329 /* k = 2 */
10330 lo = Math.imul(al2, bl0);
10331 mid = Math.imul(al2, bh0);
10332 mid = (mid + Math.imul(ah2, bl0)) | 0;
10333 hi = Math.imul(ah2, bh0);
10334 lo = (lo + Math.imul(al1, bl1)) | 0;
10335 mid = (mid + Math.imul(al1, bh1)) | 0;
10336 mid = (mid + Math.imul(ah1, bl1)) | 0;
10337 hi = (hi + Math.imul(ah1, bh1)) | 0;
10338 lo = (lo + Math.imul(al0, bl2)) | 0;
10339 mid = (mid + Math.imul(al0, bh2)) | 0;
10340 mid = (mid + Math.imul(ah0, bl2)) | 0;
10341 hi = (hi + Math.imul(ah0, bh2)) | 0;
10342 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10343 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
10344 w2 &= 0x3ffffff;
10345 /* k = 3 */
10346 lo = Math.imul(al3, bl0);
10347 mid = Math.imul(al3, bh0);
10348 mid = (mid + Math.imul(ah3, bl0)) | 0;
10349 hi = Math.imul(ah3, bh0);
10350 lo = (lo + Math.imul(al2, bl1)) | 0;
10351 mid = (mid + Math.imul(al2, bh1)) | 0;
10352 mid = (mid + Math.imul(ah2, bl1)) | 0;
10353 hi = (hi + Math.imul(ah2, bh1)) | 0;
10354 lo = (lo + Math.imul(al1, bl2)) | 0;
10355 mid = (mid + Math.imul(al1, bh2)) | 0;
10356 mid = (mid + Math.imul(ah1, bl2)) | 0;
10357 hi = (hi + Math.imul(ah1, bh2)) | 0;
10358 lo = (lo + Math.imul(al0, bl3)) | 0;
10359 mid = (mid + Math.imul(al0, bh3)) | 0;
10360 mid = (mid + Math.imul(ah0, bl3)) | 0;
10361 hi = (hi + Math.imul(ah0, bh3)) | 0;
10362 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10363 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
10364 w3 &= 0x3ffffff;
10365 /* k = 4 */
10366 lo = Math.imul(al4, bl0);
10367 mid = Math.imul(al4, bh0);
10368 mid = (mid + Math.imul(ah4, bl0)) | 0;
10369 hi = Math.imul(ah4, bh0);
10370 lo = (lo + Math.imul(al3, bl1)) | 0;
10371 mid = (mid + Math.imul(al3, bh1)) | 0;
10372 mid = (mid + Math.imul(ah3, bl1)) | 0;
10373 hi = (hi + Math.imul(ah3, bh1)) | 0;
10374 lo = (lo + Math.imul(al2, bl2)) | 0;
10375 mid = (mid + Math.imul(al2, bh2)) | 0;
10376 mid = (mid + Math.imul(ah2, bl2)) | 0;
10377 hi = (hi + Math.imul(ah2, bh2)) | 0;
10378 lo = (lo + Math.imul(al1, bl3)) | 0;
10379 mid = (mid + Math.imul(al1, bh3)) | 0;
10380 mid = (mid + Math.imul(ah1, bl3)) | 0;
10381 hi = (hi + Math.imul(ah1, bh3)) | 0;
10382 lo = (lo + Math.imul(al0, bl4)) | 0;
10383 mid = (mid + Math.imul(al0, bh4)) | 0;
10384 mid = (mid + Math.imul(ah0, bl4)) | 0;
10385 hi = (hi + Math.imul(ah0, bh4)) | 0;
10386 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10387 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
10388 w4 &= 0x3ffffff;
10389 /* k = 5 */
10390 lo = Math.imul(al5, bl0);
10391 mid = Math.imul(al5, bh0);
10392 mid = (mid + Math.imul(ah5, bl0)) | 0;
10393 hi = Math.imul(ah5, bh0);
10394 lo = (lo + Math.imul(al4, bl1)) | 0;
10395 mid = (mid + Math.imul(al4, bh1)) | 0;
10396 mid = (mid + Math.imul(ah4, bl1)) | 0;
10397 hi = (hi + Math.imul(ah4, bh1)) | 0;
10398 lo = (lo + Math.imul(al3, bl2)) | 0;
10399 mid = (mid + Math.imul(al3, bh2)) | 0;
10400 mid = (mid + Math.imul(ah3, bl2)) | 0;
10401 hi = (hi + Math.imul(ah3, bh2)) | 0;
10402 lo = (lo + Math.imul(al2, bl3)) | 0;
10403 mid = (mid + Math.imul(al2, bh3)) | 0;
10404 mid = (mid + Math.imul(ah2, bl3)) | 0;
10405 hi = (hi + Math.imul(ah2, bh3)) | 0;
10406 lo = (lo + Math.imul(al1, bl4)) | 0;
10407 mid = (mid + Math.imul(al1, bh4)) | 0;
10408 mid = (mid + Math.imul(ah1, bl4)) | 0;
10409 hi = (hi + Math.imul(ah1, bh4)) | 0;
10410 lo = (lo + Math.imul(al0, bl5)) | 0;
10411 mid = (mid + Math.imul(al0, bh5)) | 0;
10412 mid = (mid + Math.imul(ah0, bl5)) | 0;
10413 hi = (hi + Math.imul(ah0, bh5)) | 0;
10414 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10415 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
10416 w5 &= 0x3ffffff;
10417 /* k = 6 */
10418 lo = Math.imul(al6, bl0);
10419 mid = Math.imul(al6, bh0);
10420 mid = (mid + Math.imul(ah6, bl0)) | 0;
10421 hi = Math.imul(ah6, bh0);
10422 lo = (lo + Math.imul(al5, bl1)) | 0;
10423 mid = (mid + Math.imul(al5, bh1)) | 0;
10424 mid = (mid + Math.imul(ah5, bl1)) | 0;
10425 hi = (hi + Math.imul(ah5, bh1)) | 0;
10426 lo = (lo + Math.imul(al4, bl2)) | 0;
10427 mid = (mid + Math.imul(al4, bh2)) | 0;
10428 mid = (mid + Math.imul(ah4, bl2)) | 0;
10429 hi = (hi + Math.imul(ah4, bh2)) | 0;
10430 lo = (lo + Math.imul(al3, bl3)) | 0;
10431 mid = (mid + Math.imul(al3, bh3)) | 0;
10432 mid = (mid + Math.imul(ah3, bl3)) | 0;
10433 hi = (hi + Math.imul(ah3, bh3)) | 0;
10434 lo = (lo + Math.imul(al2, bl4)) | 0;
10435 mid = (mid + Math.imul(al2, bh4)) | 0;
10436 mid = (mid + Math.imul(ah2, bl4)) | 0;
10437 hi = (hi + Math.imul(ah2, bh4)) | 0;
10438 lo = (lo + Math.imul(al1, bl5)) | 0;
10439 mid = (mid + Math.imul(al1, bh5)) | 0;
10440 mid = (mid + Math.imul(ah1, bl5)) | 0;
10441 hi = (hi + Math.imul(ah1, bh5)) | 0;
10442 lo = (lo + Math.imul(al0, bl6)) | 0;
10443 mid = (mid + Math.imul(al0, bh6)) | 0;
10444 mid = (mid + Math.imul(ah0, bl6)) | 0;
10445 hi = (hi + Math.imul(ah0, bh6)) | 0;
10446 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10447 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
10448 w6 &= 0x3ffffff;
10449 /* k = 7 */
10450 lo = Math.imul(al7, bl0);
10451 mid = Math.imul(al7, bh0);
10452 mid = (mid + Math.imul(ah7, bl0)) | 0;
10453 hi = Math.imul(ah7, bh0);
10454 lo = (lo + Math.imul(al6, bl1)) | 0;
10455 mid = (mid + Math.imul(al6, bh1)) | 0;
10456 mid = (mid + Math.imul(ah6, bl1)) | 0;
10457 hi = (hi + Math.imul(ah6, bh1)) | 0;
10458 lo = (lo + Math.imul(al5, bl2)) | 0;
10459 mid = (mid + Math.imul(al5, bh2)) | 0;
10460 mid = (mid + Math.imul(ah5, bl2)) | 0;
10461 hi = (hi + Math.imul(ah5, bh2)) | 0;
10462 lo = (lo + Math.imul(al4, bl3)) | 0;
10463 mid = (mid + Math.imul(al4, bh3)) | 0;
10464 mid = (mid + Math.imul(ah4, bl3)) | 0;
10465 hi = (hi + Math.imul(ah4, bh3)) | 0;
10466 lo = (lo + Math.imul(al3, bl4)) | 0;
10467 mid = (mid + Math.imul(al3, bh4)) | 0;
10468 mid = (mid + Math.imul(ah3, bl4)) | 0;
10469 hi = (hi + Math.imul(ah3, bh4)) | 0;
10470 lo = (lo + Math.imul(al2, bl5)) | 0;
10471 mid = (mid + Math.imul(al2, bh5)) | 0;
10472 mid = (mid + Math.imul(ah2, bl5)) | 0;
10473 hi = (hi + Math.imul(ah2, bh5)) | 0;
10474 lo = (lo + Math.imul(al1, bl6)) | 0;
10475 mid = (mid + Math.imul(al1, bh6)) | 0;
10476 mid = (mid + Math.imul(ah1, bl6)) | 0;
10477 hi = (hi + Math.imul(ah1, bh6)) | 0;
10478 lo = (lo + Math.imul(al0, bl7)) | 0;
10479 mid = (mid + Math.imul(al0, bh7)) | 0;
10480 mid = (mid + Math.imul(ah0, bl7)) | 0;
10481 hi = (hi + Math.imul(ah0, bh7)) | 0;
10482 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10483 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
10484 w7 &= 0x3ffffff;
10485 /* k = 8 */
10486 lo = Math.imul(al8, bl0);
10487 mid = Math.imul(al8, bh0);
10488 mid = (mid + Math.imul(ah8, bl0)) | 0;
10489 hi = Math.imul(ah8, bh0);
10490 lo = (lo + Math.imul(al7, bl1)) | 0;
10491 mid = (mid + Math.imul(al7, bh1)) | 0;
10492 mid = (mid + Math.imul(ah7, bl1)) | 0;
10493 hi = (hi + Math.imul(ah7, bh1)) | 0;
10494 lo = (lo + Math.imul(al6, bl2)) | 0;
10495 mid = (mid + Math.imul(al6, bh2)) | 0;
10496 mid = (mid + Math.imul(ah6, bl2)) | 0;
10497 hi = (hi + Math.imul(ah6, bh2)) | 0;
10498 lo = (lo + Math.imul(al5, bl3)) | 0;
10499 mid = (mid + Math.imul(al5, bh3)) | 0;
10500 mid = (mid + Math.imul(ah5, bl3)) | 0;
10501 hi = (hi + Math.imul(ah5, bh3)) | 0;
10502 lo = (lo + Math.imul(al4, bl4)) | 0;
10503 mid = (mid + Math.imul(al4, bh4)) | 0;
10504 mid = (mid + Math.imul(ah4, bl4)) | 0;
10505 hi = (hi + Math.imul(ah4, bh4)) | 0;
10506 lo = (lo + Math.imul(al3, bl5)) | 0;
10507 mid = (mid + Math.imul(al3, bh5)) | 0;
10508 mid = (mid + Math.imul(ah3, bl5)) | 0;
10509 hi = (hi + Math.imul(ah3, bh5)) | 0;
10510 lo = (lo + Math.imul(al2, bl6)) | 0;
10511 mid = (mid + Math.imul(al2, bh6)) | 0;
10512 mid = (mid + Math.imul(ah2, bl6)) | 0;
10513 hi = (hi + Math.imul(ah2, bh6)) | 0;
10514 lo = (lo + Math.imul(al1, bl7)) | 0;
10515 mid = (mid + Math.imul(al1, bh7)) | 0;
10516 mid = (mid + Math.imul(ah1, bl7)) | 0;
10517 hi = (hi + Math.imul(ah1, bh7)) | 0;
10518 lo = (lo + Math.imul(al0, bl8)) | 0;
10519 mid = (mid + Math.imul(al0, bh8)) | 0;
10520 mid = (mid + Math.imul(ah0, bl8)) | 0;
10521 hi = (hi + Math.imul(ah0, bh8)) | 0;
10522 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10523 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
10524 w8 &= 0x3ffffff;
10525 /* k = 9 */
10526 lo = Math.imul(al9, bl0);
10527 mid = Math.imul(al9, bh0);
10528 mid = (mid + Math.imul(ah9, bl0)) | 0;
10529 hi = Math.imul(ah9, bh0);
10530 lo = (lo + Math.imul(al8, bl1)) | 0;
10531 mid = (mid + Math.imul(al8, bh1)) | 0;
10532 mid = (mid + Math.imul(ah8, bl1)) | 0;
10533 hi = (hi + Math.imul(ah8, bh1)) | 0;
10534 lo = (lo + Math.imul(al7, bl2)) | 0;
10535 mid = (mid + Math.imul(al7, bh2)) | 0;
10536 mid = (mid + Math.imul(ah7, bl2)) | 0;
10537 hi = (hi + Math.imul(ah7, bh2)) | 0;
10538 lo = (lo + Math.imul(al6, bl3)) | 0;
10539 mid = (mid + Math.imul(al6, bh3)) | 0;
10540 mid = (mid + Math.imul(ah6, bl3)) | 0;
10541 hi = (hi + Math.imul(ah6, bh3)) | 0;
10542 lo = (lo + Math.imul(al5, bl4)) | 0;
10543 mid = (mid + Math.imul(al5, bh4)) | 0;
10544 mid = (mid + Math.imul(ah5, bl4)) | 0;
10545 hi = (hi + Math.imul(ah5, bh4)) | 0;
10546 lo = (lo + Math.imul(al4, bl5)) | 0;
10547 mid = (mid + Math.imul(al4, bh5)) | 0;
10548 mid = (mid + Math.imul(ah4, bl5)) | 0;
10549 hi = (hi + Math.imul(ah4, bh5)) | 0;
10550 lo = (lo + Math.imul(al3, bl6)) | 0;
10551 mid = (mid + Math.imul(al3, bh6)) | 0;
10552 mid = (mid + Math.imul(ah3, bl6)) | 0;
10553 hi = (hi + Math.imul(ah3, bh6)) | 0;
10554 lo = (lo + Math.imul(al2, bl7)) | 0;
10555 mid = (mid + Math.imul(al2, bh7)) | 0;
10556 mid = (mid + Math.imul(ah2, bl7)) | 0;
10557 hi = (hi + Math.imul(ah2, bh7)) | 0;
10558 lo = (lo + Math.imul(al1, bl8)) | 0;
10559 mid = (mid + Math.imul(al1, bh8)) | 0;
10560 mid = (mid + Math.imul(ah1, bl8)) | 0;
10561 hi = (hi + Math.imul(ah1, bh8)) | 0;
10562 lo = (lo + Math.imul(al0, bl9)) | 0;
10563 mid = (mid + Math.imul(al0, bh9)) | 0;
10564 mid = (mid + Math.imul(ah0, bl9)) | 0;
10565 hi = (hi + Math.imul(ah0, bh9)) | 0;
10566 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10567 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
10568 w9 &= 0x3ffffff;
10569 /* k = 10 */
10570 lo = Math.imul(al9, bl1);
10571 mid = Math.imul(al9, bh1);
10572 mid = (mid + Math.imul(ah9, bl1)) | 0;
10573 hi = Math.imul(ah9, bh1);
10574 lo = (lo + Math.imul(al8, bl2)) | 0;
10575 mid = (mid + Math.imul(al8, bh2)) | 0;
10576 mid = (mid + Math.imul(ah8, bl2)) | 0;
10577 hi = (hi + Math.imul(ah8, bh2)) | 0;
10578 lo = (lo + Math.imul(al7, bl3)) | 0;
10579 mid = (mid + Math.imul(al7, bh3)) | 0;
10580 mid = (mid + Math.imul(ah7, bl3)) | 0;
10581 hi = (hi + Math.imul(ah7, bh3)) | 0;
10582 lo = (lo + Math.imul(al6, bl4)) | 0;
10583 mid = (mid + Math.imul(al6, bh4)) | 0;
10584 mid = (mid + Math.imul(ah6, bl4)) | 0;
10585 hi = (hi + Math.imul(ah6, bh4)) | 0;
10586 lo = (lo + Math.imul(al5, bl5)) | 0;
10587 mid = (mid + Math.imul(al5, bh5)) | 0;
10588 mid = (mid + Math.imul(ah5, bl5)) | 0;
10589 hi = (hi + Math.imul(ah5, bh5)) | 0;
10590 lo = (lo + Math.imul(al4, bl6)) | 0;
10591 mid = (mid + Math.imul(al4, bh6)) | 0;
10592 mid = (mid + Math.imul(ah4, bl6)) | 0;
10593 hi = (hi + Math.imul(ah4, bh6)) | 0;
10594 lo = (lo + Math.imul(al3, bl7)) | 0;
10595 mid = (mid + Math.imul(al3, bh7)) | 0;
10596 mid = (mid + Math.imul(ah3, bl7)) | 0;
10597 hi = (hi + Math.imul(ah3, bh7)) | 0;
10598 lo = (lo + Math.imul(al2, bl8)) | 0;
10599 mid = (mid + Math.imul(al2, bh8)) | 0;
10600 mid = (mid + Math.imul(ah2, bl8)) | 0;
10601 hi = (hi + Math.imul(ah2, bh8)) | 0;
10602 lo = (lo + Math.imul(al1, bl9)) | 0;
10603 mid = (mid + Math.imul(al1, bh9)) | 0;
10604 mid = (mid + Math.imul(ah1, bl9)) | 0;
10605 hi = (hi + Math.imul(ah1, bh9)) | 0;
10606 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10607 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
10608 w10 &= 0x3ffffff;
10609 /* k = 11 */
10610 lo = Math.imul(al9, bl2);
10611 mid = Math.imul(al9, bh2);
10612 mid = (mid + Math.imul(ah9, bl2)) | 0;
10613 hi = Math.imul(ah9, bh2);
10614 lo = (lo + Math.imul(al8, bl3)) | 0;
10615 mid = (mid + Math.imul(al8, bh3)) | 0;
10616 mid = (mid + Math.imul(ah8, bl3)) | 0;
10617 hi = (hi + Math.imul(ah8, bh3)) | 0;
10618 lo = (lo + Math.imul(al7, bl4)) | 0;
10619 mid = (mid + Math.imul(al7, bh4)) | 0;
10620 mid = (mid + Math.imul(ah7, bl4)) | 0;
10621 hi = (hi + Math.imul(ah7, bh4)) | 0;
10622 lo = (lo + Math.imul(al6, bl5)) | 0;
10623 mid = (mid + Math.imul(al6, bh5)) | 0;
10624 mid = (mid + Math.imul(ah6, bl5)) | 0;
10625 hi = (hi + Math.imul(ah6, bh5)) | 0;
10626 lo = (lo + Math.imul(al5, bl6)) | 0;
10627 mid = (mid + Math.imul(al5, bh6)) | 0;
10628 mid = (mid + Math.imul(ah5, bl6)) | 0;
10629 hi = (hi + Math.imul(ah5, bh6)) | 0;
10630 lo = (lo + Math.imul(al4, bl7)) | 0;
10631 mid = (mid + Math.imul(al4, bh7)) | 0;
10632 mid = (mid + Math.imul(ah4, bl7)) | 0;
10633 hi = (hi + Math.imul(ah4, bh7)) | 0;
10634 lo = (lo + Math.imul(al3, bl8)) | 0;
10635 mid = (mid + Math.imul(al3, bh8)) | 0;
10636 mid = (mid + Math.imul(ah3, bl8)) | 0;
10637 hi = (hi + Math.imul(ah3, bh8)) | 0;
10638 lo = (lo + Math.imul(al2, bl9)) | 0;
10639 mid = (mid + Math.imul(al2, bh9)) | 0;
10640 mid = (mid + Math.imul(ah2, bl9)) | 0;
10641 hi = (hi + Math.imul(ah2, bh9)) | 0;
10642 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10643 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
10644 w11 &= 0x3ffffff;
10645 /* k = 12 */
10646 lo = Math.imul(al9, bl3);
10647 mid = Math.imul(al9, bh3);
10648 mid = (mid + Math.imul(ah9, bl3)) | 0;
10649 hi = Math.imul(ah9, bh3);
10650 lo = (lo + Math.imul(al8, bl4)) | 0;
10651 mid = (mid + Math.imul(al8, bh4)) | 0;
10652 mid = (mid + Math.imul(ah8, bl4)) | 0;
10653 hi = (hi + Math.imul(ah8, bh4)) | 0;
10654 lo = (lo + Math.imul(al7, bl5)) | 0;
10655 mid = (mid + Math.imul(al7, bh5)) | 0;
10656 mid = (mid + Math.imul(ah7, bl5)) | 0;
10657 hi = (hi + Math.imul(ah7, bh5)) | 0;
10658 lo = (lo + Math.imul(al6, bl6)) | 0;
10659 mid = (mid + Math.imul(al6, bh6)) | 0;
10660 mid = (mid + Math.imul(ah6, bl6)) | 0;
10661 hi = (hi + Math.imul(ah6, bh6)) | 0;
10662 lo = (lo + Math.imul(al5, bl7)) | 0;
10663 mid = (mid + Math.imul(al5, bh7)) | 0;
10664 mid = (mid + Math.imul(ah5, bl7)) | 0;
10665 hi = (hi + Math.imul(ah5, bh7)) | 0;
10666 lo = (lo + Math.imul(al4, bl8)) | 0;
10667 mid = (mid + Math.imul(al4, bh8)) | 0;
10668 mid = (mid + Math.imul(ah4, bl8)) | 0;
10669 hi = (hi + Math.imul(ah4, bh8)) | 0;
10670 lo = (lo + Math.imul(al3, bl9)) | 0;
10671 mid = (mid + Math.imul(al3, bh9)) | 0;
10672 mid = (mid + Math.imul(ah3, bl9)) | 0;
10673 hi = (hi + Math.imul(ah3, bh9)) | 0;
10674 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10675 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
10676 w12 &= 0x3ffffff;
10677 /* k = 13 */
10678 lo = Math.imul(al9, bl4);
10679 mid = Math.imul(al9, bh4);
10680 mid = (mid + Math.imul(ah9, bl4)) | 0;
10681 hi = Math.imul(ah9, bh4);
10682 lo = (lo + Math.imul(al8, bl5)) | 0;
10683 mid = (mid + Math.imul(al8, bh5)) | 0;
10684 mid = (mid + Math.imul(ah8, bl5)) | 0;
10685 hi = (hi + Math.imul(ah8, bh5)) | 0;
10686 lo = (lo + Math.imul(al7, bl6)) | 0;
10687 mid = (mid + Math.imul(al7, bh6)) | 0;
10688 mid = (mid + Math.imul(ah7, bl6)) | 0;
10689 hi = (hi + Math.imul(ah7, bh6)) | 0;
10690 lo = (lo + Math.imul(al6, bl7)) | 0;
10691 mid = (mid + Math.imul(al6, bh7)) | 0;
10692 mid = (mid + Math.imul(ah6, bl7)) | 0;
10693 hi = (hi + Math.imul(ah6, bh7)) | 0;
10694 lo = (lo + Math.imul(al5, bl8)) | 0;
10695 mid = (mid + Math.imul(al5, bh8)) | 0;
10696 mid = (mid + Math.imul(ah5, bl8)) | 0;
10697 hi = (hi + Math.imul(ah5, bh8)) | 0;
10698 lo = (lo + Math.imul(al4, bl9)) | 0;
10699 mid = (mid + Math.imul(al4, bh9)) | 0;
10700 mid = (mid + Math.imul(ah4, bl9)) | 0;
10701 hi = (hi + Math.imul(ah4, bh9)) | 0;
10702 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10703 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
10704 w13 &= 0x3ffffff;
10705 /* k = 14 */
10706 lo = Math.imul(al9, bl5);
10707 mid = Math.imul(al9, bh5);
10708 mid = (mid + Math.imul(ah9, bl5)) | 0;
10709 hi = Math.imul(ah9, bh5);
10710 lo = (lo + Math.imul(al8, bl6)) | 0;
10711 mid = (mid + Math.imul(al8, bh6)) | 0;
10712 mid = (mid + Math.imul(ah8, bl6)) | 0;
10713 hi = (hi + Math.imul(ah8, bh6)) | 0;
10714 lo = (lo + Math.imul(al7, bl7)) | 0;
10715 mid = (mid + Math.imul(al7, bh7)) | 0;
10716 mid = (mid + Math.imul(ah7, bl7)) | 0;
10717 hi = (hi + Math.imul(ah7, bh7)) | 0;
10718 lo = (lo + Math.imul(al6, bl8)) | 0;
10719 mid = (mid + Math.imul(al6, bh8)) | 0;
10720 mid = (mid + Math.imul(ah6, bl8)) | 0;
10721 hi = (hi + Math.imul(ah6, bh8)) | 0;
10722 lo = (lo + Math.imul(al5, bl9)) | 0;
10723 mid = (mid + Math.imul(al5, bh9)) | 0;
10724 mid = (mid + Math.imul(ah5, bl9)) | 0;
10725 hi = (hi + Math.imul(ah5, bh9)) | 0;
10726 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10727 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
10728 w14 &= 0x3ffffff;
10729 /* k = 15 */
10730 lo = Math.imul(al9, bl6);
10731 mid = Math.imul(al9, bh6);
10732 mid = (mid + Math.imul(ah9, bl6)) | 0;
10733 hi = Math.imul(ah9, bh6);
10734 lo = (lo + Math.imul(al8, bl7)) | 0;
10735 mid = (mid + Math.imul(al8, bh7)) | 0;
10736 mid = (mid + Math.imul(ah8, bl7)) | 0;
10737 hi = (hi + Math.imul(ah8, bh7)) | 0;
10738 lo = (lo + Math.imul(al7, bl8)) | 0;
10739 mid = (mid + Math.imul(al7, bh8)) | 0;
10740 mid = (mid + Math.imul(ah7, bl8)) | 0;
10741 hi = (hi + Math.imul(ah7, bh8)) | 0;
10742 lo = (lo + Math.imul(al6, bl9)) | 0;
10743 mid = (mid + Math.imul(al6, bh9)) | 0;
10744 mid = (mid + Math.imul(ah6, bl9)) | 0;
10745 hi = (hi + Math.imul(ah6, bh9)) | 0;
10746 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10747 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
10748 w15 &= 0x3ffffff;
10749 /* k = 16 */
10750 lo = Math.imul(al9, bl7);
10751 mid = Math.imul(al9, bh7);
10752 mid = (mid + Math.imul(ah9, bl7)) | 0;
10753 hi = Math.imul(ah9, bh7);
10754 lo = (lo + Math.imul(al8, bl8)) | 0;
10755 mid = (mid + Math.imul(al8, bh8)) | 0;
10756 mid = (mid + Math.imul(ah8, bl8)) | 0;
10757 hi = (hi + Math.imul(ah8, bh8)) | 0;
10758 lo = (lo + Math.imul(al7, bl9)) | 0;
10759 mid = (mid + Math.imul(al7, bh9)) | 0;
10760 mid = (mid + Math.imul(ah7, bl9)) | 0;
10761 hi = (hi + Math.imul(ah7, bh9)) | 0;
10762 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10763 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
10764 w16 &= 0x3ffffff;
10765 /* k = 17 */
10766 lo = Math.imul(al9, bl8);
10767 mid = Math.imul(al9, bh8);
10768 mid = (mid + Math.imul(ah9, bl8)) | 0;
10769 hi = Math.imul(ah9, bh8);
10770 lo = (lo + Math.imul(al8, bl9)) | 0;
10771 mid = (mid + Math.imul(al8, bh9)) | 0;
10772 mid = (mid + Math.imul(ah8, bl9)) | 0;
10773 hi = (hi + Math.imul(ah8, bh9)) | 0;
10774 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10775 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
10776 w17 &= 0x3ffffff;
10777 /* k = 18 */
10778 lo = Math.imul(al9, bl9);
10779 mid = Math.imul(al9, bh9);
10780 mid = (mid + Math.imul(ah9, bl9)) | 0;
10781 hi = Math.imul(ah9, bh9);
10782 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
10783 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
10784 w18 &= 0x3ffffff;
10785 o[0] = w0;
10786 o[1] = w1;
10787 o[2] = w2;
10788 o[3] = w3;
10789 o[4] = w4;
10790 o[5] = w5;
10791 o[6] = w6;
10792 o[7] = w7;
10793 o[8] = w8;
10794 o[9] = w9;
10795 o[10] = w10;
10796 o[11] = w11;
10797 o[12] = w12;
10798 o[13] = w13;
10799 o[14] = w14;
10800 o[15] = w15;
10801 o[16] = w16;
10802 o[17] = w17;
10803 o[18] = w18;
10804 if (c !== 0) {
10805 o[19] = c;
10806 out.length++;
10807 }
10808 return out;
10809 };
10810
10811 // Polyfill comb
10812 if (!Math.imul) {
10813 comb10MulTo = smallMulTo;
10814 }
10815
10816 function bigMulTo (self, num, out) {
10817 out.negative = num.negative ^ self.negative;
10818 out.length = self.length + num.length;
10819
10820 var carry = 0;
10821 var hncarry = 0;
10822 for (var k = 0; k < out.length - 1; k++) {
10823 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
10824 // note that ncarry could be >= 0x3ffffff
10825 var ncarry = hncarry;
10826 hncarry = 0;
10827 var rword = carry & 0x3ffffff;
10828 var maxJ = Math.min(k, num.length - 1);
10829 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
10830 var i = k - j;
10831 var a = self.words[i] | 0;
10832 var b = num.words[j] | 0;
10833 var r = a * b;
10834
10835 var lo = r & 0x3ffffff;
10836 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
10837 lo = (lo + rword) | 0;
10838 rword = lo & 0x3ffffff;
10839 ncarry = (ncarry + (lo >>> 26)) | 0;
10840
10841 hncarry += ncarry >>> 26;
10842 ncarry &= 0x3ffffff;
10843 }
10844 out.words[k] = rword;
10845 carry = ncarry;
10846 ncarry = hncarry;
10847 }
10848 if (carry !== 0) {
10849 out.words[k] = carry;
10850 } else {
10851 out.length--;
10852 }
10853
10854 return out._strip();
10855 }
10856
10857 function jumboMulTo (self, num, out) {
10858 // Temporary disable, see https://github.com/indutny/bn.js/issues/211
10859 // var fftm = new FFTM();
10860 // return fftm.mulp(self, num, out);
10861 return bigMulTo(self, num, out);
10862 }
10863
10864 BN.prototype.mulTo = function mulTo (num, out) {
10865 var res;
10866 var len = this.length + num.length;
10867 if (this.length === 10 && num.length === 10) {
10868 res = comb10MulTo(this, num, out);
10869 } else if (len < 63) {
10870 res = smallMulTo(this, num, out);
10871 } else if (len < 1024) {
10872 res = bigMulTo(this, num, out);
10873 } else {
10874 res = jumboMulTo(this, num, out);
10875 }
10876
10877 return res;
10878 };
10879
10880 // Cooley-Tukey algorithm for FFT
10881 // slightly revisited to rely on looping instead of recursion
10882
10883 function FFTM (x, y) {
10884 this.x = x;
10885 this.y = y;
10886 }
10887
10888 FFTM.prototype.makeRBT = function makeRBT (N) {
10889 var t = new Array(N);
10890 var l = BN.prototype._countBits(N) - 1;
10891 for (var i = 0; i < N; i++) {
10892 t[i] = this.revBin(i, l, N);
10893 }
10894
10895 return t;
10896 };
10897
10898 // Returns binary-reversed representation of `x`
10899 FFTM.prototype.revBin = function revBin (x, l, N) {
10900 if (x === 0 || x === N - 1) return x;
10901
10902 var rb = 0;
10903 for (var i = 0; i < l; i++) {
10904 rb |= (x & 1) << (l - i - 1);
10905 x >>= 1;
10906 }
10907
10908 return rb;
10909 };
10910
10911 // Performs "tweedling" phase, therefore 'emulating'
10912 // behaviour of the recursive algorithm
10913 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
10914 for (var i = 0; i < N; i++) {
10915 rtws[i] = rws[rbt[i]];
10916 itws[i] = iws[rbt[i]];
10917 }
10918 };
10919
10920 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
10921 this.permute(rbt, rws, iws, rtws, itws, N);
10922
10923 for (var s = 1; s < N; s <<= 1) {
10924 var l = s << 1;
10925
10926 var rtwdf = Math.cos(2 * Math.PI / l);
10927 var itwdf = Math.sin(2 * Math.PI / l);
10928
10929 for (var p = 0; p < N; p += l) {
10930 var rtwdf_ = rtwdf;
10931 var itwdf_ = itwdf;
10932
10933 for (var j = 0; j < s; j++) {
10934 var re = rtws[p + j];
10935 var ie = itws[p + j];
10936
10937 var ro = rtws[p + j + s];
10938 var io = itws[p + j + s];
10939
10940 var rx = rtwdf_ * ro - itwdf_ * io;
10941
10942 io = rtwdf_ * io + itwdf_ * ro;
10943 ro = rx;
10944
10945 rtws[p + j] = re + ro;
10946 itws[p + j] = ie + io;
10947
10948 rtws[p + j + s] = re - ro;
10949 itws[p + j + s] = ie - io;
10950
10951 /* jshint maxdepth : false */
10952 if (j !== l) {
10953 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
10954
10955 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
10956 rtwdf_ = rx;
10957 }
10958 }
10959 }
10960 }
10961 };
10962
10963 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
10964 var N = Math.max(m, n) | 1;
10965 var odd = N & 1;
10966 var i = 0;
10967 for (N = N / 2 | 0; N; N = N >>> 1) {
10968 i++;
10969 }
10970
10971 return 1 << i + 1 + odd;
10972 };
10973
10974 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
10975 if (N <= 1) return;
10976
10977 for (var i = 0; i < N / 2; i++) {
10978 var t = rws[i];
10979
10980 rws[i] = rws[N - i - 1];
10981 rws[N - i - 1] = t;
10982
10983 t = iws[i];
10984
10985 iws[i] = -iws[N - i - 1];
10986 iws[N - i - 1] = -t;
10987 }
10988 };
10989
10990 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
10991 var carry = 0;
10992 for (var i = 0; i < N / 2; i++) {
10993 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
10994 Math.round(ws[2 * i] / N) +
10995 carry;
10996
10997 ws[i] = w & 0x3ffffff;
10998
10999 if (w < 0x4000000) {
11000 carry = 0;
11001 } else {
11002 carry = w / 0x4000000 | 0;
11003 }
11004 }
11005
11006 return ws;
11007 };
11008
11009 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
11010 var carry = 0;
11011 for (var i = 0; i < len; i++) {
11012 carry = carry + (ws[i] | 0);
11013
11014 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
11015 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
11016 }
11017
11018 // Pad with zeroes
11019 for (i = 2 * len; i < N; ++i) {
11020 rws[i] = 0;
11021 }
11022
11023 assert(carry === 0);
11024 assert((carry & ~0x1fff) === 0);
11025 };
11026
11027 FFTM.prototype.stub = function stub (N) {
11028 var ph = new Array(N);
11029 for (var i = 0; i < N; i++) {
11030 ph[i] = 0;
11031 }
11032
11033 return ph;
11034 };
11035
11036 FFTM.prototype.mulp = function mulp (x, y, out) {
11037 var N = 2 * this.guessLen13b(x.length, y.length);
11038
11039 var rbt = this.makeRBT(N);
11040
11041 var _ = this.stub(N);
11042
11043 var rws = new Array(N);
11044 var rwst = new Array(N);
11045 var iwst = new Array(N);
11046
11047 var nrws = new Array(N);
11048 var nrwst = new Array(N);
11049 var niwst = new Array(N);
11050
11051 var rmws = out.words;
11052 rmws.length = N;
11053
11054 this.convert13b(x.words, x.length, rws, N);
11055 this.convert13b(y.words, y.length, nrws, N);
11056
11057 this.transform(rws, _, rwst, iwst, N, rbt);
11058 this.transform(nrws, _, nrwst, niwst, N, rbt);
11059
11060 for (var i = 0; i < N; i++) {
11061 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
11062 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
11063 rwst[i] = rx;
11064 }
11065
11066 this.conjugate(rwst, iwst, N);
11067 this.transform(rwst, iwst, rmws, _, N, rbt);
11068 this.conjugate(rmws, _, N);
11069 this.normalize13b(rmws, N);
11070
11071 out.negative = x.negative ^ y.negative;
11072 out.length = x.length + y.length;
11073 return out._strip();
11074 };
11075
11076 // Multiply `this` by `num`
11077 BN.prototype.mul = function mul (num) {
11078 var out = new BN(null);
11079 out.words = new Array(this.length + num.length);
11080 return this.mulTo(num, out);
11081 };
11082
11083 // Multiply employing FFT
11084 BN.prototype.mulf = function mulf (num) {
11085 var out = new BN(null);
11086 out.words = new Array(this.length + num.length);
11087 return jumboMulTo(this, num, out);
11088 };
11089
11090 // In-place Multiplication
11091 BN.prototype.imul = function imul (num) {
11092 return this.clone().mulTo(num, this);
11093 };
11094
11095 BN.prototype.imuln = function imuln (num) {
11096 var isNegNum = num < 0;
11097 if (isNegNum) num = -num;
11098
11099 assert(typeof num === 'number');
11100 assert(num < 0x4000000);
11101
11102 // Carry
11103 var carry = 0;
11104 for (var i = 0; i < this.length; i++) {
11105 var w = (this.words[i] | 0) * num;
11106 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
11107 carry >>= 26;
11108 carry += (w / 0x4000000) | 0;
11109 // NOTE: lo is 27bit maximum
11110 carry += lo >>> 26;
11111 this.words[i] = lo & 0x3ffffff;
11112 }
11113
11114 if (carry !== 0) {
11115 this.words[i] = carry;
11116 this.length++;
11117 }
11118
11119 return isNegNum ? this.ineg() : this;
11120 };
11121
11122 BN.prototype.muln = function muln (num) {
11123 return this.clone().imuln(num);
11124 };
11125
11126 // `this` * `this`
11127 BN.prototype.sqr = function sqr () {
11128 return this.mul(this);
11129 };
11130
11131 // `this` * `this` in-place
11132 BN.prototype.isqr = function isqr () {
11133 return this.imul(this.clone());
11134 };
11135
11136 // Math.pow(`this`, `num`)
11137 BN.prototype.pow = function pow (num) {
11138 var w = toBitArray(num);
11139 if (w.length === 0) return new BN(1);
11140
11141 // Skip leading zeroes
11142 var res = this;
11143 for (var i = 0; i < w.length; i++, res = res.sqr()) {
11144 if (w[i] !== 0) break;
11145 }
11146
11147 if (++i < w.length) {
11148 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
11149 if (w[i] === 0) continue;
11150
11151 res = res.mul(q);
11152 }
11153 }
11154
11155 return res;
11156 };
11157
11158 // Shift-left in-place
11159 BN.prototype.iushln = function iushln (bits) {
11160 assert(typeof bits === 'number' && bits >= 0);
11161 var r = bits % 26;
11162 var s = (bits - r) / 26;
11163 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
11164 var i;
11165
11166 if (r !== 0) {
11167 var carry = 0;
11168
11169 for (i = 0; i < this.length; i++) {
11170 var newCarry = this.words[i] & carryMask;
11171 var c = ((this.words[i] | 0) - newCarry) << r;
11172 this.words[i] = c | carry;
11173 carry = newCarry >>> (26 - r);
11174 }
11175
11176 if (carry) {
11177 this.words[i] = carry;
11178 this.length++;
11179 }
11180 }
11181
11182 if (s !== 0) {
11183 for (i = this.length - 1; i >= 0; i--) {
11184 this.words[i + s] = this.words[i];
11185 }
11186
11187 for (i = 0; i < s; i++) {
11188 this.words[i] = 0;
11189 }
11190
11191 this.length += s;
11192 }
11193
11194 return this._strip();
11195 };
11196
11197 BN.prototype.ishln = function ishln (bits) {
11198 // TODO(indutny): implement me
11199 assert(this.negative === 0);
11200 return this.iushln(bits);
11201 };
11202
11203 // Shift-right in-place
11204 // NOTE: `hint` is a lowest bit before trailing zeroes
11205 // NOTE: if `extended` is present - it will be filled with destroyed bits
11206 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
11207 assert(typeof bits === 'number' && bits >= 0);
11208 var h;
11209 if (hint) {
11210 h = (hint - (hint % 26)) / 26;
11211 } else {
11212 h = 0;
11213 }
11214
11215 var r = bits % 26;
11216 var s = Math.min((bits - r) / 26, this.length);
11217 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
11218 var maskedWords = extended;
11219
11220 h -= s;
11221 h = Math.max(0, h);
11222
11223 // Extended mode, copy masked part
11224 if (maskedWords) {
11225 for (var i = 0; i < s; i++) {
11226 maskedWords.words[i] = this.words[i];
11227 }
11228 maskedWords.length = s;
11229 }
11230
11231 if (s === 0) {
11232 // No-op, we should not move anything at all
11233 } else if (this.length > s) {
11234 this.length -= s;
11235 for (i = 0; i < this.length; i++) {
11236 this.words[i] = this.words[i + s];
11237 }
11238 } else {
11239 this.words[0] = 0;
11240 this.length = 1;
11241 }
11242
11243 var carry = 0;
11244 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
11245 var word = this.words[i] | 0;
11246 this.words[i] = (carry << (26 - r)) | (word >>> r);
11247 carry = word & mask;
11248 }
11249
11250 // Push carried bits as a mask
11251 if (maskedWords && carry !== 0) {
11252 maskedWords.words[maskedWords.length++] = carry;
11253 }
11254
11255 if (this.length === 0) {
11256 this.words[0] = 0;
11257 this.length = 1;
11258 }
11259
11260 return this._strip();
11261 };
11262
11263 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
11264 // TODO(indutny): implement me
11265 assert(this.negative === 0);
11266 return this.iushrn(bits, hint, extended);
11267 };
11268
11269 // Shift-left
11270 BN.prototype.shln = function shln (bits) {
11271 return this.clone().ishln(bits);
11272 };
11273
11274 BN.prototype.ushln = function ushln (bits) {
11275 return this.clone().iushln(bits);
11276 };
11277
11278 // Shift-right
11279 BN.prototype.shrn = function shrn (bits) {
11280 return this.clone().ishrn(bits);
11281 };
11282
11283 BN.prototype.ushrn = function ushrn (bits) {
11284 return this.clone().iushrn(bits);
11285 };
11286
11287 // Test if n bit is set
11288 BN.prototype.testn = function testn (bit) {
11289 assert(typeof bit === 'number' && bit >= 0);
11290 var r = bit % 26;
11291 var s = (bit - r) / 26;
11292 var q = 1 << r;
11293
11294 // Fast case: bit is much higher than all existing words
11295 if (this.length <= s) return false;
11296
11297 // Check bit and return
11298 var w = this.words[s];
11299
11300 return !!(w & q);
11301 };
11302
11303 // Return only lowers bits of number (in-place)
11304 BN.prototype.imaskn = function imaskn (bits) {
11305 assert(typeof bits === 'number' && bits >= 0);
11306 var r = bits % 26;
11307 var s = (bits - r) / 26;
11308
11309 assert(this.negative === 0, 'imaskn works only with positive numbers');
11310
11311 if (this.length <= s) {
11312 return this;
11313 }
11314
11315 if (r !== 0) {
11316 s++;
11317 }
11318 this.length = Math.min(s, this.length);
11319
11320 if (r !== 0) {
11321 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
11322 this.words[this.length - 1] &= mask;
11323 }
11324
11325 return this._strip();
11326 };
11327
11328 // Return only lowers bits of number
11329 BN.prototype.maskn = function maskn (bits) {
11330 return this.clone().imaskn(bits);
11331 };
11332
11333 // Add plain number `num` to `this`
11334 BN.prototype.iaddn = function iaddn (num) {
11335 assert(typeof num === 'number');
11336 assert(num < 0x4000000);
11337 if (num < 0) return this.isubn(-num);
11338
11339 // Possible sign change
11340 if (this.negative !== 0) {
11341 if (this.length === 1 && (this.words[0] | 0) <= num) {
11342 this.words[0] = num - (this.words[0] | 0);
11343 this.negative = 0;
11344 return this;
11345 }
11346
11347 this.negative = 0;
11348 this.isubn(num);
11349 this.negative = 1;
11350 return this;
11351 }
11352
11353 // Add without checks
11354 return this._iaddn(num);
11355 };
11356
11357 BN.prototype._iaddn = function _iaddn (num) {
11358 this.words[0] += num;
11359
11360 // Carry
11361 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
11362 this.words[i] -= 0x4000000;
11363 if (i === this.length - 1) {
11364 this.words[i + 1] = 1;
11365 } else {
11366 this.words[i + 1]++;
11367 }
11368 }
11369 this.length = Math.max(this.length, i + 1);
11370
11371 return this;
11372 };
11373
11374 // Subtract plain number `num` from `this`
11375 BN.prototype.isubn = function isubn (num) {
11376 assert(typeof num === 'number');
11377 assert(num < 0x4000000);
11378 if (num < 0) return this.iaddn(-num);
11379
11380 if (this.negative !== 0) {
11381 this.negative = 0;
11382 this.iaddn(num);
11383 this.negative = 1;
11384 return this;
11385 }
11386
11387 this.words[0] -= num;
11388
11389 if (this.length === 1 && this.words[0] < 0) {
11390 this.words[0] = -this.words[0];
11391 this.negative = 1;
11392 } else {
11393 // Carry
11394 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
11395 this.words[i] += 0x4000000;
11396 this.words[i + 1] -= 1;
11397 }
11398 }
11399
11400 return this._strip();
11401 };
11402
11403 BN.prototype.addn = function addn (num) {
11404 return this.clone().iaddn(num);
11405 };
11406
11407 BN.prototype.subn = function subn (num) {
11408 return this.clone().isubn(num);
11409 };
11410
11411 BN.prototype.iabs = function iabs () {
11412 this.negative = 0;
11413
11414 return this;
11415 };
11416
11417 BN.prototype.abs = function abs () {
11418 return this.clone().iabs();
11419 };
11420
11421 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
11422 var len = num.length + shift;
11423 var i;
11424
11425 this._expand(len);
11426
11427 var w;
11428 var carry = 0;
11429 for (i = 0; i < num.length; i++) {
11430 w = (this.words[i + shift] | 0) + carry;
11431 var right = (num.words[i] | 0) * mul;
11432 w -= right & 0x3ffffff;
11433 carry = (w >> 26) - ((right / 0x4000000) | 0);
11434 this.words[i + shift] = w & 0x3ffffff;
11435 }
11436 for (; i < this.length - shift; i++) {
11437 w = (this.words[i + shift] | 0) + carry;
11438 carry = w >> 26;
11439 this.words[i + shift] = w & 0x3ffffff;
11440 }
11441
11442 if (carry === 0) return this._strip();
11443
11444 // Subtraction overflow
11445 assert(carry === -1);
11446 carry = 0;
11447 for (i = 0; i < this.length; i++) {
11448 w = -(this.words[i] | 0) + carry;
11449 carry = w >> 26;
11450 this.words[i] = w & 0x3ffffff;
11451 }
11452 this.negative = 1;
11453
11454 return this._strip();
11455 };
11456
11457 BN.prototype._wordDiv = function _wordDiv (num, mode) {
11458 var shift = this.length - num.length;
11459
11460 var a = this.clone();
11461 var b = num;
11462
11463 // Normalize
11464 var bhi = b.words[b.length - 1] | 0;
11465 var bhiBits = this._countBits(bhi);
11466 shift = 26 - bhiBits;
11467 if (shift !== 0) {
11468 b = b.ushln(shift);
11469 a.iushln(shift);
11470 bhi = b.words[b.length - 1] | 0;
11471 }
11472
11473 // Initialize quotient
11474 var m = a.length - b.length;
11475 var q;
11476
11477 if (mode !== 'mod') {
11478 q = new BN(null);
11479 q.length = m + 1;
11480 q.words = new Array(q.length);
11481 for (var i = 0; i < q.length; i++) {
11482 q.words[i] = 0;
11483 }
11484 }
11485
11486 var diff = a.clone()._ishlnsubmul(b, 1, m);
11487 if (diff.negative === 0) {
11488 a = diff;
11489 if (q) {
11490 q.words[m] = 1;
11491 }
11492 }
11493
11494 for (var j = m - 1; j >= 0; j--) {
11495 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
11496 (a.words[b.length + j - 1] | 0);
11497
11498 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
11499 // (0x7ffffff)
11500 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
11501
11502 a._ishlnsubmul(b, qj, j);
11503 while (a.negative !== 0) {
11504 qj--;
11505 a.negative = 0;
11506 a._ishlnsubmul(b, 1, j);
11507 if (!a.isZero()) {
11508 a.negative ^= 1;
11509 }
11510 }
11511 if (q) {
11512 q.words[j] = qj;
11513 }
11514 }
11515 if (q) {
11516 q._strip();
11517 }
11518 a._strip();
11519
11520 // Denormalize
11521 if (mode !== 'div' && shift !== 0) {
11522 a.iushrn(shift);
11523 }
11524
11525 return {
11526 div: q || null,
11527 mod: a
11528 };
11529 };
11530
11531 // NOTE: 1) `mode` can be set to `mod` to request mod only,
11532 // to `div` to request div only, or be absent to
11533 // request both div & mod
11534 // 2) `positive` is true if unsigned mod is requested
11535 BN.prototype.divmod = function divmod (num, mode, positive) {
11536 assert(!num.isZero());
11537
11538 if (this.isZero()) {
11539 return {
11540 div: new BN(0),
11541 mod: new BN(0)
11542 };
11543 }
11544
11545 var div, mod, res;
11546 if (this.negative !== 0 && num.negative === 0) {
11547 res = this.neg().divmod(num, mode);
11548
11549 if (mode !== 'mod') {
11550 div = res.div.neg();
11551 }
11552
11553 if (mode !== 'div') {
11554 mod = res.mod.neg();
11555 if (positive && mod.negative !== 0) {
11556 mod.iadd(num);
11557 }
11558 }
11559
11560 return {
11561 div: div,
11562 mod: mod
11563 };
11564 }
11565
11566 if (this.negative === 0 && num.negative !== 0) {
11567 res = this.divmod(num.neg(), mode);
11568
11569 if (mode !== 'mod') {
11570 div = res.div.neg();
11571 }
11572
11573 return {
11574 div: div,
11575 mod: res.mod
11576 };
11577 }
11578
11579 if ((this.negative & num.negative) !== 0) {
11580 res = this.neg().divmod(num.neg(), mode);
11581
11582 if (mode !== 'div') {
11583 mod = res.mod.neg();
11584 if (positive && mod.negative !== 0) {
11585 mod.isub(num);
11586 }
11587 }
11588
11589 return {
11590 div: res.div,
11591 mod: mod
11592 };
11593 }
11594
11595 // Both numbers are positive at this point
11596
11597 // Strip both numbers to approximate shift value
11598 if (num.length > this.length || this.cmp(num) < 0) {
11599 return {
11600 div: new BN(0),
11601 mod: this
11602 };
11603 }
11604
11605 // Very short reduction
11606 if (num.length === 1) {
11607 if (mode === 'div') {
11608 return {
11609 div: this.divn(num.words[0]),
11610 mod: null
11611 };
11612 }
11613
11614 if (mode === 'mod') {
11615 return {
11616 div: null,
11617 mod: new BN(this.modrn(num.words[0]))
11618 };
11619 }
11620
11621 return {
11622 div: this.divn(num.words[0]),
11623 mod: new BN(this.modrn(num.words[0]))
11624 };
11625 }
11626
11627 return this._wordDiv(num, mode);
11628 };
11629
11630 // Find `this` / `num`
11631 BN.prototype.div = function div (num) {
11632 return this.divmod(num, 'div', false).div;
11633 };
11634
11635 // Find `this` % `num`
11636 BN.prototype.mod = function mod (num) {
11637 return this.divmod(num, 'mod', false).mod;
11638 };
11639
11640 BN.prototype.umod = function umod (num) {
11641 return this.divmod(num, 'mod', true).mod;
11642 };
11643
11644 // Find Round(`this` / `num`)
11645 BN.prototype.divRound = function divRound (num) {
11646 var dm = this.divmod(num);
11647
11648 // Fast case - exact division
11649 if (dm.mod.isZero()) return dm.div;
11650
11651 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
11652
11653 var half = num.ushrn(1);
11654 var r2 = num.andln(1);
11655 var cmp = mod.cmp(half);
11656
11657 // Round down
11658 if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;
11659
11660 // Round up
11661 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
11662 };
11663
11664 BN.prototype.modrn = function modrn (num) {
11665 var isNegNum = num < 0;
11666 if (isNegNum) num = -num;
11667
11668 assert(num <= 0x3ffffff);
11669 var p = (1 << 26) % num;
11670
11671 var acc = 0;
11672 for (var i = this.length - 1; i >= 0; i--) {
11673 acc = (p * acc + (this.words[i] | 0)) % num;
11674 }
11675
11676 return isNegNum ? -acc : acc;
11677 };
11678
11679 // WARNING: DEPRECATED
11680 BN.prototype.modn = function modn (num) {
11681 return this.modrn(num);
11682 };
11683
11684 // In-place division by number
11685 BN.prototype.idivn = function idivn (num) {
11686 var isNegNum = num < 0;
11687 if (isNegNum) num = -num;
11688
11689 assert(num <= 0x3ffffff);
11690
11691 var carry = 0;
11692 for (var i = this.length - 1; i >= 0; i--) {
11693 var w = (this.words[i] | 0) + carry * 0x4000000;
11694 this.words[i] = (w / num) | 0;
11695 carry = w % num;
11696 }
11697
11698 this._strip();
11699 return isNegNum ? this.ineg() : this;
11700 };
11701
11702 BN.prototype.divn = function divn (num) {
11703 return this.clone().idivn(num);
11704 };
11705
11706 BN.prototype.egcd = function egcd (p) {
11707 assert(p.negative === 0);
11708 assert(!p.isZero());
11709
11710 var x = this;
11711 var y = p.clone();
11712
11713 if (x.negative !== 0) {
11714 x = x.umod(p);
11715 } else {
11716 x = x.clone();
11717 }
11718
11719 // A * x + B * y = x
11720 var A = new BN(1);
11721 var B = new BN(0);
11722
11723 // C * x + D * y = y
11724 var C = new BN(0);
11725 var D = new BN(1);
11726
11727 var g = 0;
11728
11729 while (x.isEven() && y.isEven()) {
11730 x.iushrn(1);
11731 y.iushrn(1);
11732 ++g;
11733 }
11734
11735 var yp = y.clone();
11736 var xp = x.clone();
11737
11738 while (!x.isZero()) {
11739 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
11740 if (i > 0) {
11741 x.iushrn(i);
11742 while (i-- > 0) {
11743 if (A.isOdd() || B.isOdd()) {
11744 A.iadd(yp);
11745 B.isub(xp);
11746 }
11747
11748 A.iushrn(1);
11749 B.iushrn(1);
11750 }
11751 }
11752
11753 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
11754 if (j > 0) {
11755 y.iushrn(j);
11756 while (j-- > 0) {
11757 if (C.isOdd() || D.isOdd()) {
11758 C.iadd(yp);
11759 D.isub(xp);
11760 }
11761
11762 C.iushrn(1);
11763 D.iushrn(1);
11764 }
11765 }
11766
11767 if (x.cmp(y) >= 0) {
11768 x.isub(y);
11769 A.isub(C);
11770 B.isub(D);
11771 } else {
11772 y.isub(x);
11773 C.isub(A);
11774 D.isub(B);
11775 }
11776 }
11777
11778 return {
11779 a: C,
11780 b: D,
11781 gcd: y.iushln(g)
11782 };
11783 };
11784
11785 // This is reduced incarnation of the binary EEA
11786 // above, designated to invert members of the
11787 // _prime_ fields F(p) at a maximal speed
11788 BN.prototype._invmp = function _invmp (p) {
11789 assert(p.negative === 0);
11790 assert(!p.isZero());
11791
11792 var a = this;
11793 var b = p.clone();
11794
11795 if (a.negative !== 0) {
11796 a = a.umod(p);
11797 } else {
11798 a = a.clone();
11799 }
11800
11801 var x1 = new BN(1);
11802 var x2 = new BN(0);
11803
11804 var delta = b.clone();
11805
11806 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
11807 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
11808 if (i > 0) {
11809 a.iushrn(i);
11810 while (i-- > 0) {
11811 if (x1.isOdd()) {
11812 x1.iadd(delta);
11813 }
11814
11815 x1.iushrn(1);
11816 }
11817 }
11818
11819 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
11820 if (j > 0) {
11821 b.iushrn(j);
11822 while (j-- > 0) {
11823 if (x2.isOdd()) {
11824 x2.iadd(delta);
11825 }
11826
11827 x2.iushrn(1);
11828 }
11829 }
11830
11831 if (a.cmp(b) >= 0) {
11832 a.isub(b);
11833 x1.isub(x2);
11834 } else {
11835 b.isub(a);
11836 x2.isub(x1);
11837 }
11838 }
11839
11840 var res;
11841 if (a.cmpn(1) === 0) {
11842 res = x1;
11843 } else {
11844 res = x2;
11845 }
11846
11847 if (res.cmpn(0) < 0) {
11848 res.iadd(p);
11849 }
11850
11851 return res;
11852 };
11853
11854 BN.prototype.gcd = function gcd (num) {
11855 if (this.isZero()) return num.abs();
11856 if (num.isZero()) return this.abs();
11857
11858 var a = this.clone();
11859 var b = num.clone();
11860 a.negative = 0;
11861 b.negative = 0;
11862
11863 // Remove common factor of two
11864 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
11865 a.iushrn(1);
11866 b.iushrn(1);
11867 }
11868
11869 do {
11870 while (a.isEven()) {
11871 a.iushrn(1);
11872 }
11873 while (b.isEven()) {
11874 b.iushrn(1);
11875 }
11876
11877 var r = a.cmp(b);
11878 if (r < 0) {
11879 // Swap `a` and `b` to make `a` always bigger than `b`
11880 var t = a;
11881 a = b;
11882 b = t;
11883 } else if (r === 0 || b.cmpn(1) === 0) {
11884 break;
11885 }
11886
11887 a.isub(b);
11888 } while (true);
11889
11890 return b.iushln(shift);
11891 };
11892
11893 // Invert number in the field F(num)
11894 BN.prototype.invm = function invm (num) {
11895 return this.egcd(num).a.umod(num);
11896 };
11897
11898 BN.prototype.isEven = function isEven () {
11899 return (this.words[0] & 1) === 0;
11900 };
11901
11902 BN.prototype.isOdd = function isOdd () {
11903 return (this.words[0] & 1) === 1;
11904 };
11905
11906 // And first word and num
11907 BN.prototype.andln = function andln (num) {
11908 return this.words[0] & num;
11909 };
11910
11911 // Increment at the bit position in-line
11912 BN.prototype.bincn = function bincn (bit) {
11913 assert(typeof bit === 'number');
11914 var r = bit % 26;
11915 var s = (bit - r) / 26;
11916 var q = 1 << r;
11917
11918 // Fast case: bit is much higher than all existing words
11919 if (this.length <= s) {
11920 this._expand(s + 1);
11921 this.words[s] |= q;
11922 return this;
11923 }
11924
11925 // Add bit and propagate, if needed
11926 var carry = q;
11927 for (var i = s; carry !== 0 && i < this.length; i++) {
11928 var w = this.words[i] | 0;
11929 w += carry;
11930 carry = w >>> 26;
11931 w &= 0x3ffffff;
11932 this.words[i] = w;
11933 }
11934 if (carry !== 0) {
11935 this.words[i] = carry;
11936 this.length++;
11937 }
11938 return this;
11939 };
11940
11941 BN.prototype.isZero = function isZero () {
11942 return this.length === 1 && this.words[0] === 0;
11943 };
11944
11945 BN.prototype.cmpn = function cmpn (num) {
11946 var negative = num < 0;
11947
11948 if (this.negative !== 0 && !negative) return -1;
11949 if (this.negative === 0 && negative) return 1;
11950
11951 this._strip();
11952
11953 var res;
11954 if (this.length > 1) {
11955 res = 1;
11956 } else {
11957 if (negative) {
11958 num = -num;
11959 }
11960
11961 assert(num <= 0x3ffffff, 'Number is too big');
11962
11963 var w = this.words[0] | 0;
11964 res = w === num ? 0 : w < num ? -1 : 1;
11965 }
11966 if (this.negative !== 0) return -res | 0;
11967 return res;
11968 };
11969
11970 // Compare two numbers and return:
11971 // 1 - if `this` > `num`
11972 // 0 - if `this` == `num`
11973 // -1 - if `this` < `num`
11974 BN.prototype.cmp = function cmp (num) {
11975 if (this.negative !== 0 && num.negative === 0) return -1;
11976 if (this.negative === 0 && num.negative !== 0) return 1;
11977
11978 var res = this.ucmp(num);
11979 if (this.negative !== 0) return -res | 0;
11980 return res;
11981 };
11982
11983 // Unsigned comparison
11984 BN.prototype.ucmp = function ucmp (num) {
11985 // At this point both numbers have the same sign
11986 if (this.length > num.length) return 1;
11987 if (this.length < num.length) return -1;
11988
11989 var res = 0;
11990 for (var i = this.length - 1; i >= 0; i--) {
11991 var a = this.words[i] | 0;
11992 var b = num.words[i] | 0;
11993
11994 if (a === b) continue;
11995 if (a < b) {
11996 res = -1;
11997 } else if (a > b) {
11998 res = 1;
11999 }
12000 break;
12001 }
12002 return res;
12003 };
12004
12005 BN.prototype.gtn = function gtn (num) {
12006 return this.cmpn(num) === 1;
12007 };
12008
12009 BN.prototype.gt = function gt (num) {
12010 return this.cmp(num) === 1;
12011 };
12012
12013 BN.prototype.gten = function gten (num) {
12014 return this.cmpn(num) >= 0;
12015 };
12016
12017 BN.prototype.gte = function gte (num) {
12018 return this.cmp(num) >= 0;
12019 };
12020
12021 BN.prototype.ltn = function ltn (num) {
12022 return this.cmpn(num) === -1;
12023 };
12024
12025 BN.prototype.lt = function lt (num) {
12026 return this.cmp(num) === -1;
12027 };
12028
12029 BN.prototype.lten = function lten (num) {
12030 return this.cmpn(num) <= 0;
12031 };
12032
12033 BN.prototype.lte = function lte (num) {
12034 return this.cmp(num) <= 0;
12035 };
12036
12037 BN.prototype.eqn = function eqn (num) {
12038 return this.cmpn(num) === 0;
12039 };
12040
12041 BN.prototype.eq = function eq (num) {
12042 return this.cmp(num) === 0;
12043 };
12044
12045 //
12046 // A reduce context, could be using montgomery or something better, depending
12047 // on the `m` itself.
12048 //
12049 BN.red = function red (num) {
12050 return new Red(num);
12051 };
12052
12053 BN.prototype.toRed = function toRed (ctx) {
12054 assert(!this.red, 'Already a number in reduction context');
12055 assert(this.negative === 0, 'red works only with positives');
12056 return ctx.convertTo(this)._forceRed(ctx);
12057 };
12058
12059 BN.prototype.fromRed = function fromRed () {
12060 assert(this.red, 'fromRed works only with numbers in reduction context');
12061 return this.red.convertFrom(this);
12062 };
12063
12064 BN.prototype._forceRed = function _forceRed (ctx) {
12065 this.red = ctx;
12066 return this;
12067 };
12068
12069 BN.prototype.forceRed = function forceRed (ctx) {
12070 assert(!this.red, 'Already a number in reduction context');
12071 return this._forceRed(ctx);
12072 };
12073
12074 BN.prototype.redAdd = function redAdd (num) {
12075 assert(this.red, 'redAdd works only with red numbers');
12076 return this.red.add(this, num);
12077 };
12078
12079 BN.prototype.redIAdd = function redIAdd (num) {
12080 assert(this.red, 'redIAdd works only with red numbers');
12081 return this.red.iadd(this, num);
12082 };
12083
12084 BN.prototype.redSub = function redSub (num) {
12085 assert(this.red, 'redSub works only with red numbers');
12086 return this.red.sub(this, num);
12087 };
12088
12089 BN.prototype.redISub = function redISub (num) {
12090 assert(this.red, 'redISub works only with red numbers');
12091 return this.red.isub(this, num);
12092 };
12093
12094 BN.prototype.redShl = function redShl (num) {
12095 assert(this.red, 'redShl works only with red numbers');
12096 return this.red.shl(this, num);
12097 };
12098
12099 BN.prototype.redMul = function redMul (num) {
12100 assert(this.red, 'redMul works only with red numbers');
12101 this.red._verify2(this, num);
12102 return this.red.mul(this, num);
12103 };
12104
12105 BN.prototype.redIMul = function redIMul (num) {
12106 assert(this.red, 'redMul works only with red numbers');
12107 this.red._verify2(this, num);
12108 return this.red.imul(this, num);
12109 };
12110
12111 BN.prototype.redSqr = function redSqr () {
12112 assert(this.red, 'redSqr works only with red numbers');
12113 this.red._verify1(this);
12114 return this.red.sqr(this);
12115 };
12116
12117 BN.prototype.redISqr = function redISqr () {
12118 assert(this.red, 'redISqr works only with red numbers');
12119 this.red._verify1(this);
12120 return this.red.isqr(this);
12121 };
12122
12123 // Square root over p
12124 BN.prototype.redSqrt = function redSqrt () {
12125 assert(this.red, 'redSqrt works only with red numbers');
12126 this.red._verify1(this);
12127 return this.red.sqrt(this);
12128 };
12129
12130 BN.prototype.redInvm = function redInvm () {
12131 assert(this.red, 'redInvm works only with red numbers');
12132 this.red._verify1(this);
12133 return this.red.invm(this);
12134 };
12135
12136 // Return negative clone of `this` % `red modulo`
12137 BN.prototype.redNeg = function redNeg () {
12138 assert(this.red, 'redNeg works only with red numbers');
12139 this.red._verify1(this);
12140 return this.red.neg(this);
12141 };
12142
12143 BN.prototype.redPow = function redPow (num) {
12144 assert(this.red && !num.red, 'redPow(normalNum)');
12145 this.red._verify1(this);
12146 return this.red.pow(this, num);
12147 };
12148
12149 // Prime numbers with efficient reduction
12150 var primes = {
12151 k256: null,
12152 p224: null,
12153 p192: null,
12154 p25519: null
12155 };
12156
12157 // Pseudo-Mersenne prime
12158 function MPrime (name, p) {
12159 // P = 2 ^ N - K
12160 this.name = name;
12161 this.p = new BN(p, 16);
12162 this.n = this.p.bitLength();
12163 this.k = new BN(1).iushln(this.n).isub(this.p);
12164
12165 this.tmp = this._tmp();
12166 }
12167
12168 MPrime.prototype._tmp = function _tmp () {
12169 var tmp = new BN(null);
12170 tmp.words = new Array(Math.ceil(this.n / 13));
12171 return tmp;
12172 };
12173
12174 MPrime.prototype.ireduce = function ireduce (num) {
12175 // Assumes that `num` is less than `P^2`
12176 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
12177 var r = num;
12178 var rlen;
12179
12180 do {
12181 this.split(r, this.tmp);
12182 r = this.imulK(r);
12183 r = r.iadd(this.tmp);
12184 rlen = r.bitLength();
12185 } while (rlen > this.n);
12186
12187 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
12188 if (cmp === 0) {
12189 r.words[0] = 0;
12190 r.length = 1;
12191 } else if (cmp > 0) {
12192 r.isub(this.p);
12193 } else {
12194 if (r.strip !== undefined) {
12195 // r is a BN v4 instance
12196 r.strip();
12197 } else {
12198 // r is a BN v5 instance
12199 r._strip();
12200 }
12201 }
12202
12203 return r;
12204 };
12205
12206 MPrime.prototype.split = function split (input, out) {
12207 input.iushrn(this.n, 0, out);
12208 };
12209
12210 MPrime.prototype.imulK = function imulK (num) {
12211 return num.imul(this.k);
12212 };
12213
12214 function K256 () {
12215 MPrime.call(
12216 this,
12217 'k256',
12218 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
12219 }
12220 inherits(K256, MPrime);
12221
12222 K256.prototype.split = function split (input, output) {
12223 // 256 = 9 * 26 + 22
12224 var mask = 0x3fffff;
12225
12226 var outLen = Math.min(input.length, 9);
12227 for (var i = 0; i < outLen; i++) {
12228 output.words[i] = input.words[i];
12229 }
12230 output.length = outLen;
12231
12232 if (input.length <= 9) {
12233 input.words[0] = 0;
12234 input.length = 1;
12235 return;
12236 }
12237
12238 // Shift by 9 limbs
12239 var prev = input.words[9];
12240 output.words[output.length++] = prev & mask;
12241
12242 for (i = 10; i < input.length; i++) {
12243 var next = input.words[i] | 0;
12244 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
12245 prev = next;
12246 }
12247 prev >>>= 22;
12248 input.words[i - 10] = prev;
12249 if (prev === 0 && input.length > 10) {
12250 input.length -= 10;
12251 } else {
12252 input.length -= 9;
12253 }
12254 };
12255
12256 K256.prototype.imulK = function imulK (num) {
12257 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
12258 num.words[num.length] = 0;
12259 num.words[num.length + 1] = 0;
12260 num.length += 2;
12261
12262 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
12263 var lo = 0;
12264 for (var i = 0; i < num.length; i++) {
12265 var w = num.words[i] | 0;
12266 lo += w * 0x3d1;
12267 num.words[i] = lo & 0x3ffffff;
12268 lo = w * 0x40 + ((lo / 0x4000000) | 0);
12269 }
12270
12271 // Fast length reduction
12272 if (num.words[num.length - 1] === 0) {
12273 num.length--;
12274 if (num.words[num.length - 1] === 0) {
12275 num.length--;
12276 }
12277 }
12278 return num;
12279 };
12280
12281 function P224 () {
12282 MPrime.call(
12283 this,
12284 'p224',
12285 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
12286 }
12287 inherits(P224, MPrime);
12288
12289 function P192 () {
12290 MPrime.call(
12291 this,
12292 'p192',
12293 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
12294 }
12295 inherits(P192, MPrime);
12296
12297 function P25519 () {
12298 // 2 ^ 255 - 19
12299 MPrime.call(
12300 this,
12301 '25519',
12302 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
12303 }
12304 inherits(P25519, MPrime);
12305
12306 P25519.prototype.imulK = function imulK (num) {
12307 // K = 0x13
12308 var carry = 0;
12309 for (var i = 0; i < num.length; i++) {
12310 var hi = (num.words[i] | 0) * 0x13 + carry;
12311 var lo = hi & 0x3ffffff;
12312 hi >>>= 26;
12313
12314 num.words[i] = lo;
12315 carry = hi;
12316 }
12317 if (carry !== 0) {
12318 num.words[num.length++] = carry;
12319 }
12320 return num;
12321 };
12322
12323 // Exported mostly for testing purposes, use plain name instead
12324 BN._prime = function prime (name) {
12325 // Cached version of prime
12326 if (primes[name]) return primes[name];
12327
12328 var prime;
12329 if (name === 'k256') {
12330 prime = new K256();
12331 } else if (name === 'p224') {
12332 prime = new P224();
12333 } else if (name === 'p192') {
12334 prime = new P192();
12335 } else if (name === 'p25519') {
12336 prime = new P25519();
12337 } else {
12338 throw new Error('Unknown prime ' + name);
12339 }
12340 primes[name] = prime;
12341
12342 return prime;
12343 };
12344
12345 //
12346 // Base reduction engine
12347 //
12348 function Red (m) {
12349 if (typeof m === 'string') {
12350 var prime = BN._prime(m);
12351 this.m = prime.p;
12352 this.prime = prime;
12353 } else {
12354 assert(m.gtn(1), 'modulus must be greater than 1');
12355 this.m = m;
12356 this.prime = null;
12357 }
12358 }
12359
12360 Red.prototype._verify1 = function _verify1 (a) {
12361 assert(a.negative === 0, 'red works only with positives');
12362 assert(a.red, 'red works only with red numbers');
12363 };
12364
12365 Red.prototype._verify2 = function _verify2 (a, b) {
12366 assert((a.negative | b.negative) === 0, 'red works only with positives');
12367 assert(a.red && a.red === b.red,
12368 'red works only with red numbers');
12369 };
12370
12371 Red.prototype.imod = function imod (a) {
12372 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
12373
12374 move(a, a.umod(this.m)._forceRed(this));
12375 return a;
12376 };
12377
12378 Red.prototype.neg = function neg (a) {
12379 if (a.isZero()) {
12380 return a.clone();
12381 }
12382
12383 return this.m.sub(a)._forceRed(this);
12384 };
12385
12386 Red.prototype.add = function add (a, b) {
12387 this._verify2(a, b);
12388
12389 var res = a.add(b);
12390 if (res.cmp(this.m) >= 0) {
12391 res.isub(this.m);
12392 }
12393 return res._forceRed(this);
12394 };
12395
12396 Red.prototype.iadd = function iadd (a, b) {
12397 this._verify2(a, b);
12398
12399 var res = a.iadd(b);
12400 if (res.cmp(this.m) >= 0) {
12401 res.isub(this.m);
12402 }
12403 return res;
12404 };
12405
12406 Red.prototype.sub = function sub (a, b) {
12407 this._verify2(a, b);
12408
12409 var res = a.sub(b);
12410 if (res.cmpn(0) < 0) {
12411 res.iadd(this.m);
12412 }
12413 return res._forceRed(this);
12414 };
12415
12416 Red.prototype.isub = function isub (a, b) {
12417 this._verify2(a, b);
12418
12419 var res = a.isub(b);
12420 if (res.cmpn(0) < 0) {
12421 res.iadd(this.m);
12422 }
12423 return res;
12424 };
12425
12426 Red.prototype.shl = function shl (a, num) {
12427 this._verify1(a);
12428 return this.imod(a.ushln(num));
12429 };
12430
12431 Red.prototype.imul = function imul (a, b) {
12432 this._verify2(a, b);
12433 return this.imod(a.imul(b));
12434 };
12435
12436 Red.prototype.mul = function mul (a, b) {
12437 this._verify2(a, b);
12438 return this.imod(a.mul(b));
12439 };
12440
12441 Red.prototype.isqr = function isqr (a) {
12442 return this.imul(a, a.clone());
12443 };
12444
12445 Red.prototype.sqr = function sqr (a) {
12446 return this.mul(a, a);
12447 };
12448
12449 Red.prototype.sqrt = function sqrt (a) {
12450 if (a.isZero()) return a.clone();
12451
12452 var mod3 = this.m.andln(3);
12453 assert(mod3 % 2 === 1);
12454
12455 // Fast case
12456 if (mod3 === 3) {
12457 var pow = this.m.add(new BN(1)).iushrn(2);
12458 return this.pow(a, pow);
12459 }
12460
12461 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
12462 //
12463 // Find Q and S, that Q * 2 ^ S = (P - 1)
12464 var q = this.m.subn(1);
12465 var s = 0;
12466 while (!q.isZero() && q.andln(1) === 0) {
12467 s++;
12468 q.iushrn(1);
12469 }
12470 assert(!q.isZero());
12471
12472 var one = new BN(1).toRed(this);
12473 var nOne = one.redNeg();
12474
12475 // Find quadratic non-residue
12476 // NOTE: Max is such because of generalized Riemann hypothesis.
12477 var lpow = this.m.subn(1).iushrn(1);
12478 var z = this.m.bitLength();
12479 z = new BN(2 * z * z).toRed(this);
12480
12481 while (this.pow(z, lpow).cmp(nOne) !== 0) {
12482 z.redIAdd(nOne);
12483 }
12484
12485 var c = this.pow(z, q);
12486 var r = this.pow(a, q.addn(1).iushrn(1));
12487 var t = this.pow(a, q);
12488 var m = s;
12489 while (t.cmp(one) !== 0) {
12490 var tmp = t;
12491 for (var i = 0; tmp.cmp(one) !== 0; i++) {
12492 tmp = tmp.redSqr();
12493 }
12494 assert(i < m);
12495 var b = this.pow(c, new BN(1).iushln(m - i - 1));
12496
12497 r = r.redMul(b);
12498 c = b.redSqr();
12499 t = t.redMul(c);
12500 m = i;
12501 }
12502
12503 return r;
12504 };
12505
12506 Red.prototype.invm = function invm (a) {
12507 var inv = a._invmp(this.m);
12508 if (inv.negative !== 0) {
12509 inv.negative = 0;
12510 return this.imod(inv).redNeg();
12511 } else {
12512 return this.imod(inv);
12513 }
12514 };
12515
12516 Red.prototype.pow = function pow (a, num) {
12517 if (num.isZero()) return new BN(1).toRed(this);
12518 if (num.cmpn(1) === 0) return a.clone();
12519
12520 var windowSize = 4;
12521 var wnd = new Array(1 << windowSize);
12522 wnd[0] = new BN(1).toRed(this);
12523 wnd[1] = a;
12524 for (var i = 2; i < wnd.length; i++) {
12525 wnd[i] = this.mul(wnd[i - 1], a);
12526 }
12527
12528 var res = wnd[0];
12529 var current = 0;
12530 var currentLen = 0;
12531 var start = num.bitLength() % 26;
12532 if (start === 0) {
12533 start = 26;
12534 }
12535
12536 for (i = num.length - 1; i >= 0; i--) {
12537 var word = num.words[i];
12538 for (var j = start - 1; j >= 0; j--) {
12539 var bit = (word >> j) & 1;
12540 if (res !== wnd[0]) {
12541 res = this.sqr(res);
12542 }
12543
12544 if (bit === 0 && current === 0) {
12545 currentLen = 0;
12546 continue;
12547 }
12548
12549 current <<= 1;
12550 current |= bit;
12551 currentLen++;
12552 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
12553
12554 res = this.mul(res, wnd[current]);
12555 currentLen = 0;
12556 current = 0;
12557 }
12558 start = 26;
12559 }
12560
12561 return res;
12562 };
12563
12564 Red.prototype.convertTo = function convertTo (num) {
12565 var r = num.umod(this.m);
12566
12567 return r === num ? r.clone() : r;
12568 };
12569
12570 Red.prototype.convertFrom = function convertFrom (num) {
12571 var res = num.clone();
12572 res.red = null;
12573 return res;
12574 };
12575
12576 //
12577 // Montgomery method engine
12578 //
12579
12580 BN.mont = function mont (num) {
12581 return new Mont(num);
12582 };
12583
12584 function Mont (m) {
12585 Red.call(this, m);
12586
12587 this.shift = this.m.bitLength();
12588 if (this.shift % 26 !== 0) {
12589 this.shift += 26 - (this.shift % 26);
12590 }
12591
12592 this.r = new BN(1).iushln(this.shift);
12593 this.r2 = this.imod(this.r.sqr());
12594 this.rinv = this.r._invmp(this.m);
12595
12596 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
12597 this.minv = this.minv.umod(this.r);
12598 this.minv = this.r.sub(this.minv);
12599 }
12600 inherits(Mont, Red);
12601
12602 Mont.prototype.convertTo = function convertTo (num) {
12603 return this.imod(num.ushln(this.shift));
12604 };
12605
12606 Mont.prototype.convertFrom = function convertFrom (num) {
12607 var r = this.imod(num.mul(this.rinv));
12608 r.red = null;
12609 return r;
12610 };
12611
12612 Mont.prototype.imul = function imul (a, b) {
12613 if (a.isZero() || b.isZero()) {
12614 a.words[0] = 0;
12615 a.length = 1;
12616 return a;
12617 }
12618
12619 var t = a.imul(b);
12620 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
12621 var u = t.isub(c).iushrn(this.shift);
12622 var res = u;
12623
12624 if (u.cmp(this.m) >= 0) {
12625 res = u.isub(this.m);
12626 } else if (u.cmpn(0) < 0) {
12627 res = u.iadd(this.m);
12628 }
12629
12630 return res._forceRed(this);
12631 };
12632
12633 Mont.prototype.mul = function mul (a, b) {
12634 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
12635
12636 var t = a.mul(b);
12637 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
12638 var u = t.isub(c).iushrn(this.shift);
12639 var res = u;
12640 if (u.cmp(this.m) >= 0) {
12641 res = u.isub(this.m);
12642 } else if (u.cmpn(0) < 0) {
12643 res = u.iadd(this.m);
12644 }
12645
12646 return res._forceRed(this);
12647 };
12648
12649 Mont.prototype.invm = function invm (a) {
12650 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
12651 var res = this.imod(a._invmp(this.m).mul(this.r2));
12652 return res._forceRed(this);
12653 };
12654})(typeof module === 'undefined' || module, this);
12655
12656},{"buffer":33}],32:[function(require,module,exports){
12657var r;
12658
12659module.exports = function rand(len) {
12660 if (!r)
12661 r = new Rand(null);
12662
12663 return r.generate(len);
12664};
12665
12666function Rand(rand) {
12667 this.rand = rand;
12668}
12669module.exports.Rand = Rand;
12670
12671Rand.prototype.generate = function generate(len) {
12672 return this._rand(len);
12673};
12674
12675// Emulate crypto API using randy
12676Rand.prototype._rand = function _rand(n) {
12677 if (this.rand.getBytes)
12678 return this.rand.getBytes(n);
12679
12680 var res = new Uint8Array(n);
12681 for (var i = 0; i < res.length; i++)
12682 res[i] = this.rand.getByte();
12683 return res;
12684};
12685
12686if (typeof self === 'object') {
12687 if (self.crypto && self.crypto.getRandomValues) {
12688 // Modern browsers
12689 Rand.prototype._rand = function _rand(n) {
12690 var arr = new Uint8Array(n);
12691 self.crypto.getRandomValues(arr);
12692 return arr;
12693 };
12694 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
12695 // IE
12696 Rand.prototype._rand = function _rand(n) {
12697 var arr = new Uint8Array(n);
12698 self.msCrypto.getRandomValues(arr);
12699 return arr;
12700 };
12701
12702 // Safari's WebWorkers do not have `crypto`
12703 } else if (typeof window === 'object') {
12704 // Old junk
12705 Rand.prototype._rand = function() {
12706 throw new Error('Not implemented yet');
12707 };
12708 }
12709} else {
12710 // Node.js or Web worker with no crypto support
12711 try {
12712 var crypto = require('crypto');
12713 if (typeof crypto.randomBytes !== 'function')
12714 throw new Error('Not supported');
12715
12716 Rand.prototype._rand = function _rand(n) {
12717 return crypto.randomBytes(n);
12718 };
12719 } catch (e) {
12720 }
12721}
12722
12723},{"crypto":33}],33:[function(require,module,exports){
12724
12725},{}],34:[function(require,module,exports){
12726// based on the aes implimentation in triple sec
12727// https://github.com/keybase/triplesec
12728// which is in turn based on the one from crypto-js
12729// https://code.google.com/p/crypto-js/
12730
12731var Buffer = require('safe-buffer').Buffer
12732
12733function asUInt32Array (buf) {
12734 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
12735
12736 var len = (buf.length / 4) | 0
12737 var out = new Array(len)
12738
12739 for (var i = 0; i < len; i++) {
12740 out[i] = buf.readUInt32BE(i * 4)
12741 }
12742
12743 return out
12744}
12745
12746function scrubVec (v) {
12747 for (var i = 0; i < v.length; v++) {
12748 v[i] = 0
12749 }
12750}
12751
12752function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
12753 var SUB_MIX0 = SUB_MIX[0]
12754 var SUB_MIX1 = SUB_MIX[1]
12755 var SUB_MIX2 = SUB_MIX[2]
12756 var SUB_MIX3 = SUB_MIX[3]
12757
12758 var s0 = M[0] ^ keySchedule[0]
12759 var s1 = M[1] ^ keySchedule[1]
12760 var s2 = M[2] ^ keySchedule[2]
12761 var s3 = M[3] ^ keySchedule[3]
12762 var t0, t1, t2, t3
12763 var ksRow = 4
12764
12765 for (var round = 1; round < nRounds; round++) {
12766 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
12767 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
12768 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
12769 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
12770 s0 = t0
12771 s1 = t1
12772 s2 = t2
12773 s3 = t3
12774 }
12775
12776 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
12777 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
12778 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
12779 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
12780 t0 = t0 >>> 0
12781 t1 = t1 >>> 0
12782 t2 = t2 >>> 0
12783 t3 = t3 >>> 0
12784
12785 return [t0, t1, t2, t3]
12786}
12787
12788// AES constants
12789var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
12790var G = (function () {
12791 // Compute double table
12792 var d = new Array(256)
12793 for (var j = 0; j < 256; j++) {
12794 if (j < 128) {
12795 d[j] = j << 1
12796 } else {
12797 d[j] = (j << 1) ^ 0x11b
12798 }
12799 }
12800
12801 var SBOX = []
12802 var INV_SBOX = []
12803 var SUB_MIX = [[], [], [], []]
12804 var INV_SUB_MIX = [[], [], [], []]
12805
12806 // Walk GF(2^8)
12807 var x = 0
12808 var xi = 0
12809 for (var i = 0; i < 256; ++i) {
12810 // Compute sbox
12811 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
12812 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
12813 SBOX[x] = sx
12814 INV_SBOX[sx] = x
12815
12816 // Compute multiplication
12817 var x2 = d[x]
12818 var x4 = d[x2]
12819 var x8 = d[x4]
12820
12821 // Compute sub bytes, mix columns tables
12822 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
12823 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
12824 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
12825 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
12826 SUB_MIX[3][x] = t
12827
12828 // Compute inv sub bytes, inv mix columns tables
12829 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
12830 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
12831 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
12832 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
12833 INV_SUB_MIX[3][sx] = t
12834
12835 if (x === 0) {
12836 x = xi = 1
12837 } else {
12838 x = x2 ^ d[d[d[x8 ^ x2]]]
12839 xi ^= d[d[xi]]
12840 }
12841 }
12842
12843 return {
12844 SBOX: SBOX,
12845 INV_SBOX: INV_SBOX,
12846 SUB_MIX: SUB_MIX,
12847 INV_SUB_MIX: INV_SUB_MIX
12848 }
12849})()
12850
12851function AES (key) {
12852 this._key = asUInt32Array(key)
12853 this._reset()
12854}
12855
12856AES.blockSize = 4 * 4
12857AES.keySize = 256 / 8
12858AES.prototype.blockSize = AES.blockSize
12859AES.prototype.keySize = AES.keySize
12860AES.prototype._reset = function () {
12861 var keyWords = this._key
12862 var keySize = keyWords.length
12863 var nRounds = keySize + 6
12864 var ksRows = (nRounds + 1) * 4
12865
12866 var keySchedule = []
12867 for (var k = 0; k < keySize; k++) {
12868 keySchedule[k] = keyWords[k]
12869 }
12870
12871 for (k = keySize; k < ksRows; k++) {
12872 var t = keySchedule[k - 1]
12873
12874 if (k % keySize === 0) {
12875 t = (t << 8) | (t >>> 24)
12876 t =
12877 (G.SBOX[t >>> 24] << 24) |
12878 (G.SBOX[(t >>> 16) & 0xff] << 16) |
12879 (G.SBOX[(t >>> 8) & 0xff] << 8) |
12880 (G.SBOX[t & 0xff])
12881
12882 t ^= RCON[(k / keySize) | 0] << 24
12883 } else if (keySize > 6 && k % keySize === 4) {
12884 t =
12885 (G.SBOX[t >>> 24] << 24) |
12886 (G.SBOX[(t >>> 16) & 0xff] << 16) |
12887 (G.SBOX[(t >>> 8) & 0xff] << 8) |
12888 (G.SBOX[t & 0xff])
12889 }
12890
12891 keySchedule[k] = keySchedule[k - keySize] ^ t
12892 }
12893
12894 var invKeySchedule = []
12895 for (var ik = 0; ik < ksRows; ik++) {
12896 var ksR = ksRows - ik
12897 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
12898
12899 if (ik < 4 || ksR <= 4) {
12900 invKeySchedule[ik] = tt
12901 } else {
12902 invKeySchedule[ik] =
12903 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
12904 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
12905 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
12906 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
12907 }
12908 }
12909
12910 this._nRounds = nRounds
12911 this._keySchedule = keySchedule
12912 this._invKeySchedule = invKeySchedule
12913}
12914
12915AES.prototype.encryptBlockRaw = function (M) {
12916 M = asUInt32Array(M)
12917 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
12918}
12919
12920AES.prototype.encryptBlock = function (M) {
12921 var out = this.encryptBlockRaw(M)
12922 var buf = Buffer.allocUnsafe(16)
12923 buf.writeUInt32BE(out[0], 0)
12924 buf.writeUInt32BE(out[1], 4)
12925 buf.writeUInt32BE(out[2], 8)
12926 buf.writeUInt32BE(out[3], 12)
12927 return buf
12928}
12929
12930AES.prototype.decryptBlock = function (M) {
12931 M = asUInt32Array(M)
12932
12933 // swap
12934 var m1 = M[1]
12935 M[1] = M[3]
12936 M[3] = m1
12937
12938 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
12939 var buf = Buffer.allocUnsafe(16)
12940 buf.writeUInt32BE(out[0], 0)
12941 buf.writeUInt32BE(out[3], 4)
12942 buf.writeUInt32BE(out[2], 8)
12943 buf.writeUInt32BE(out[1], 12)
12944 return buf
12945}
12946
12947AES.prototype.scrub = function () {
12948 scrubVec(this._keySchedule)
12949 scrubVec(this._invKeySchedule)
12950 scrubVec(this._key)
12951}
12952
12953module.exports.AES = AES
12954
12955},{"safe-buffer":200}],35:[function(require,module,exports){
12956var aes = require('./aes')
12957var Buffer = require('safe-buffer').Buffer
12958var Transform = require('cipher-base')
12959var inherits = require('inherits')
12960var GHASH = require('./ghash')
12961var xor = require('buffer-xor')
12962var incr32 = require('./incr32')
12963
12964function xorTest (a, b) {
12965 var out = 0
12966 if (a.length !== b.length) out++
12967
12968 var len = Math.min(a.length, b.length)
12969 for (var i = 0; i < len; ++i) {
12970 out += (a[i] ^ b[i])
12971 }
12972
12973 return out
12974}
12975
12976function calcIv (self, iv, ck) {
12977 if (iv.length === 12) {
12978 self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
12979 return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
12980 }
12981 var ghash = new GHASH(ck)
12982 var len = iv.length
12983 var toPad = len % 16
12984 ghash.update(iv)
12985 if (toPad) {
12986 toPad = 16 - toPad
12987 ghash.update(Buffer.alloc(toPad, 0))
12988 }
12989 ghash.update(Buffer.alloc(8, 0))
12990 var ivBits = len * 8
12991 var tail = Buffer.alloc(8)
12992 tail.writeUIntBE(ivBits, 0, 8)
12993 ghash.update(tail)
12994 self._finID = ghash.state
12995 var out = Buffer.from(self._finID)
12996 incr32(out)
12997 return out
12998}
12999function StreamCipher (mode, key, iv, decrypt) {
13000 Transform.call(this)
13001
13002 var h = Buffer.alloc(4, 0)
13003
13004 this._cipher = new aes.AES(key)
13005 var ck = this._cipher.encryptBlock(h)
13006 this._ghash = new GHASH(ck)
13007 iv = calcIv(this, iv, ck)
13008
13009 this._prev = Buffer.from(iv)
13010 this._cache = Buffer.allocUnsafe(0)
13011 this._secCache = Buffer.allocUnsafe(0)
13012 this._decrypt = decrypt
13013 this._alen = 0
13014 this._len = 0
13015 this._mode = mode
13016
13017 this._authTag = null
13018 this._called = false
13019}
13020
13021inherits(StreamCipher, Transform)
13022
13023StreamCipher.prototype._update = function (chunk) {
13024 if (!this._called && this._alen) {
13025 var rump = 16 - (this._alen % 16)
13026 if (rump < 16) {
13027 rump = Buffer.alloc(rump, 0)
13028 this._ghash.update(rump)
13029 }
13030 }
13031
13032 this._called = true
13033 var out = this._mode.encrypt(this, chunk)
13034 if (this._decrypt) {
13035 this._ghash.update(chunk)
13036 } else {
13037 this._ghash.update(out)
13038 }
13039 this._len += chunk.length
13040 return out
13041}
13042
13043StreamCipher.prototype._final = function () {
13044 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
13045
13046 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
13047 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
13048
13049 this._authTag = tag
13050 this._cipher.scrub()
13051}
13052
13053StreamCipher.prototype.getAuthTag = function getAuthTag () {
13054 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
13055
13056 return this._authTag
13057}
13058
13059StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
13060 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
13061
13062 this._authTag = tag
13063}
13064
13065StreamCipher.prototype.setAAD = function setAAD (buf) {
13066 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
13067
13068 this._ghash.update(buf)
13069 this._alen += buf.length
13070}
13071
13072module.exports = StreamCipher
13073
13074},{"./aes":34,"./ghash":39,"./incr32":40,"buffer-xor":76,"cipher-base":78,"inherits":152,"safe-buffer":200}],36:[function(require,module,exports){
13075var ciphers = require('./encrypter')
13076var deciphers = require('./decrypter')
13077var modes = require('./modes/list.json')
13078
13079function getCiphers () {
13080 return Object.keys(modes)
13081}
13082
13083exports.createCipher = exports.Cipher = ciphers.createCipher
13084exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
13085exports.createDecipher = exports.Decipher = deciphers.createDecipher
13086exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
13087exports.listCiphers = exports.getCiphers = getCiphers
13088
13089},{"./decrypter":37,"./encrypter":38,"./modes/list.json":48}],37:[function(require,module,exports){
13090var AuthCipher = require('./authCipher')
13091var Buffer = require('safe-buffer').Buffer
13092var MODES = require('./modes')
13093var StreamCipher = require('./streamCipher')
13094var Transform = require('cipher-base')
13095var aes = require('./aes')
13096var ebtk = require('evp_bytestokey')
13097var inherits = require('inherits')
13098
13099function Decipher (mode, key, iv) {
13100 Transform.call(this)
13101
13102 this._cache = new Splitter()
13103 this._last = void 0
13104 this._cipher = new aes.AES(key)
13105 this._prev = Buffer.from(iv)
13106 this._mode = mode
13107 this._autopadding = true
13108}
13109
13110inherits(Decipher, Transform)
13111
13112Decipher.prototype._update = function (data) {
13113 this._cache.add(data)
13114 var chunk
13115 var thing
13116 var out = []
13117 while ((chunk = this._cache.get(this._autopadding))) {
13118 thing = this._mode.decrypt(this, chunk)
13119 out.push(thing)
13120 }
13121 return Buffer.concat(out)
13122}
13123
13124Decipher.prototype._final = function () {
13125 var chunk = this._cache.flush()
13126 if (this._autopadding) {
13127 return unpad(this._mode.decrypt(this, chunk))
13128 } else if (chunk) {
13129 throw new Error('data not multiple of block length')
13130 }
13131}
13132
13133Decipher.prototype.setAutoPadding = function (setTo) {
13134 this._autopadding = !!setTo
13135 return this
13136}
13137
13138function Splitter () {
13139 this.cache = Buffer.allocUnsafe(0)
13140}
13141
13142Splitter.prototype.add = function (data) {
13143 this.cache = Buffer.concat([this.cache, data])
13144}
13145
13146Splitter.prototype.get = function (autoPadding) {
13147 var out
13148 if (autoPadding) {
13149 if (this.cache.length > 16) {
13150 out = this.cache.slice(0, 16)
13151 this.cache = this.cache.slice(16)
13152 return out
13153 }
13154 } else {
13155 if (this.cache.length >= 16) {
13156 out = this.cache.slice(0, 16)
13157 this.cache = this.cache.slice(16)
13158 return out
13159 }
13160 }
13161
13162 return null
13163}
13164
13165Splitter.prototype.flush = function () {
13166 if (this.cache.length) return this.cache
13167}
13168
13169function unpad (last) {
13170 var padded = last[15]
13171 if (padded < 1 || padded > 16) {
13172 throw new Error('unable to decrypt data')
13173 }
13174 var i = -1
13175 while (++i < padded) {
13176 if (last[(i + (16 - padded))] !== padded) {
13177 throw new Error('unable to decrypt data')
13178 }
13179 }
13180 if (padded === 16) return
13181
13182 return last.slice(0, 16 - padded)
13183}
13184
13185function createDecipheriv (suite, password, iv) {
13186 var config = MODES[suite.toLowerCase()]
13187 if (!config) throw new TypeError('invalid suite type')
13188
13189 if (typeof iv === 'string') iv = Buffer.from(iv)
13190 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
13191
13192 if (typeof password === 'string') password = Buffer.from(password)
13193 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
13194
13195 if (config.type === 'stream') {
13196 return new StreamCipher(config.module, password, iv, true)
13197 } else if (config.type === 'auth') {
13198 return new AuthCipher(config.module, password, iv, true)
13199 }
13200
13201 return new Decipher(config.module, password, iv)
13202}
13203
13204function createDecipher (suite, password) {
13205 var config = MODES[suite.toLowerCase()]
13206 if (!config) throw new TypeError('invalid suite type')
13207
13208 var keys = ebtk(password, false, config.key, config.iv)
13209 return createDecipheriv(suite, keys.key, keys.iv)
13210}
13211
13212exports.createDecipher = createDecipher
13213exports.createDecipheriv = createDecipheriv
13214
13215},{"./aes":34,"./authCipher":35,"./modes":47,"./streamCipher":50,"cipher-base":78,"evp_bytestokey":121,"inherits":152,"safe-buffer":200}],38:[function(require,module,exports){
13216var MODES = require('./modes')
13217var AuthCipher = require('./authCipher')
13218var Buffer = require('safe-buffer').Buffer
13219var StreamCipher = require('./streamCipher')
13220var Transform = require('cipher-base')
13221var aes = require('./aes')
13222var ebtk = require('evp_bytestokey')
13223var inherits = require('inherits')
13224
13225function Cipher (mode, key, iv) {
13226 Transform.call(this)
13227
13228 this._cache = new Splitter()
13229 this._cipher = new aes.AES(key)
13230 this._prev = Buffer.from(iv)
13231 this._mode = mode
13232 this._autopadding = true
13233}
13234
13235inherits(Cipher, Transform)
13236
13237Cipher.prototype._update = function (data) {
13238 this._cache.add(data)
13239 var chunk
13240 var thing
13241 var out = []
13242
13243 while ((chunk = this._cache.get())) {
13244 thing = this._mode.encrypt(this, chunk)
13245 out.push(thing)
13246 }
13247
13248 return Buffer.concat(out)
13249}
13250
13251var PADDING = Buffer.alloc(16, 0x10)
13252
13253Cipher.prototype._final = function () {
13254 var chunk = this._cache.flush()
13255 if (this._autopadding) {
13256 chunk = this._mode.encrypt(this, chunk)
13257 this._cipher.scrub()
13258 return chunk
13259 }
13260
13261 if (!chunk.equals(PADDING)) {
13262 this._cipher.scrub()
13263 throw new Error('data not multiple of block length')
13264 }
13265}
13266
13267Cipher.prototype.setAutoPadding = function (setTo) {
13268 this._autopadding = !!setTo
13269 return this
13270}
13271
13272function Splitter () {
13273 this.cache = Buffer.allocUnsafe(0)
13274}
13275
13276Splitter.prototype.add = function (data) {
13277 this.cache = Buffer.concat([this.cache, data])
13278}
13279
13280Splitter.prototype.get = function () {
13281 if (this.cache.length > 15) {
13282 var out = this.cache.slice(0, 16)
13283 this.cache = this.cache.slice(16)
13284 return out
13285 }
13286 return null
13287}
13288
13289Splitter.prototype.flush = function () {
13290 var len = 16 - this.cache.length
13291 var padBuff = Buffer.allocUnsafe(len)
13292
13293 var i = -1
13294 while (++i < len) {
13295 padBuff.writeUInt8(len, i)
13296 }
13297
13298 return Buffer.concat([this.cache, padBuff])
13299}
13300
13301function createCipheriv (suite, password, iv) {
13302 var config = MODES[suite.toLowerCase()]
13303 if (!config) throw new TypeError('invalid suite type')
13304
13305 if (typeof password === 'string') password = Buffer.from(password)
13306 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
13307
13308 if (typeof iv === 'string') iv = Buffer.from(iv)
13309 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
13310
13311 if (config.type === 'stream') {
13312 return new StreamCipher(config.module, password, iv)
13313 } else if (config.type === 'auth') {
13314 return new AuthCipher(config.module, password, iv)
13315 }
13316
13317 return new Cipher(config.module, password, iv)
13318}
13319
13320function createCipher (suite, password) {
13321 var config = MODES[suite.toLowerCase()]
13322 if (!config) throw new TypeError('invalid suite type')
13323
13324 var keys = ebtk(password, false, config.key, config.iv)
13325 return createCipheriv(suite, keys.key, keys.iv)
13326}
13327
13328exports.createCipheriv = createCipheriv
13329exports.createCipher = createCipher
13330
13331},{"./aes":34,"./authCipher":35,"./modes":47,"./streamCipher":50,"cipher-base":78,"evp_bytestokey":121,"inherits":152,"safe-buffer":200}],39:[function(require,module,exports){
13332var Buffer = require('safe-buffer').Buffer
13333var ZEROES = Buffer.alloc(16, 0)
13334
13335function toArray (buf) {
13336 return [
13337 buf.readUInt32BE(0),
13338 buf.readUInt32BE(4),
13339 buf.readUInt32BE(8),
13340 buf.readUInt32BE(12)
13341 ]
13342}
13343
13344function fromArray (out) {
13345 var buf = Buffer.allocUnsafe(16)
13346 buf.writeUInt32BE(out[0] >>> 0, 0)
13347 buf.writeUInt32BE(out[1] >>> 0, 4)
13348 buf.writeUInt32BE(out[2] >>> 0, 8)
13349 buf.writeUInt32BE(out[3] >>> 0, 12)
13350 return buf
13351}
13352
13353function GHASH (key) {
13354 this.h = key
13355 this.state = Buffer.alloc(16, 0)
13356 this.cache = Buffer.allocUnsafe(0)
13357}
13358
13359// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
13360// by Juho Vähä-Herttua
13361GHASH.prototype.ghash = function (block) {
13362 var i = -1
13363 while (++i < block.length) {
13364 this.state[i] ^= block[i]
13365 }
13366 this._multiply()
13367}
13368
13369GHASH.prototype._multiply = function () {
13370 var Vi = toArray(this.h)
13371 var Zi = [0, 0, 0, 0]
13372 var j, xi, lsbVi
13373 var i = -1
13374 while (++i < 128) {
13375 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
13376 if (xi) {
13377 // Z_i+1 = Z_i ^ V_i
13378 Zi[0] ^= Vi[0]
13379 Zi[1] ^= Vi[1]
13380 Zi[2] ^= Vi[2]
13381 Zi[3] ^= Vi[3]
13382 }
13383
13384 // Store the value of LSB(V_i)
13385 lsbVi = (Vi[3] & 1) !== 0
13386
13387 // V_i+1 = V_i >> 1
13388 for (j = 3; j > 0; j--) {
13389 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
13390 }
13391 Vi[0] = Vi[0] >>> 1
13392
13393 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
13394 if (lsbVi) {
13395 Vi[0] = Vi[0] ^ (0xe1 << 24)
13396 }
13397 }
13398 this.state = fromArray(Zi)
13399}
13400
13401GHASH.prototype.update = function (buf) {
13402 this.cache = Buffer.concat([this.cache, buf])
13403 var chunk
13404 while (this.cache.length >= 16) {
13405 chunk = this.cache.slice(0, 16)
13406 this.cache = this.cache.slice(16)
13407 this.ghash(chunk)
13408 }
13409}
13410
13411GHASH.prototype.final = function (abl, bl) {
13412 if (this.cache.length) {
13413 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
13414 }
13415
13416 this.ghash(fromArray([0, abl, 0, bl]))
13417 return this.state
13418}
13419
13420module.exports = GHASH
13421
13422},{"safe-buffer":200}],40:[function(require,module,exports){
13423function incr32 (iv) {
13424 var len = iv.length
13425 var item
13426 while (len--) {
13427 item = iv.readUInt8(len)
13428 if (item === 255) {
13429 iv.writeUInt8(0, len)
13430 } else {
13431 item++
13432 iv.writeUInt8(item, len)
13433 break
13434 }
13435 }
13436}
13437module.exports = incr32
13438
13439},{}],41:[function(require,module,exports){
13440var xor = require('buffer-xor')
13441
13442exports.encrypt = function (self, block) {
13443 var data = xor(block, self._prev)
13444
13445 self._prev = self._cipher.encryptBlock(data)
13446 return self._prev
13447}
13448
13449exports.decrypt = function (self, block) {
13450 var pad = self._prev
13451
13452 self._prev = block
13453 var out = self._cipher.decryptBlock(block)
13454
13455 return xor(out, pad)
13456}
13457
13458},{"buffer-xor":76}],42:[function(require,module,exports){
13459var Buffer = require('safe-buffer').Buffer
13460var xor = require('buffer-xor')
13461
13462function encryptStart (self, data, decrypt) {
13463 var len = data.length
13464 var out = xor(data, self._cache)
13465 self._cache = self._cache.slice(len)
13466 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
13467 return out
13468}
13469
13470exports.encrypt = function (self, data, decrypt) {
13471 var out = Buffer.allocUnsafe(0)
13472 var len
13473
13474 while (data.length) {
13475 if (self._cache.length === 0) {
13476 self._cache = self._cipher.encryptBlock(self._prev)
13477 self._prev = Buffer.allocUnsafe(0)
13478 }
13479
13480 if (self._cache.length <= data.length) {
13481 len = self._cache.length
13482 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
13483 data = data.slice(len)
13484 } else {
13485 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
13486 break
13487 }
13488 }
13489
13490 return out
13491}
13492
13493},{"buffer-xor":76,"safe-buffer":200}],43:[function(require,module,exports){
13494var Buffer = require('safe-buffer').Buffer
13495
13496function encryptByte (self, byteParam, decrypt) {
13497 var pad
13498 var i = -1
13499 var len = 8
13500 var out = 0
13501 var bit, value
13502 while (++i < len) {
13503 pad = self._cipher.encryptBlock(self._prev)
13504 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
13505 value = pad[0] ^ bit
13506 out += ((value & 0x80) >> (i % 8))
13507 self._prev = shiftIn(self._prev, decrypt ? bit : value)
13508 }
13509 return out
13510}
13511
13512function shiftIn (buffer, value) {
13513 var len = buffer.length
13514 var i = -1
13515 var out = Buffer.allocUnsafe(buffer.length)
13516 buffer = Buffer.concat([buffer, Buffer.from([value])])
13517
13518 while (++i < len) {
13519 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
13520 }
13521
13522 return out
13523}
13524
13525exports.encrypt = function (self, chunk, decrypt) {
13526 var len = chunk.length
13527 var out = Buffer.allocUnsafe(len)
13528 var i = -1
13529
13530 while (++i < len) {
13531 out[i] = encryptByte(self, chunk[i], decrypt)
13532 }
13533
13534 return out
13535}
13536
13537},{"safe-buffer":200}],44:[function(require,module,exports){
13538var Buffer = require('safe-buffer').Buffer
13539
13540function encryptByte (self, byteParam, decrypt) {
13541 var pad = self._cipher.encryptBlock(self._prev)
13542 var out = pad[0] ^ byteParam
13543
13544 self._prev = Buffer.concat([
13545 self._prev.slice(1),
13546 Buffer.from([decrypt ? byteParam : out])
13547 ])
13548
13549 return out
13550}
13551
13552exports.encrypt = function (self, chunk, decrypt) {
13553 var len = chunk.length
13554 var out = Buffer.allocUnsafe(len)
13555 var i = -1
13556
13557 while (++i < len) {
13558 out[i] = encryptByte(self, chunk[i], decrypt)
13559 }
13560
13561 return out
13562}
13563
13564},{"safe-buffer":200}],45:[function(require,module,exports){
13565var xor = require('buffer-xor')
13566var Buffer = require('safe-buffer').Buffer
13567var incr32 = require('../incr32')
13568
13569function getBlock (self) {
13570 var out = self._cipher.encryptBlockRaw(self._prev)
13571 incr32(self._prev)
13572 return out
13573}
13574
13575var blockSize = 16
13576exports.encrypt = function (self, chunk) {
13577 var chunkNum = Math.ceil(chunk.length / blockSize)
13578 var start = self._cache.length
13579 self._cache = Buffer.concat([
13580 self._cache,
13581 Buffer.allocUnsafe(chunkNum * blockSize)
13582 ])
13583 for (var i = 0; i < chunkNum; i++) {
13584 var out = getBlock(self)
13585 var offset = start + i * blockSize
13586 self._cache.writeUInt32BE(out[0], offset + 0)
13587 self._cache.writeUInt32BE(out[1], offset + 4)
13588 self._cache.writeUInt32BE(out[2], offset + 8)
13589 self._cache.writeUInt32BE(out[3], offset + 12)
13590 }
13591 var pad = self._cache.slice(0, chunk.length)
13592 self._cache = self._cache.slice(chunk.length)
13593 return xor(chunk, pad)
13594}
13595
13596},{"../incr32":40,"buffer-xor":76,"safe-buffer":200}],46:[function(require,module,exports){
13597exports.encrypt = function (self, block) {
13598 return self._cipher.encryptBlock(block)
13599}
13600
13601exports.decrypt = function (self, block) {
13602 return self._cipher.decryptBlock(block)
13603}
13604
13605},{}],47:[function(require,module,exports){
13606var modeModules = {
13607 ECB: require('./ecb'),
13608 CBC: require('./cbc'),
13609 CFB: require('./cfb'),
13610 CFB8: require('./cfb8'),
13611 CFB1: require('./cfb1'),
13612 OFB: require('./ofb'),
13613 CTR: require('./ctr'),
13614 GCM: require('./ctr')
13615}
13616
13617var modes = require('./list.json')
13618
13619for (var key in modes) {
13620 modes[key].module = modeModules[modes[key].mode]
13621}
13622
13623module.exports = modes
13624
13625},{"./cbc":41,"./cfb":42,"./cfb1":43,"./cfb8":44,"./ctr":45,"./ecb":46,"./list.json":48,"./ofb":49}],48:[function(require,module,exports){
13626module.exports={
13627 "aes-128-ecb": {
13628 "cipher": "AES",
13629 "key": 128,
13630 "iv": 0,
13631 "mode": "ECB",
13632 "type": "block"
13633 },
13634 "aes-192-ecb": {
13635 "cipher": "AES",
13636 "key": 192,
13637 "iv": 0,
13638 "mode": "ECB",
13639 "type": "block"
13640 },
13641 "aes-256-ecb": {
13642 "cipher": "AES",
13643 "key": 256,
13644 "iv": 0,
13645 "mode": "ECB",
13646 "type": "block"
13647 },
13648 "aes-128-cbc": {
13649 "cipher": "AES",
13650 "key": 128,
13651 "iv": 16,
13652 "mode": "CBC",
13653 "type": "block"
13654 },
13655 "aes-192-cbc": {
13656 "cipher": "AES",
13657 "key": 192,
13658 "iv": 16,
13659 "mode": "CBC",
13660 "type": "block"
13661 },
13662 "aes-256-cbc": {
13663 "cipher": "AES",
13664 "key": 256,
13665 "iv": 16,
13666 "mode": "CBC",
13667 "type": "block"
13668 },
13669 "aes128": {
13670 "cipher": "AES",
13671 "key": 128,
13672 "iv": 16,
13673 "mode": "CBC",
13674 "type": "block"
13675 },
13676 "aes192": {
13677 "cipher": "AES",
13678 "key": 192,
13679 "iv": 16,
13680 "mode": "CBC",
13681 "type": "block"
13682 },
13683 "aes256": {
13684 "cipher": "AES",
13685 "key": 256,
13686 "iv": 16,
13687 "mode": "CBC",
13688 "type": "block"
13689 },
13690 "aes-128-cfb": {
13691 "cipher": "AES",
13692 "key": 128,
13693 "iv": 16,
13694 "mode": "CFB",
13695 "type": "stream"
13696 },
13697 "aes-192-cfb": {
13698 "cipher": "AES",
13699 "key": 192,
13700 "iv": 16,
13701 "mode": "CFB",
13702 "type": "stream"
13703 },
13704 "aes-256-cfb": {
13705 "cipher": "AES",
13706 "key": 256,
13707 "iv": 16,
13708 "mode": "CFB",
13709 "type": "stream"
13710 },
13711 "aes-128-cfb8": {
13712 "cipher": "AES",
13713 "key": 128,
13714 "iv": 16,
13715 "mode": "CFB8",
13716 "type": "stream"
13717 },
13718 "aes-192-cfb8": {
13719 "cipher": "AES",
13720 "key": 192,
13721 "iv": 16,
13722 "mode": "CFB8",
13723 "type": "stream"
13724 },
13725 "aes-256-cfb8": {
13726 "cipher": "AES",
13727 "key": 256,
13728 "iv": 16,
13729 "mode": "CFB8",
13730 "type": "stream"
13731 },
13732 "aes-128-cfb1": {
13733 "cipher": "AES",
13734 "key": 128,
13735 "iv": 16,
13736 "mode": "CFB1",
13737 "type": "stream"
13738 },
13739 "aes-192-cfb1": {
13740 "cipher": "AES",
13741 "key": 192,
13742 "iv": 16,
13743 "mode": "CFB1",
13744 "type": "stream"
13745 },
13746 "aes-256-cfb1": {
13747 "cipher": "AES",
13748 "key": 256,
13749 "iv": 16,
13750 "mode": "CFB1",
13751 "type": "stream"
13752 },
13753 "aes-128-ofb": {
13754 "cipher": "AES",
13755 "key": 128,
13756 "iv": 16,
13757 "mode": "OFB",
13758 "type": "stream"
13759 },
13760 "aes-192-ofb": {
13761 "cipher": "AES",
13762 "key": 192,
13763 "iv": 16,
13764 "mode": "OFB",
13765 "type": "stream"
13766 },
13767 "aes-256-ofb": {
13768 "cipher": "AES",
13769 "key": 256,
13770 "iv": 16,
13771 "mode": "OFB",
13772 "type": "stream"
13773 },
13774 "aes-128-ctr": {
13775 "cipher": "AES",
13776 "key": 128,
13777 "iv": 16,
13778 "mode": "CTR",
13779 "type": "stream"
13780 },
13781 "aes-192-ctr": {
13782 "cipher": "AES",
13783 "key": 192,
13784 "iv": 16,
13785 "mode": "CTR",
13786 "type": "stream"
13787 },
13788 "aes-256-ctr": {
13789 "cipher": "AES",
13790 "key": 256,
13791 "iv": 16,
13792 "mode": "CTR",
13793 "type": "stream"
13794 },
13795 "aes-128-gcm": {
13796 "cipher": "AES",
13797 "key": 128,
13798 "iv": 12,
13799 "mode": "GCM",
13800 "type": "auth"
13801 },
13802 "aes-192-gcm": {
13803 "cipher": "AES",
13804 "key": 192,
13805 "iv": 12,
13806 "mode": "GCM",
13807 "type": "auth"
13808 },
13809 "aes-256-gcm": {
13810 "cipher": "AES",
13811 "key": 256,
13812 "iv": 12,
13813 "mode": "GCM",
13814 "type": "auth"
13815 }
13816}
13817
13818},{}],49:[function(require,module,exports){
13819(function (Buffer){(function (){
13820var xor = require('buffer-xor')
13821
13822function getBlock (self) {
13823 self._prev = self._cipher.encryptBlock(self._prev)
13824 return self._prev
13825}
13826
13827exports.encrypt = function (self, chunk) {
13828 while (self._cache.length < chunk.length) {
13829 self._cache = Buffer.concat([self._cache, getBlock(self)])
13830 }
13831
13832 var pad = self._cache.slice(0, chunk.length)
13833 self._cache = self._cache.slice(chunk.length)
13834 return xor(chunk, pad)
13835}
13836
13837}).call(this)}).call(this,require("buffer").Buffer)
13838},{"buffer":77,"buffer-xor":76}],50:[function(require,module,exports){
13839var aes = require('./aes')
13840var Buffer = require('safe-buffer').Buffer
13841var Transform = require('cipher-base')
13842var inherits = require('inherits')
13843
13844function StreamCipher (mode, key, iv, decrypt) {
13845 Transform.call(this)
13846
13847 this._cipher = new aes.AES(key)
13848 this._prev = Buffer.from(iv)
13849 this._cache = Buffer.allocUnsafe(0)
13850 this._secCache = Buffer.allocUnsafe(0)
13851 this._decrypt = decrypt
13852 this._mode = mode
13853}
13854
13855inherits(StreamCipher, Transform)
13856
13857StreamCipher.prototype._update = function (chunk) {
13858 return this._mode.encrypt(this, chunk, this._decrypt)
13859}
13860
13861StreamCipher.prototype._final = function () {
13862 this._cipher.scrub()
13863}
13864
13865module.exports = StreamCipher
13866
13867},{"./aes":34,"cipher-base":78,"inherits":152,"safe-buffer":200}],51:[function(require,module,exports){
13868var DES = require('browserify-des')
13869var aes = require('browserify-aes/browser')
13870var aesModes = require('browserify-aes/modes')
13871var desModes = require('browserify-des/modes')
13872var ebtk = require('evp_bytestokey')
13873
13874function createCipher (suite, password) {
13875 suite = suite.toLowerCase()
13876
13877 var keyLen, ivLen
13878 if (aesModes[suite]) {
13879 keyLen = aesModes[suite].key
13880 ivLen = aesModes[suite].iv
13881 } else if (desModes[suite]) {
13882 keyLen = desModes[suite].key * 8
13883 ivLen = desModes[suite].iv
13884 } else {
13885 throw new TypeError('invalid suite type')
13886 }
13887
13888 var keys = ebtk(password, false, keyLen, ivLen)
13889 return createCipheriv(suite, keys.key, keys.iv)
13890}
13891
13892function createDecipher (suite, password) {
13893 suite = suite.toLowerCase()
13894
13895 var keyLen, ivLen
13896 if (aesModes[suite]) {
13897 keyLen = aesModes[suite].key
13898 ivLen = aesModes[suite].iv
13899 } else if (desModes[suite]) {
13900 keyLen = desModes[suite].key * 8
13901 ivLen = desModes[suite].iv
13902 } else {
13903 throw new TypeError('invalid suite type')
13904 }
13905
13906 var keys = ebtk(password, false, keyLen, ivLen)
13907 return createDecipheriv(suite, keys.key, keys.iv)
13908}
13909
13910function createCipheriv (suite, key, iv) {
13911 suite = suite.toLowerCase()
13912 if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
13913 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })
13914
13915 throw new TypeError('invalid suite type')
13916}
13917
13918function createDecipheriv (suite, key, iv) {
13919 suite = suite.toLowerCase()
13920 if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
13921 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })
13922
13923 throw new TypeError('invalid suite type')
13924}
13925
13926function getCiphers () {
13927 return Object.keys(desModes).concat(aes.getCiphers())
13928}
13929
13930exports.createCipher = exports.Cipher = createCipher
13931exports.createCipheriv = exports.Cipheriv = createCipheriv
13932exports.createDecipher = exports.Decipher = createDecipher
13933exports.createDecipheriv = exports.Decipheriv = createDecipheriv
13934exports.listCiphers = exports.getCiphers = getCiphers
13935
13936},{"browserify-aes/browser":36,"browserify-aes/modes":47,"browserify-des":52,"browserify-des/modes":53,"evp_bytestokey":121}],52:[function(require,module,exports){
13937var CipherBase = require('cipher-base')
13938var des = require('des.js')
13939var inherits = require('inherits')
13940var Buffer = require('safe-buffer').Buffer
13941
13942var modes = {
13943 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
13944 'des-ede3': des.EDE,
13945 'des-ede-cbc': des.CBC.instantiate(des.EDE),
13946 'des-ede': des.EDE,
13947 'des-cbc': des.CBC.instantiate(des.DES),
13948 'des-ecb': des.DES
13949}
13950modes.des = modes['des-cbc']
13951modes.des3 = modes['des-ede3-cbc']
13952module.exports = DES
13953inherits(DES, CipherBase)
13954function DES (opts) {
13955 CipherBase.call(this)
13956 var modeName = opts.mode.toLowerCase()
13957 var mode = modes[modeName]
13958 var type
13959 if (opts.decrypt) {
13960 type = 'decrypt'
13961 } else {
13962 type = 'encrypt'
13963 }
13964 var key = opts.key
13965 if (!Buffer.isBuffer(key)) {
13966 key = Buffer.from(key)
13967 }
13968 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
13969 key = Buffer.concat([key, key.slice(0, 8)])
13970 }
13971 var iv = opts.iv
13972 if (!Buffer.isBuffer(iv)) {
13973 iv = Buffer.from(iv)
13974 }
13975 this._des = mode.create({
13976 key: key,
13977 iv: iv,
13978 type: type
13979 })
13980}
13981DES.prototype._update = function (data) {
13982 return Buffer.from(this._des.update(data))
13983}
13984DES.prototype._final = function () {
13985 return Buffer.from(this._des.final())
13986}
13987
13988},{"cipher-base":78,"des.js":87,"inherits":152,"safe-buffer":200}],53:[function(require,module,exports){
13989exports['des-ecb'] = {
13990 key: 8,
13991 iv: 0
13992}
13993exports['des-cbc'] = exports.des = {
13994 key: 8,
13995 iv: 8
13996}
13997exports['des-ede3-cbc'] = exports.des3 = {
13998 key: 24,
13999 iv: 8
14000}
14001exports['des-ede3'] = {
14002 key: 24,
14003 iv: 0
14004}
14005exports['des-ede-cbc'] = {
14006 key: 16,
14007 iv: 8
14008}
14009exports['des-ede'] = {
14010 key: 16,
14011 iv: 0
14012}
14013
14014},{}],54:[function(require,module,exports){
14015(function (Buffer){(function (){
14016var BN = require('bn.js')
14017var randomBytes = require('randombytes')
14018
14019function blind (priv) {
14020 var r = getr(priv)
14021 var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed()
14022 return { blinder: blinder, unblinder: r.invm(priv.modulus) }
14023}
14024
14025function getr (priv) {
14026 var len = priv.modulus.byteLength()
14027 var r
14028 do {
14029 r = new BN(randomBytes(len))
14030 } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2))
14031 return r
14032}
14033
14034function crt (msg, priv) {
14035 var blinds = blind(priv)
14036 var len = priv.modulus.byteLength()
14037 var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus)
14038 var c1 = blinded.toRed(BN.mont(priv.prime1))
14039 var c2 = blinded.toRed(BN.mont(priv.prime2))
14040 var qinv = priv.coefficient
14041 var p = priv.prime1
14042 var q = priv.prime2
14043 var m1 = c1.redPow(priv.exponent1).fromRed()
14044 var m2 = c2.redPow(priv.exponent2).fromRed()
14045 var h = m1.isub(m2).imul(qinv).umod(p).imul(q)
14046 return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len)
14047}
14048crt.getr = getr
14049
14050module.exports = crt
14051
14052}).call(this)}).call(this,require("buffer").Buffer)
14053},{"bn.js":31,"buffer":77,"randombytes":182}],55:[function(require,module,exports){
14054module.exports = require('./browser/algorithms.json')
14055
14056},{"./browser/algorithms.json":56}],56:[function(require,module,exports){
14057module.exports={
14058 "sha224WithRSAEncryption": {
14059 "sign": "rsa",
14060 "hash": "sha224",
14061 "id": "302d300d06096086480165030402040500041c"
14062 },
14063 "RSA-SHA224": {
14064 "sign": "ecdsa/rsa",
14065 "hash": "sha224",
14066 "id": "302d300d06096086480165030402040500041c"
14067 },
14068 "sha256WithRSAEncryption": {
14069 "sign": "rsa",
14070 "hash": "sha256",
14071 "id": "3031300d060960864801650304020105000420"
14072 },
14073 "RSA-SHA256": {
14074 "sign": "ecdsa/rsa",
14075 "hash": "sha256",
14076 "id": "3031300d060960864801650304020105000420"
14077 },
14078 "sha384WithRSAEncryption": {
14079 "sign": "rsa",
14080 "hash": "sha384",
14081 "id": "3041300d060960864801650304020205000430"
14082 },
14083 "RSA-SHA384": {
14084 "sign": "ecdsa/rsa",
14085 "hash": "sha384",
14086 "id": "3041300d060960864801650304020205000430"
14087 },
14088 "sha512WithRSAEncryption": {
14089 "sign": "rsa",
14090 "hash": "sha512",
14091 "id": "3051300d060960864801650304020305000440"
14092 },
14093 "RSA-SHA512": {
14094 "sign": "ecdsa/rsa",
14095 "hash": "sha512",
14096 "id": "3051300d060960864801650304020305000440"
14097 },
14098 "RSA-SHA1": {
14099 "sign": "rsa",
14100 "hash": "sha1",
14101 "id": "3021300906052b0e03021a05000414"
14102 },
14103 "ecdsa-with-SHA1": {
14104 "sign": "ecdsa",
14105 "hash": "sha1",
14106 "id": ""
14107 },
14108 "sha256": {
14109 "sign": "ecdsa",
14110 "hash": "sha256",
14111 "id": ""
14112 },
14113 "sha224": {
14114 "sign": "ecdsa",
14115 "hash": "sha224",
14116 "id": ""
14117 },
14118 "sha384": {
14119 "sign": "ecdsa",
14120 "hash": "sha384",
14121 "id": ""
14122 },
14123 "sha512": {
14124 "sign": "ecdsa",
14125 "hash": "sha512",
14126 "id": ""
14127 },
14128 "DSA-SHA": {
14129 "sign": "dsa",
14130 "hash": "sha1",
14131 "id": ""
14132 },
14133 "DSA-SHA1": {
14134 "sign": "dsa",
14135 "hash": "sha1",
14136 "id": ""
14137 },
14138 "DSA": {
14139 "sign": "dsa",
14140 "hash": "sha1",
14141 "id": ""
14142 },
14143 "DSA-WITH-SHA224": {
14144 "sign": "dsa",
14145 "hash": "sha224",
14146 "id": ""
14147 },
14148 "DSA-SHA224": {
14149 "sign": "dsa",
14150 "hash": "sha224",
14151 "id": ""
14152 },
14153 "DSA-WITH-SHA256": {
14154 "sign": "dsa",
14155 "hash": "sha256",
14156 "id": ""
14157 },
14158 "DSA-SHA256": {
14159 "sign": "dsa",
14160 "hash": "sha256",
14161 "id": ""
14162 },
14163 "DSA-WITH-SHA384": {
14164 "sign": "dsa",
14165 "hash": "sha384",
14166 "id": ""
14167 },
14168 "DSA-SHA384": {
14169 "sign": "dsa",
14170 "hash": "sha384",
14171 "id": ""
14172 },
14173 "DSA-WITH-SHA512": {
14174 "sign": "dsa",
14175 "hash": "sha512",
14176 "id": ""
14177 },
14178 "DSA-SHA512": {
14179 "sign": "dsa",
14180 "hash": "sha512",
14181 "id": ""
14182 },
14183 "DSA-RIPEMD160": {
14184 "sign": "dsa",
14185 "hash": "rmd160",
14186 "id": ""
14187 },
14188 "ripemd160WithRSA": {
14189 "sign": "rsa",
14190 "hash": "rmd160",
14191 "id": "3021300906052b2403020105000414"
14192 },
14193 "RSA-RIPEMD160": {
14194 "sign": "rsa",
14195 "hash": "rmd160",
14196 "id": "3021300906052b2403020105000414"
14197 },
14198 "md5WithRSAEncryption": {
14199 "sign": "rsa",
14200 "hash": "md5",
14201 "id": "3020300c06082a864886f70d020505000410"
14202 },
14203 "RSA-MD5": {
14204 "sign": "rsa",
14205 "hash": "md5",
14206 "id": "3020300c06082a864886f70d020505000410"
14207 }
14208}
14209
14210},{}],57:[function(require,module,exports){
14211module.exports={
14212 "1.3.132.0.10": "secp256k1",
14213 "1.3.132.0.33": "p224",
14214 "1.2.840.10045.3.1.1": "p192",
14215 "1.2.840.10045.3.1.7": "p256",
14216 "1.3.132.0.34": "p384",
14217 "1.3.132.0.35": "p521"
14218}
14219
14220},{}],58:[function(require,module,exports){
14221var Buffer = require('safe-buffer').Buffer
14222var createHash = require('create-hash')
14223var stream = require('readable-stream')
14224var inherits = require('inherits')
14225var sign = require('./sign')
14226var verify = require('./verify')
14227
14228var algorithms = require('./algorithms.json')
14229Object.keys(algorithms).forEach(function (key) {
14230 algorithms[key].id = Buffer.from(algorithms[key].id, 'hex')
14231 algorithms[key.toLowerCase()] = algorithms[key]
14232})
14233
14234function Sign (algorithm) {
14235 stream.Writable.call(this)
14236
14237 var data = algorithms[algorithm]
14238 if (!data) throw new Error('Unknown message digest')
14239
14240 this._hashType = data.hash
14241 this._hash = createHash(data.hash)
14242 this._tag = data.id
14243 this._signType = data.sign
14244}
14245inherits(Sign, stream.Writable)
14246
14247Sign.prototype._write = function _write (data, _, done) {
14248 this._hash.update(data)
14249 done()
14250}
14251
14252Sign.prototype.update = function update (data, enc) {
14253 if (typeof data === 'string') data = Buffer.from(data, enc)
14254
14255 this._hash.update(data)
14256 return this
14257}
14258
14259Sign.prototype.sign = function signMethod (key, enc) {
14260 this.end()
14261 var hash = this._hash.digest()
14262 var sig = sign(hash, key, this._hashType, this._signType, this._tag)
14263
14264 return enc ? sig.toString(enc) : sig
14265}
14266
14267function Verify (algorithm) {
14268 stream.Writable.call(this)
14269
14270 var data = algorithms[algorithm]
14271 if (!data) throw new Error('Unknown message digest')
14272
14273 this._hash = createHash(data.hash)
14274 this._tag = data.id
14275 this._signType = data.sign
14276}
14277inherits(Verify, stream.Writable)
14278
14279Verify.prototype._write = function _write (data, _, done) {
14280 this._hash.update(data)
14281 done()
14282}
14283
14284Verify.prototype.update = function update (data, enc) {
14285 if (typeof data === 'string') data = Buffer.from(data, enc)
14286
14287 this._hash.update(data)
14288 return this
14289}
14290
14291Verify.prototype.verify = function verifyMethod (key, sig, enc) {
14292 if (typeof sig === 'string') sig = Buffer.from(sig, enc)
14293
14294 this.end()
14295 var hash = this._hash.digest()
14296 return verify(sig, hash, key, this._signType, this._tag)
14297}
14298
14299function createSign (algorithm) {
14300 return new Sign(algorithm)
14301}
14302
14303function createVerify (algorithm) {
14304 return new Verify(algorithm)
14305}
14306
14307module.exports = {
14308 Sign: createSign,
14309 Verify: createVerify,
14310 createSign: createSign,
14311 createVerify: createVerify
14312}
14313
14314},{"./algorithms.json":56,"./sign":59,"./verify":60,"create-hash":82,"inherits":152,"readable-stream":75,"safe-buffer":200}],59:[function(require,module,exports){
14315// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
14316var Buffer = require('safe-buffer').Buffer
14317var createHmac = require('create-hmac')
14318var crt = require('browserify-rsa')
14319var EC = require('elliptic').ec
14320var BN = require('bn.js')
14321var parseKeys = require('parse-asn1')
14322var curves = require('./curves.json')
14323
14324function sign (hash, key, hashType, signType, tag) {
14325 var priv = parseKeys(key)
14326 if (priv.curve) {
14327 // rsa keys can be interpreted as ecdsa ones in openssl
14328 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
14329 return ecSign(hash, priv)
14330 } else if (priv.type === 'dsa') {
14331 if (signType !== 'dsa') throw new Error('wrong private key type')
14332 return dsaSign(hash, priv, hashType)
14333 } else {
14334 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
14335 }
14336 hash = Buffer.concat([tag, hash])
14337 var len = priv.modulus.byteLength()
14338 var pad = [0, 1]
14339 while (hash.length + pad.length + 1 < len) pad.push(0xff)
14340 pad.push(0x00)
14341 var i = -1
14342 while (++i < hash.length) pad.push(hash[i])
14343
14344 var out = crt(pad, priv)
14345 return out
14346}
14347
14348function ecSign (hash, priv) {
14349 var curveId = curves[priv.curve.join('.')]
14350 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
14351
14352 var curve = new EC(curveId)
14353 var key = curve.keyFromPrivate(priv.privateKey)
14354 var out = key.sign(hash)
14355
14356 return Buffer.from(out.toDER())
14357}
14358
14359function dsaSign (hash, priv, algo) {
14360 var x = priv.params.priv_key
14361 var p = priv.params.p
14362 var q = priv.params.q
14363 var g = priv.params.g
14364 var r = new BN(0)
14365 var k
14366 var H = bits2int(hash, q).mod(q)
14367 var s = false
14368 var kv = getKey(x, q, hash, algo)
14369 while (s === false) {
14370 k = makeKey(q, kv, algo)
14371 r = makeR(g, k, p, q)
14372 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
14373 if (s.cmpn(0) === 0) {
14374 s = false
14375 r = new BN(0)
14376 }
14377 }
14378 return toDER(r, s)
14379}
14380
14381function toDER (r, s) {
14382 r = r.toArray()
14383 s = s.toArray()
14384
14385 // Pad values
14386 if (r[0] & 0x80) r = [0].concat(r)
14387 if (s[0] & 0x80) s = [0].concat(s)
14388
14389 var total = r.length + s.length + 4
14390 var res = [0x30, total, 0x02, r.length]
14391 res = res.concat(r, [0x02, s.length], s)
14392 return Buffer.from(res)
14393}
14394
14395function getKey (x, q, hash, algo) {
14396 x = Buffer.from(x.toArray())
14397 if (x.length < q.byteLength()) {
14398 var zeros = Buffer.alloc(q.byteLength() - x.length)
14399 x = Buffer.concat([zeros, x])
14400 }
14401 var hlen = hash.length
14402 var hbits = bits2octets(hash, q)
14403 var v = Buffer.alloc(hlen)
14404 v.fill(1)
14405 var k = Buffer.alloc(hlen)
14406 k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest()
14407 v = createHmac(algo, k).update(v).digest()
14408 k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest()
14409 v = createHmac(algo, k).update(v).digest()
14410 return { k: k, v: v }
14411}
14412
14413function bits2int (obits, q) {
14414 var bits = new BN(obits)
14415 var shift = (obits.length << 3) - q.bitLength()
14416 if (shift > 0) bits.ishrn(shift)
14417 return bits
14418}
14419
14420function bits2octets (bits, q) {
14421 bits = bits2int(bits, q)
14422 bits = bits.mod(q)
14423 var out = Buffer.from(bits.toArray())
14424 if (out.length < q.byteLength()) {
14425 var zeros = Buffer.alloc(q.byteLength() - out.length)
14426 out = Buffer.concat([zeros, out])
14427 }
14428 return out
14429}
14430
14431function makeKey (q, kv, algo) {
14432 var t
14433 var k
14434
14435 do {
14436 t = Buffer.alloc(0)
14437
14438 while (t.length * 8 < q.bitLength()) {
14439 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
14440 t = Buffer.concat([t, kv.v])
14441 }
14442
14443 k = bits2int(t, q)
14444 kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest()
14445 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
14446 } while (k.cmp(q) !== -1)
14447
14448 return k
14449}
14450
14451function makeR (g, k, p, q) {
14452 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
14453}
14454
14455module.exports = sign
14456module.exports.getKey = getKey
14457module.exports.makeKey = makeKey
14458
14459},{"./curves.json":57,"bn.js":31,"browserify-rsa":54,"create-hmac":84,"elliptic":103,"parse-asn1":166,"safe-buffer":200}],60:[function(require,module,exports){
14460// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
14461var Buffer = require('safe-buffer').Buffer
14462var BN = require('bn.js')
14463var EC = require('elliptic').ec
14464var parseKeys = require('parse-asn1')
14465var curves = require('./curves.json')
14466
14467function verify (sig, hash, key, signType, tag) {
14468 var pub = parseKeys(key)
14469 if (pub.type === 'ec') {
14470 // rsa keys can be interpreted as ecdsa ones in openssl
14471 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
14472 return ecVerify(sig, hash, pub)
14473 } else if (pub.type === 'dsa') {
14474 if (signType !== 'dsa') throw new Error('wrong public key type')
14475 return dsaVerify(sig, hash, pub)
14476 } else {
14477 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
14478 }
14479 hash = Buffer.concat([tag, hash])
14480 var len = pub.modulus.byteLength()
14481 var pad = [1]
14482 var padNum = 0
14483 while (hash.length + pad.length + 2 < len) {
14484 pad.push(0xff)
14485 padNum++
14486 }
14487 pad.push(0x00)
14488 var i = -1
14489 while (++i < hash.length) {
14490 pad.push(hash[i])
14491 }
14492 pad = Buffer.from(pad)
14493 var red = BN.mont(pub.modulus)
14494 sig = new BN(sig).toRed(red)
14495
14496 sig = sig.redPow(new BN(pub.publicExponent))
14497 sig = Buffer.from(sig.fromRed().toArray())
14498 var out = padNum < 8 ? 1 : 0
14499 len = Math.min(sig.length, pad.length)
14500 if (sig.length !== pad.length) out = 1
14501
14502 i = -1
14503 while (++i < len) out |= sig[i] ^ pad[i]
14504 return out === 0
14505}
14506
14507function ecVerify (sig, hash, pub) {
14508 var curveId = curves[pub.data.algorithm.curve.join('.')]
14509 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
14510
14511 var curve = new EC(curveId)
14512 var pubkey = pub.data.subjectPrivateKey.data
14513
14514 return curve.verify(hash, sig, pubkey)
14515}
14516
14517function dsaVerify (sig, hash, pub) {
14518 var p = pub.data.p
14519 var q = pub.data.q
14520 var g = pub.data.g
14521 var y = pub.data.pub_key
14522 var unpacked = parseKeys.signature.decode(sig, 'der')
14523 var s = unpacked.s
14524 var r = unpacked.r
14525 checkValue(s, q)
14526 checkValue(r, q)
14527 var montp = BN.mont(p)
14528 var w = s.invm(q)
14529 var v = g.toRed(montp)
14530 .redPow(new BN(hash).mul(w).mod(q))
14531 .fromRed()
14532 .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
14533 .mod(p)
14534 .mod(q)
14535 return v.cmp(r) === 0
14536}
14537
14538function checkValue (b, q) {
14539 if (b.cmpn(0) <= 0) throw new Error('invalid sig')
14540 if (b.cmp(q) >= q) throw new Error('invalid sig')
14541}
14542
14543module.exports = verify
14544
14545},{"./curves.json":57,"bn.js":31,"elliptic":103,"parse-asn1":166,"safe-buffer":200}],61:[function(require,module,exports){
14546'use strict';
14547
14548function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
14549
14550var codes = {};
14551
14552function createErrorType(code, message, Base) {
14553 if (!Base) {
14554 Base = Error;
14555 }
14556
14557 function getMessage(arg1, arg2, arg3) {
14558 if (typeof message === 'string') {
14559 return message;
14560 } else {
14561 return message(arg1, arg2, arg3);
14562 }
14563 }
14564
14565 var NodeError =
14566 /*#__PURE__*/
14567 function (_Base) {
14568 _inheritsLoose(NodeError, _Base);
14569
14570 function NodeError(arg1, arg2, arg3) {
14571 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
14572 }
14573
14574 return NodeError;
14575 }(Base);
14576
14577 NodeError.prototype.name = Base.name;
14578 NodeError.prototype.code = code;
14579 codes[code] = NodeError;
14580} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
14581
14582
14583function oneOf(expected, thing) {
14584 if (Array.isArray(expected)) {
14585 var len = expected.length;
14586 expected = expected.map(function (i) {
14587 return String(i);
14588 });
14589
14590 if (len > 2) {
14591 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
14592 } else if (len === 2) {
14593 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
14594 } else {
14595 return "of ".concat(thing, " ").concat(expected[0]);
14596 }
14597 } else {
14598 return "of ".concat(thing, " ").concat(String(expected));
14599 }
14600} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
14601
14602
14603function startsWith(str, search, pos) {
14604 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
14605} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
14606
14607
14608function endsWith(str, search, this_len) {
14609 if (this_len === undefined || this_len > str.length) {
14610 this_len = str.length;
14611 }
14612
14613 return str.substring(this_len - search.length, this_len) === search;
14614} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
14615
14616
14617function includes(str, search, start) {
14618 if (typeof start !== 'number') {
14619 start = 0;
14620 }
14621
14622 if (start + search.length > str.length) {
14623 return false;
14624 } else {
14625 return str.indexOf(search, start) !== -1;
14626 }
14627}
14628
14629createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
14630 return 'The value "' + value + '" is invalid for option "' + name + '"';
14631}, TypeError);
14632createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
14633 // determiner: 'must be' or 'must not be'
14634 var determiner;
14635
14636 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
14637 determiner = 'must not be';
14638 expected = expected.replace(/^not /, '');
14639 } else {
14640 determiner = 'must be';
14641 }
14642
14643 var msg;
14644
14645 if (endsWith(name, ' argument')) {
14646 // For cases like 'first argument'
14647 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
14648 } else {
14649 var type = includes(name, '.') ? 'property' : 'argument';
14650 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
14651 }
14652
14653 msg += ". Received type ".concat(typeof actual);
14654 return msg;
14655}, TypeError);
14656createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
14657createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
14658 return 'The ' + name + ' method is not implemented';
14659});
14660createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
14661createErrorType('ERR_STREAM_DESTROYED', function (name) {
14662 return 'Cannot call ' + name + ' after a stream was destroyed';
14663});
14664createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
14665createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
14666createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
14667createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
14668createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
14669 return 'Unknown encoding: ' + arg;
14670}, TypeError);
14671createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
14672module.exports.codes = codes;
14673
14674},{}],62:[function(require,module,exports){
14675(function (process){(function (){
14676// Copyright Joyent, Inc. and other Node contributors.
14677//
14678// Permission is hereby granted, free of charge, to any person obtaining a
14679// copy of this software and associated documentation files (the
14680// "Software"), to deal in the Software without restriction, including
14681// without limitation the rights to use, copy, modify, merge, publish,
14682// distribute, sublicense, and/or sell copies of the Software, and to permit
14683// persons to whom the Software is furnished to do so, subject to the
14684// following conditions:
14685//
14686// The above copyright notice and this permission notice shall be included
14687// in all copies or substantial portions of the Software.
14688//
14689// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14690// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14691// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14692// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14693// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14694// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14695// USE OR OTHER DEALINGS IN THE SOFTWARE.
14696// a duplex stream is just a stream that is both readable and writable.
14697// Since JS doesn't have multiple prototypal inheritance, this class
14698// prototypally inherits from Readable, and then parasitically from
14699// Writable.
14700'use strict';
14701/*<replacement>*/
14702
14703var objectKeys = Object.keys || function (obj) {
14704 var keys = [];
14705
14706 for (var key in obj) {
14707 keys.push(key);
14708 }
14709
14710 return keys;
14711};
14712/*</replacement>*/
14713
14714
14715module.exports = Duplex;
14716
14717var Readable = require('./_stream_readable');
14718
14719var Writable = require('./_stream_writable');
14720
14721require('inherits')(Duplex, Readable);
14722
14723{
14724 // Allow the keys array to be GC'ed.
14725 var keys = objectKeys(Writable.prototype);
14726
14727 for (var v = 0; v < keys.length; v++) {
14728 var method = keys[v];
14729 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
14730 }
14731}
14732
14733function Duplex(options) {
14734 if (!(this instanceof Duplex)) return new Duplex(options);
14735 Readable.call(this, options);
14736 Writable.call(this, options);
14737 this.allowHalfOpen = true;
14738
14739 if (options) {
14740 if (options.readable === false) this.readable = false;
14741 if (options.writable === false) this.writable = false;
14742
14743 if (options.allowHalfOpen === false) {
14744 this.allowHalfOpen = false;
14745 this.once('end', onend);
14746 }
14747 }
14748}
14749
14750Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
14751 // making it explicit this property is not enumerable
14752 // because otherwise some prototype manipulation in
14753 // userland will fail
14754 enumerable: false,
14755 get: function get() {
14756 return this._writableState.highWaterMark;
14757 }
14758});
14759Object.defineProperty(Duplex.prototype, 'writableBuffer', {
14760 // making it explicit this property is not enumerable
14761 // because otherwise some prototype manipulation in
14762 // userland will fail
14763 enumerable: false,
14764 get: function get() {
14765 return this._writableState && this._writableState.getBuffer();
14766 }
14767});
14768Object.defineProperty(Duplex.prototype, 'writableLength', {
14769 // making it explicit this property is not enumerable
14770 // because otherwise some prototype manipulation in
14771 // userland will fail
14772 enumerable: false,
14773 get: function get() {
14774 return this._writableState.length;
14775 }
14776}); // the no-half-open enforcer
14777
14778function onend() {
14779 // If the writable side ended, then we're ok.
14780 if (this._writableState.ended) return; // no more data can be written.
14781 // But allow more writes to happen in this tick.
14782
14783 process.nextTick(onEndNT, this);
14784}
14785
14786function onEndNT(self) {
14787 self.end();
14788}
14789
14790Object.defineProperty(Duplex.prototype, 'destroyed', {
14791 // making it explicit this property is not enumerable
14792 // because otherwise some prototype manipulation in
14793 // userland will fail
14794 enumerable: false,
14795 get: function get() {
14796 if (this._readableState === undefined || this._writableState === undefined) {
14797 return false;
14798 }
14799
14800 return this._readableState.destroyed && this._writableState.destroyed;
14801 },
14802 set: function set(value) {
14803 // we ignore the value if the stream
14804 // has not been initialized yet
14805 if (this._readableState === undefined || this._writableState === undefined) {
14806 return;
14807 } // backward compatibility, the user is explicitly
14808 // managing destroyed
14809
14810
14811 this._readableState.destroyed = value;
14812 this._writableState.destroyed = value;
14813 }
14814});
14815}).call(this)}).call(this,require('_process'))
14816},{"./_stream_readable":64,"./_stream_writable":66,"_process":174,"inherits":152}],63:[function(require,module,exports){
14817// Copyright Joyent, Inc. and other Node contributors.
14818//
14819// Permission is hereby granted, free of charge, to any person obtaining a
14820// copy of this software and associated documentation files (the
14821// "Software"), to deal in the Software without restriction, including
14822// without limitation the rights to use, copy, modify, merge, publish,
14823// distribute, sublicense, and/or sell copies of the Software, and to permit
14824// persons to whom the Software is furnished to do so, subject to the
14825// following conditions:
14826//
14827// The above copyright notice and this permission notice shall be included
14828// in all copies or substantial portions of the Software.
14829//
14830// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14831// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14832// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14833// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14834// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14835// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14836// USE OR OTHER DEALINGS IN THE SOFTWARE.
14837// a passthrough stream.
14838// basically just the most minimal sort of Transform stream.
14839// Every written chunk gets output as-is.
14840'use strict';
14841
14842module.exports = PassThrough;
14843
14844var Transform = require('./_stream_transform');
14845
14846require('inherits')(PassThrough, Transform);
14847
14848function PassThrough(options) {
14849 if (!(this instanceof PassThrough)) return new PassThrough(options);
14850 Transform.call(this, options);
14851}
14852
14853PassThrough.prototype._transform = function (chunk, encoding, cb) {
14854 cb(null, chunk);
14855};
14856},{"./_stream_transform":65,"inherits":152}],64:[function(require,module,exports){
14857(function (process,global){(function (){
14858// Copyright Joyent, Inc. and other Node contributors.
14859//
14860// Permission is hereby granted, free of charge, to any person obtaining a
14861// copy of this software and associated documentation files (the
14862// "Software"), to deal in the Software without restriction, including
14863// without limitation the rights to use, copy, modify, merge, publish,
14864// distribute, sublicense, and/or sell copies of the Software, and to permit
14865// persons to whom the Software is furnished to do so, subject to the
14866// following conditions:
14867//
14868// The above copyright notice and this permission notice shall be included
14869// in all copies or substantial portions of the Software.
14870//
14871// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14872// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14873// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
14874// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
14875// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
14876// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
14877// USE OR OTHER DEALINGS IN THE SOFTWARE.
14878'use strict';
14879
14880module.exports = Readable;
14881/*<replacement>*/
14882
14883var Duplex;
14884/*</replacement>*/
14885
14886Readable.ReadableState = ReadableState;
14887/*<replacement>*/
14888
14889var EE = require('events').EventEmitter;
14890
14891var EElistenerCount = function EElistenerCount(emitter, type) {
14892 return emitter.listeners(type).length;
14893};
14894/*</replacement>*/
14895
14896/*<replacement>*/
14897
14898
14899var Stream = require('./internal/streams/stream');
14900/*</replacement>*/
14901
14902
14903var Buffer = require('buffer').Buffer;
14904
14905var OurUint8Array = global.Uint8Array || function () {};
14906
14907function _uint8ArrayToBuffer(chunk) {
14908 return Buffer.from(chunk);
14909}
14910
14911function _isUint8Array(obj) {
14912 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
14913}
14914/*<replacement>*/
14915
14916
14917var debugUtil = require('util');
14918
14919var debug;
14920
14921if (debugUtil && debugUtil.debuglog) {
14922 debug = debugUtil.debuglog('stream');
14923} else {
14924 debug = function debug() {};
14925}
14926/*</replacement>*/
14927
14928
14929var BufferList = require('./internal/streams/buffer_list');
14930
14931var destroyImpl = require('./internal/streams/destroy');
14932
14933var _require = require('./internal/streams/state'),
14934 getHighWaterMark = _require.getHighWaterMark;
14935
14936var _require$codes = require('../errors').codes,
14937 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
14938 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
14939 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
14940 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
14941
14942
14943var StringDecoder;
14944var createReadableStreamAsyncIterator;
14945var from;
14946
14947require('inherits')(Readable, Stream);
14948
14949var errorOrDestroy = destroyImpl.errorOrDestroy;
14950var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
14951
14952function prependListener(emitter, event, fn) {
14953 // Sadly this is not cacheable as some libraries bundle their own
14954 // event emitter implementation with them.
14955 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
14956 // userland ones. NEVER DO THIS. This is here only because this code needs
14957 // to continue to work with older versions of Node.js that do not include
14958 // the prependListener() method. The goal is to eventually remove this hack.
14959
14960 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
14961}
14962
14963function ReadableState(options, stream, isDuplex) {
14964 Duplex = Duplex || require('./_stream_duplex');
14965 options = options || {}; // Duplex streams are both readable and writable, but share
14966 // the same options object.
14967 // However, some cases require setting options to different
14968 // values for the readable and the writable sides of the duplex stream.
14969 // These options can be provided separately as readableXXX and writableXXX.
14970
14971 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
14972 // make all the buffer merging and length checks go away
14973
14974 this.objectMode = !!options.objectMode;
14975 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
14976 // Note: 0 is a valid value, means "don't call _read preemptively ever"
14977
14978 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
14979 // linked list can remove elements from the beginning faster than
14980 // array.shift()
14981
14982 this.buffer = new BufferList();
14983 this.length = 0;
14984 this.pipes = null;
14985 this.pipesCount = 0;
14986 this.flowing = null;
14987 this.ended = false;
14988 this.endEmitted = false;
14989 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
14990 // immediately, or on a later tick. We set this to true at first, because
14991 // any actions that shouldn't happen until "later" should generally also
14992 // not happen before the first read call.
14993
14994 this.sync = true; // whenever we return null, then we set a flag to say
14995 // that we're awaiting a 'readable' event emission.
14996
14997 this.needReadable = false;
14998 this.emittedReadable = false;
14999 this.readableListening = false;
15000 this.resumeScheduled = false;
15001 this.paused = true; // Should close be emitted on destroy. Defaults to true.
15002
15003 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
15004
15005 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
15006
15007 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
15008 // encoding is 'binary' so we have to make this configurable.
15009 // Everything else in the universe uses 'utf8', though.
15010
15011 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
15012
15013 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
15014
15015 this.readingMore = false;
15016 this.decoder = null;
15017 this.encoding = null;
15018
15019 if (options.encoding) {
15020 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
15021 this.decoder = new StringDecoder(options.encoding);
15022 this.encoding = options.encoding;
15023 }
15024}
15025
15026function Readable(options) {
15027 Duplex = Duplex || require('./_stream_duplex');
15028 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
15029 // the ReadableState constructor, at least with V8 6.5
15030
15031 var isDuplex = this instanceof Duplex;
15032 this._readableState = new ReadableState(options, this, isDuplex); // legacy
15033
15034 this.readable = true;
15035
15036 if (options) {
15037 if (typeof options.read === 'function') this._read = options.read;
15038 if (typeof options.destroy === 'function') this._destroy = options.destroy;
15039 }
15040
15041 Stream.call(this);
15042}
15043
15044Object.defineProperty(Readable.prototype, 'destroyed', {
15045 // making it explicit this property is not enumerable
15046 // because otherwise some prototype manipulation in
15047 // userland will fail
15048 enumerable: false,
15049 get: function get() {
15050 if (this._readableState === undefined) {
15051 return false;
15052 }
15053
15054 return this._readableState.destroyed;
15055 },
15056 set: function set(value) {
15057 // we ignore the value if the stream
15058 // has not been initialized yet
15059 if (!this._readableState) {
15060 return;
15061 } // backward compatibility, the user is explicitly
15062 // managing destroyed
15063
15064
15065 this._readableState.destroyed = value;
15066 }
15067});
15068Readable.prototype.destroy = destroyImpl.destroy;
15069Readable.prototype._undestroy = destroyImpl.undestroy;
15070
15071Readable.prototype._destroy = function (err, cb) {
15072 cb(err);
15073}; // Manually shove something into the read() buffer.
15074// This returns true if the highWaterMark has not been hit yet,
15075// similar to how Writable.write() returns true if you should
15076// write() some more.
15077
15078
15079Readable.prototype.push = function (chunk, encoding) {
15080 var state = this._readableState;
15081 var skipChunkCheck;
15082
15083 if (!state.objectMode) {
15084 if (typeof chunk === 'string') {
15085 encoding = encoding || state.defaultEncoding;
15086
15087 if (encoding !== state.encoding) {
15088 chunk = Buffer.from(chunk, encoding);
15089 encoding = '';
15090 }
15091
15092 skipChunkCheck = true;
15093 }
15094 } else {
15095 skipChunkCheck = true;
15096 }
15097
15098 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
15099}; // Unshift should *always* be something directly out of read()
15100
15101
15102Readable.prototype.unshift = function (chunk) {
15103 return readableAddChunk(this, chunk, null, true, false);
15104};
15105
15106function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
15107 debug('readableAddChunk', chunk);
15108 var state = stream._readableState;
15109
15110 if (chunk === null) {
15111 state.reading = false;
15112 onEofChunk(stream, state);
15113 } else {
15114 var er;
15115 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
15116
15117 if (er) {
15118 errorOrDestroy(stream, er);
15119 } else if (state.objectMode || chunk && chunk.length > 0) {
15120 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
15121 chunk = _uint8ArrayToBuffer(chunk);
15122 }
15123
15124 if (addToFront) {
15125 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
15126 } else if (state.ended) {
15127 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
15128 } else if (state.destroyed) {
15129 return false;
15130 } else {
15131 state.reading = false;
15132
15133 if (state.decoder && !encoding) {
15134 chunk = state.decoder.write(chunk);
15135 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
15136 } else {
15137 addChunk(stream, state, chunk, false);
15138 }
15139 }
15140 } else if (!addToFront) {
15141 state.reading = false;
15142 maybeReadMore(stream, state);
15143 }
15144 } // We can push more data if we are below the highWaterMark.
15145 // Also, if we have no data yet, we can stand some more bytes.
15146 // This is to work around cases where hwm=0, such as the repl.
15147
15148
15149 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
15150}
15151
15152function addChunk(stream, state, chunk, addToFront) {
15153 if (state.flowing && state.length === 0 && !state.sync) {
15154 state.awaitDrain = 0;
15155 stream.emit('data', chunk);
15156 } else {
15157 // update the buffer info.
15158 state.length += state.objectMode ? 1 : chunk.length;
15159 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
15160 if (state.needReadable) emitReadable(stream);
15161 }
15162
15163 maybeReadMore(stream, state);
15164}
15165
15166function chunkInvalid(state, chunk) {
15167 var er;
15168
15169 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
15170 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
15171 }
15172
15173 return er;
15174}
15175
15176Readable.prototype.isPaused = function () {
15177 return this._readableState.flowing === false;
15178}; // backwards compatibility.
15179
15180
15181Readable.prototype.setEncoding = function (enc) {
15182 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
15183 var decoder = new StringDecoder(enc);
15184 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
15185
15186 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
15187
15188 var p = this._readableState.buffer.head;
15189 var content = '';
15190
15191 while (p !== null) {
15192 content += decoder.write(p.data);
15193 p = p.next;
15194 }
15195
15196 this._readableState.buffer.clear();
15197
15198 if (content !== '') this._readableState.buffer.push(content);
15199 this._readableState.length = content.length;
15200 return this;
15201}; // Don't raise the hwm > 1GB
15202
15203
15204var MAX_HWM = 0x40000000;
15205
15206function computeNewHighWaterMark(n) {
15207 if (n >= MAX_HWM) {
15208 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
15209 n = MAX_HWM;
15210 } else {
15211 // Get the next highest power of 2 to prevent increasing hwm excessively in
15212 // tiny amounts
15213 n--;
15214 n |= n >>> 1;
15215 n |= n >>> 2;
15216 n |= n >>> 4;
15217 n |= n >>> 8;
15218 n |= n >>> 16;
15219 n++;
15220 }
15221
15222 return n;
15223} // This function is designed to be inlinable, so please take care when making
15224// changes to the function body.
15225
15226
15227function howMuchToRead(n, state) {
15228 if (n <= 0 || state.length === 0 && state.ended) return 0;
15229 if (state.objectMode) return 1;
15230
15231 if (n !== n) {
15232 // Only flow one buffer at a time
15233 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
15234 } // If we're asking for more than the current hwm, then raise the hwm.
15235
15236
15237 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
15238 if (n <= state.length) return n; // Don't have enough
15239
15240 if (!state.ended) {
15241 state.needReadable = true;
15242 return 0;
15243 }
15244
15245 return state.length;
15246} // you can override either this method, or the async _read(n) below.
15247
15248
15249Readable.prototype.read = function (n) {
15250 debug('read', n);
15251 n = parseInt(n, 10);
15252 var state = this._readableState;
15253 var nOrig = n;
15254 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
15255 // already have a bunch of data in the buffer, then just trigger
15256 // the 'readable' event and move on.
15257
15258 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
15259 debug('read: emitReadable', state.length, state.ended);
15260 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
15261 return null;
15262 }
15263
15264 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
15265
15266 if (n === 0 && state.ended) {
15267 if (state.length === 0) endReadable(this);
15268 return null;
15269 } // All the actual chunk generation logic needs to be
15270 // *below* the call to _read. The reason is that in certain
15271 // synthetic stream cases, such as passthrough streams, _read
15272 // may be a completely synchronous operation which may change
15273 // the state of the read buffer, providing enough data when
15274 // before there was *not* enough.
15275 //
15276 // So, the steps are:
15277 // 1. Figure out what the state of things will be after we do
15278 // a read from the buffer.
15279 //
15280 // 2. If that resulting state will trigger a _read, then call _read.
15281 // Note that this may be asynchronous, or synchronous. Yes, it is
15282 // deeply ugly to write APIs this way, but that still doesn't mean
15283 // that the Readable class should behave improperly, as streams are
15284 // designed to be sync/async agnostic.
15285 // Take note if the _read call is sync or async (ie, if the read call
15286 // has returned yet), so that we know whether or not it's safe to emit
15287 // 'readable' etc.
15288 //
15289 // 3. Actually pull the requested chunks out of the buffer and return.
15290 // if we need a readable event, then we need to do some reading.
15291
15292
15293 var doRead = state.needReadable;
15294 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
15295
15296 if (state.length === 0 || state.length - n < state.highWaterMark) {
15297 doRead = true;
15298 debug('length less than watermark', doRead);
15299 } // however, if we've ended, then there's no point, and if we're already
15300 // reading, then it's unnecessary.
15301
15302
15303 if (state.ended || state.reading) {
15304 doRead = false;
15305 debug('reading or ended', doRead);
15306 } else if (doRead) {
15307 debug('do read');
15308 state.reading = true;
15309 state.sync = true; // if the length is currently zero, then we *need* a readable event.
15310
15311 if (state.length === 0) state.needReadable = true; // call internal read method
15312
15313 this._read(state.highWaterMark);
15314
15315 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
15316 // and we need to re-evaluate how much data we can return to the user.
15317
15318 if (!state.reading) n = howMuchToRead(nOrig, state);
15319 }
15320
15321 var ret;
15322 if (n > 0) ret = fromList(n, state);else ret = null;
15323
15324 if (ret === null) {
15325 state.needReadable = state.length <= state.highWaterMark;
15326 n = 0;
15327 } else {
15328 state.length -= n;
15329 state.awaitDrain = 0;
15330 }
15331
15332 if (state.length === 0) {
15333 // If we have nothing in the buffer, then we want to know
15334 // as soon as we *do* get something into the buffer.
15335 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
15336
15337 if (nOrig !== n && state.ended) endReadable(this);
15338 }
15339
15340 if (ret !== null) this.emit('data', ret);
15341 return ret;
15342};
15343
15344function onEofChunk(stream, state) {
15345 debug('onEofChunk');
15346 if (state.ended) return;
15347
15348 if (state.decoder) {
15349 var chunk = state.decoder.end();
15350
15351 if (chunk && chunk.length) {
15352 state.buffer.push(chunk);
15353 state.length += state.objectMode ? 1 : chunk.length;
15354 }
15355 }
15356
15357 state.ended = true;
15358
15359 if (state.sync) {
15360 // if we are sync, wait until next tick to emit the data.
15361 // Otherwise we risk emitting data in the flow()
15362 // the readable code triggers during a read() call
15363 emitReadable(stream);
15364 } else {
15365 // emit 'readable' now to make sure it gets picked up.
15366 state.needReadable = false;
15367
15368 if (!state.emittedReadable) {
15369 state.emittedReadable = true;
15370 emitReadable_(stream);
15371 }
15372 }
15373} // Don't emit readable right away in sync mode, because this can trigger
15374// another read() call => stack overflow. This way, it might trigger
15375// a nextTick recursion warning, but that's not so bad.
15376
15377
15378function emitReadable(stream) {
15379 var state = stream._readableState;
15380 debug('emitReadable', state.needReadable, state.emittedReadable);
15381 state.needReadable = false;
15382
15383 if (!state.emittedReadable) {
15384 debug('emitReadable', state.flowing);
15385 state.emittedReadable = true;
15386 process.nextTick(emitReadable_, stream);
15387 }
15388}
15389
15390function emitReadable_(stream) {
15391 var state = stream._readableState;
15392 debug('emitReadable_', state.destroyed, state.length, state.ended);
15393
15394 if (!state.destroyed && (state.length || state.ended)) {
15395 stream.emit('readable');
15396 state.emittedReadable = false;
15397 } // The stream needs another readable event if
15398 // 1. It is not flowing, as the flow mechanism will take
15399 // care of it.
15400 // 2. It is not ended.
15401 // 3. It is below the highWaterMark, so we can schedule
15402 // another readable later.
15403
15404
15405 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
15406 flow(stream);
15407} // at this point, the user has presumably seen the 'readable' event,
15408// and called read() to consume some data. that may have triggered
15409// in turn another _read(n) call, in which case reading = true if
15410// it's in progress.
15411// However, if we're not ended, or reading, and the length < hwm,
15412// then go ahead and try to read some more preemptively.
15413
15414
15415function maybeReadMore(stream, state) {
15416 if (!state.readingMore) {
15417 state.readingMore = true;
15418 process.nextTick(maybeReadMore_, stream, state);
15419 }
15420}
15421
15422function maybeReadMore_(stream, state) {
15423 // Attempt to read more data if we should.
15424 //
15425 // The conditions for reading more data are (one of):
15426 // - Not enough data buffered (state.length < state.highWaterMark). The loop
15427 // is responsible for filling the buffer with enough data if such data
15428 // is available. If highWaterMark is 0 and we are not in the flowing mode
15429 // we should _not_ attempt to buffer any extra data. We'll get more data
15430 // when the stream consumer calls read() instead.
15431 // - No data in the buffer, and the stream is in flowing mode. In this mode
15432 // the loop below is responsible for ensuring read() is called. Failing to
15433 // call read here would abort the flow and there's no other mechanism for
15434 // continuing the flow if the stream consumer has just subscribed to the
15435 // 'data' event.
15436 //
15437 // In addition to the above conditions to keep reading data, the following
15438 // conditions prevent the data from being read:
15439 // - The stream has ended (state.ended).
15440 // - There is already a pending 'read' operation (state.reading). This is a
15441 // case where the the stream has called the implementation defined _read()
15442 // method, but they are processing the call asynchronously and have _not_
15443 // called push() with new data. In this case we skip performing more
15444 // read()s. The execution ends in this method again after the _read() ends
15445 // up calling push() with more data.
15446 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
15447 var len = state.length;
15448 debug('maybeReadMore read 0');
15449 stream.read(0);
15450 if (len === state.length) // didn't get any data, stop spinning.
15451 break;
15452 }
15453
15454 state.readingMore = false;
15455} // abstract method. to be overridden in specific implementation classes.
15456// call cb(er, data) where data is <= n in length.
15457// for virtual (non-string, non-buffer) streams, "length" is somewhat
15458// arbitrary, and perhaps not very meaningful.
15459
15460
15461Readable.prototype._read = function (n) {
15462 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
15463};
15464
15465Readable.prototype.pipe = function (dest, pipeOpts) {
15466 var src = this;
15467 var state = this._readableState;
15468
15469 switch (state.pipesCount) {
15470 case 0:
15471 state.pipes = dest;
15472 break;
15473
15474 case 1:
15475 state.pipes = [state.pipes, dest];
15476 break;
15477
15478 default:
15479 state.pipes.push(dest);
15480 break;
15481 }
15482
15483 state.pipesCount += 1;
15484 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
15485 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
15486 var endFn = doEnd ? onend : unpipe;
15487 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
15488 dest.on('unpipe', onunpipe);
15489
15490 function onunpipe(readable, unpipeInfo) {
15491 debug('onunpipe');
15492
15493 if (readable === src) {
15494 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
15495 unpipeInfo.hasUnpiped = true;
15496 cleanup();
15497 }
15498 }
15499 }
15500
15501 function onend() {
15502 debug('onend');
15503 dest.end();
15504 } // when the dest drains, it reduces the awaitDrain counter
15505 // on the source. This would be more elegant with a .once()
15506 // handler in flow(), but adding and removing repeatedly is
15507 // too slow.
15508
15509
15510 var ondrain = pipeOnDrain(src);
15511 dest.on('drain', ondrain);
15512 var cleanedUp = false;
15513
15514 function cleanup() {
15515 debug('cleanup'); // cleanup event handlers once the pipe is broken
15516
15517 dest.removeListener('close', onclose);
15518 dest.removeListener('finish', onfinish);
15519 dest.removeListener('drain', ondrain);
15520 dest.removeListener('error', onerror);
15521 dest.removeListener('unpipe', onunpipe);
15522 src.removeListener('end', onend);
15523 src.removeListener('end', unpipe);
15524 src.removeListener('data', ondata);
15525 cleanedUp = true; // if the reader is waiting for a drain event from this
15526 // specific writer, then it would cause it to never start
15527 // flowing again.
15528 // So, if this is awaiting a drain, then we just call it now.
15529 // If we don't know, then assume that we are waiting for one.
15530
15531 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
15532 }
15533
15534 src.on('data', ondata);
15535
15536 function ondata(chunk) {
15537 debug('ondata');
15538 var ret = dest.write(chunk);
15539 debug('dest.write', ret);
15540
15541 if (ret === false) {
15542 // If the user unpiped during `dest.write()`, it is possible
15543 // to get stuck in a permanently paused state if that write
15544 // also returned false.
15545 // => Check whether `dest` is still a piping destination.
15546 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
15547 debug('false write response, pause', state.awaitDrain);
15548 state.awaitDrain++;
15549 }
15550
15551 src.pause();
15552 }
15553 } // if the dest has an error, then stop piping into it.
15554 // however, don't suppress the throwing behavior for this.
15555
15556
15557 function onerror(er) {
15558 debug('onerror', er);
15559 unpipe();
15560 dest.removeListener('error', onerror);
15561 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
15562 } // Make sure our error handler is attached before userland ones.
15563
15564
15565 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
15566
15567 function onclose() {
15568 dest.removeListener('finish', onfinish);
15569 unpipe();
15570 }
15571
15572 dest.once('close', onclose);
15573
15574 function onfinish() {
15575 debug('onfinish');
15576 dest.removeListener('close', onclose);
15577 unpipe();
15578 }
15579
15580 dest.once('finish', onfinish);
15581
15582 function unpipe() {
15583 debug('unpipe');
15584 src.unpipe(dest);
15585 } // tell the dest that it's being piped to
15586
15587
15588 dest.emit('pipe', src); // start the flow if it hasn't been started already.
15589
15590 if (!state.flowing) {
15591 debug('pipe resume');
15592 src.resume();
15593 }
15594
15595 return dest;
15596};
15597
15598function pipeOnDrain(src) {
15599 return function pipeOnDrainFunctionResult() {
15600 var state = src._readableState;
15601 debug('pipeOnDrain', state.awaitDrain);
15602 if (state.awaitDrain) state.awaitDrain--;
15603
15604 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
15605 state.flowing = true;
15606 flow(src);
15607 }
15608 };
15609}
15610
15611Readable.prototype.unpipe = function (dest) {
15612 var state = this._readableState;
15613 var unpipeInfo = {
15614 hasUnpiped: false
15615 }; // if we're not piping anywhere, then do nothing.
15616
15617 if (state.pipesCount === 0) return this; // just one destination. most common case.
15618
15619 if (state.pipesCount === 1) {
15620 // passed in one, but it's not the right one.
15621 if (dest && dest !== state.pipes) return this;
15622 if (!dest) dest = state.pipes; // got a match.
15623
15624 state.pipes = null;
15625 state.pipesCount = 0;
15626 state.flowing = false;
15627 if (dest) dest.emit('unpipe', this, unpipeInfo);
15628 return this;
15629 } // slow case. multiple pipe destinations.
15630
15631
15632 if (!dest) {
15633 // remove all.
15634 var dests = state.pipes;
15635 var len = state.pipesCount;
15636 state.pipes = null;
15637 state.pipesCount = 0;
15638 state.flowing = false;
15639
15640 for (var i = 0; i < len; i++) {
15641 dests[i].emit('unpipe', this, {
15642 hasUnpiped: false
15643 });
15644 }
15645
15646 return this;
15647 } // try to find the right one.
15648
15649
15650 var index = indexOf(state.pipes, dest);
15651 if (index === -1) return this;
15652 state.pipes.splice(index, 1);
15653 state.pipesCount -= 1;
15654 if (state.pipesCount === 1) state.pipes = state.pipes[0];
15655 dest.emit('unpipe', this, unpipeInfo);
15656 return this;
15657}; // set up data events if they are asked for
15658// Ensure readable listeners eventually get something
15659
15660
15661Readable.prototype.on = function (ev, fn) {
15662 var res = Stream.prototype.on.call(this, ev, fn);
15663 var state = this._readableState;
15664
15665 if (ev === 'data') {
15666 // update readableListening so that resume() may be a no-op
15667 // a few lines down. This is needed to support once('readable').
15668 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
15669
15670 if (state.flowing !== false) this.resume();
15671 } else if (ev === 'readable') {
15672 if (!state.endEmitted && !state.readableListening) {
15673 state.readableListening = state.needReadable = true;
15674 state.flowing = false;
15675 state.emittedReadable = false;
15676 debug('on readable', state.length, state.reading);
15677
15678 if (state.length) {
15679 emitReadable(this);
15680 } else if (!state.reading) {
15681 process.nextTick(nReadingNextTick, this);
15682 }
15683 }
15684 }
15685
15686 return res;
15687};
15688
15689Readable.prototype.addListener = Readable.prototype.on;
15690
15691Readable.prototype.removeListener = function (ev, fn) {
15692 var res = Stream.prototype.removeListener.call(this, ev, fn);
15693
15694 if (ev === 'readable') {
15695 // We need to check if there is someone still listening to
15696 // readable and reset the state. However this needs to happen
15697 // after readable has been emitted but before I/O (nextTick) to
15698 // support once('readable', fn) cycles. This means that calling
15699 // resume within the same tick will have no
15700 // effect.
15701 process.nextTick(updateReadableListening, this);
15702 }
15703
15704 return res;
15705};
15706
15707Readable.prototype.removeAllListeners = function (ev) {
15708 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
15709
15710 if (ev === 'readable' || ev === undefined) {
15711 // We need to check if there is someone still listening to
15712 // readable and reset the state. However this needs to happen
15713 // after readable has been emitted but before I/O (nextTick) to
15714 // support once('readable', fn) cycles. This means that calling
15715 // resume within the same tick will have no
15716 // effect.
15717 process.nextTick(updateReadableListening, this);
15718 }
15719
15720 return res;
15721};
15722
15723function updateReadableListening(self) {
15724 var state = self._readableState;
15725 state.readableListening = self.listenerCount('readable') > 0;
15726
15727 if (state.resumeScheduled && !state.paused) {
15728 // flowing needs to be set to true now, otherwise
15729 // the upcoming resume will not flow.
15730 state.flowing = true; // crude way to check if we should resume
15731 } else if (self.listenerCount('data') > 0) {
15732 self.resume();
15733 }
15734}
15735
15736function nReadingNextTick(self) {
15737 debug('readable nexttick read 0');
15738 self.read(0);
15739} // pause() and resume() are remnants of the legacy readable stream API
15740// If the user uses them, then switch into old mode.
15741
15742
15743Readable.prototype.resume = function () {
15744 var state = this._readableState;
15745
15746 if (!state.flowing) {
15747 debug('resume'); // we flow only if there is no one listening
15748 // for readable, but we still have to call
15749 // resume()
15750
15751 state.flowing = !state.readableListening;
15752 resume(this, state);
15753 }
15754
15755 state.paused = false;
15756 return this;
15757};
15758
15759function resume(stream, state) {
15760 if (!state.resumeScheduled) {
15761 state.resumeScheduled = true;
15762 process.nextTick(resume_, stream, state);
15763 }
15764}
15765
15766function resume_(stream, state) {
15767 debug('resume', state.reading);
15768
15769 if (!state.reading) {
15770 stream.read(0);
15771 }
15772
15773 state.resumeScheduled = false;
15774 stream.emit('resume');
15775 flow(stream);
15776 if (state.flowing && !state.reading) stream.read(0);
15777}
15778
15779Readable.prototype.pause = function () {
15780 debug('call pause flowing=%j', this._readableState.flowing);
15781
15782 if (this._readableState.flowing !== false) {
15783 debug('pause');
15784 this._readableState.flowing = false;
15785 this.emit('pause');
15786 }
15787
15788 this._readableState.paused = true;
15789 return this;
15790};
15791
15792function flow(stream) {
15793 var state = stream._readableState;
15794 debug('flow', state.flowing);
15795
15796 while (state.flowing && stream.read() !== null) {
15797 ;
15798 }
15799} // wrap an old-style stream as the async data source.
15800// This is *not* part of the readable stream interface.
15801// It is an ugly unfortunate mess of history.
15802
15803
15804Readable.prototype.wrap = function (stream) {
15805 var _this = this;
15806
15807 var state = this._readableState;
15808 var paused = false;
15809 stream.on('end', function () {
15810 debug('wrapped end');
15811
15812 if (state.decoder && !state.ended) {
15813 var chunk = state.decoder.end();
15814 if (chunk && chunk.length) _this.push(chunk);
15815 }
15816
15817 _this.push(null);
15818 });
15819 stream.on('data', function (chunk) {
15820 debug('wrapped data');
15821 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
15822
15823 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
15824
15825 var ret = _this.push(chunk);
15826
15827 if (!ret) {
15828 paused = true;
15829 stream.pause();
15830 }
15831 }); // proxy all the other methods.
15832 // important when wrapping filters and duplexes.
15833
15834 for (var i in stream) {
15835 if (this[i] === undefined && typeof stream[i] === 'function') {
15836 this[i] = function methodWrap(method) {
15837 return function methodWrapReturnFunction() {
15838 return stream[method].apply(stream, arguments);
15839 };
15840 }(i);
15841 }
15842 } // proxy certain important events.
15843
15844
15845 for (var n = 0; n < kProxyEvents.length; n++) {
15846 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
15847 } // when we try to consume some more bytes, simply unpause the
15848 // underlying stream.
15849
15850
15851 this._read = function (n) {
15852 debug('wrapped _read', n);
15853
15854 if (paused) {
15855 paused = false;
15856 stream.resume();
15857 }
15858 };
15859
15860 return this;
15861};
15862
15863if (typeof Symbol === 'function') {
15864 Readable.prototype[Symbol.asyncIterator] = function () {
15865 if (createReadableStreamAsyncIterator === undefined) {
15866 createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
15867 }
15868
15869 return createReadableStreamAsyncIterator(this);
15870 };
15871}
15872
15873Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
15874 // making it explicit this property is not enumerable
15875 // because otherwise some prototype manipulation in
15876 // userland will fail
15877 enumerable: false,
15878 get: function get() {
15879 return this._readableState.highWaterMark;
15880 }
15881});
15882Object.defineProperty(Readable.prototype, 'readableBuffer', {
15883 // making it explicit this property is not enumerable
15884 // because otherwise some prototype manipulation in
15885 // userland will fail
15886 enumerable: false,
15887 get: function get() {
15888 return this._readableState && this._readableState.buffer;
15889 }
15890});
15891Object.defineProperty(Readable.prototype, 'readableFlowing', {
15892 // making it explicit this property is not enumerable
15893 // because otherwise some prototype manipulation in
15894 // userland will fail
15895 enumerable: false,
15896 get: function get() {
15897 return this._readableState.flowing;
15898 },
15899 set: function set(state) {
15900 if (this._readableState) {
15901 this._readableState.flowing = state;
15902 }
15903 }
15904}); // exposed for testing purposes only.
15905
15906Readable._fromList = fromList;
15907Object.defineProperty(Readable.prototype, 'readableLength', {
15908 // making it explicit this property is not enumerable
15909 // because otherwise some prototype manipulation in
15910 // userland will fail
15911 enumerable: false,
15912 get: function get() {
15913 return this._readableState.length;
15914 }
15915}); // Pluck off n bytes from an array of buffers.
15916// Length is the combined lengths of all the buffers in the list.
15917// This function is designed to be inlinable, so please take care when making
15918// changes to the function body.
15919
15920function fromList(n, state) {
15921 // nothing buffered
15922 if (state.length === 0) return null;
15923 var ret;
15924 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
15925 // read it all, truncate the list
15926 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
15927 state.buffer.clear();
15928 } else {
15929 // read part of list
15930 ret = state.buffer.consume(n, state.decoder);
15931 }
15932 return ret;
15933}
15934
15935function endReadable(stream) {
15936 var state = stream._readableState;
15937 debug('endReadable', state.endEmitted);
15938
15939 if (!state.endEmitted) {
15940 state.ended = true;
15941 process.nextTick(endReadableNT, state, stream);
15942 }
15943}
15944
15945function endReadableNT(state, stream) {
15946 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
15947
15948 if (!state.endEmitted && state.length === 0) {
15949 state.endEmitted = true;
15950 stream.readable = false;
15951 stream.emit('end');
15952
15953 if (state.autoDestroy) {
15954 // In case of duplex streams we need a way to detect
15955 // if the writable side is ready for autoDestroy as well
15956 var wState = stream._writableState;
15957
15958 if (!wState || wState.autoDestroy && wState.finished) {
15959 stream.destroy();
15960 }
15961 }
15962 }
15963}
15964
15965if (typeof Symbol === 'function') {
15966 Readable.from = function (iterable, opts) {
15967 if (from === undefined) {
15968 from = require('./internal/streams/from');
15969 }
15970
15971 return from(Readable, iterable, opts);
15972 };
15973}
15974
15975function indexOf(xs, x) {
15976 for (var i = 0, l = xs.length; i < l; i++) {
15977 if (xs[i] === x) return i;
15978 }
15979
15980 return -1;
15981}
15982}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15983},{"../errors":61,"./_stream_duplex":62,"./internal/streams/async_iterator":67,"./internal/streams/buffer_list":68,"./internal/streams/destroy":69,"./internal/streams/from":71,"./internal/streams/state":73,"./internal/streams/stream":74,"_process":174,"buffer":77,"events":120,"inherits":152,"string_decoder/":211,"util":33}],65:[function(require,module,exports){
15984// Copyright Joyent, Inc. and other Node contributors.
15985//
15986// Permission is hereby granted, free of charge, to any person obtaining a
15987// copy of this software and associated documentation files (the
15988// "Software"), to deal in the Software without restriction, including
15989// without limitation the rights to use, copy, modify, merge, publish,
15990// distribute, sublicense, and/or sell copies of the Software, and to permit
15991// persons to whom the Software is furnished to do so, subject to the
15992// following conditions:
15993//
15994// The above copyright notice and this permission notice shall be included
15995// in all copies or substantial portions of the Software.
15996//
15997// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15998// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15999// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16000// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16001// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16002// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16003// USE OR OTHER DEALINGS IN THE SOFTWARE.
16004// a transform stream is a readable/writable stream where you do
16005// something with the data. Sometimes it's called a "filter",
16006// but that's not a great name for it, since that implies a thing where
16007// some bits pass through, and others are simply ignored. (That would
16008// be a valid example of a transform, of course.)
16009//
16010// While the output is causally related to the input, it's not a
16011// necessarily symmetric or synchronous transformation. For example,
16012// a zlib stream might take multiple plain-text writes(), and then
16013// emit a single compressed chunk some time in the future.
16014//
16015// Here's how this works:
16016//
16017// The Transform stream has all the aspects of the readable and writable
16018// stream classes. When you write(chunk), that calls _write(chunk,cb)
16019// internally, and returns false if there's a lot of pending writes
16020// buffered up. When you call read(), that calls _read(n) until
16021// there's enough pending readable data buffered up.
16022//
16023// In a transform stream, the written data is placed in a buffer. When
16024// _read(n) is called, it transforms the queued up data, calling the
16025// buffered _write cb's as it consumes chunks. If consuming a single
16026// written chunk would result in multiple output chunks, then the first
16027// outputted bit calls the readcb, and subsequent chunks just go into
16028// the read buffer, and will cause it to emit 'readable' if necessary.
16029//
16030// This way, back-pressure is actually determined by the reading side,
16031// since _read has to be called to start processing a new chunk. However,
16032// a pathological inflate type of transform can cause excessive buffering
16033// here. For example, imagine a stream where every byte of input is
16034// interpreted as an integer from 0-255, and then results in that many
16035// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
16036// 1kb of data being output. In this case, you could write a very small
16037// amount of input, and end up with a very large amount of output. In
16038// such a pathological inflating mechanism, there'd be no way to tell
16039// the system to stop doing the transform. A single 4MB write could
16040// cause the system to run out of memory.
16041//
16042// However, even in such a pathological case, only a single written chunk
16043// would be consumed, and then the rest would wait (un-transformed) until
16044// the results of the previous transformed chunk were consumed.
16045'use strict';
16046
16047module.exports = Transform;
16048
16049var _require$codes = require('../errors').codes,
16050 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
16051 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
16052 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
16053 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
16054
16055var Duplex = require('./_stream_duplex');
16056
16057require('inherits')(Transform, Duplex);
16058
16059function afterTransform(er, data) {
16060 var ts = this._transformState;
16061 ts.transforming = false;
16062 var cb = ts.writecb;
16063
16064 if (cb === null) {
16065 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
16066 }
16067
16068 ts.writechunk = null;
16069 ts.writecb = null;
16070 if (data != null) // single equals check for both `null` and `undefined`
16071 this.push(data);
16072 cb(er);
16073 var rs = this._readableState;
16074 rs.reading = false;
16075
16076 if (rs.needReadable || rs.length < rs.highWaterMark) {
16077 this._read(rs.highWaterMark);
16078 }
16079}
16080
16081function Transform(options) {
16082 if (!(this instanceof Transform)) return new Transform(options);
16083 Duplex.call(this, options);
16084 this._transformState = {
16085 afterTransform: afterTransform.bind(this),
16086 needTransform: false,
16087 transforming: false,
16088 writecb: null,
16089 writechunk: null,
16090 writeencoding: null
16091 }; // start out asking for a readable event once data is transformed.
16092
16093 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
16094 // that Readable wants before the first _read call, so unset the
16095 // sync guard flag.
16096
16097 this._readableState.sync = false;
16098
16099 if (options) {
16100 if (typeof options.transform === 'function') this._transform = options.transform;
16101 if (typeof options.flush === 'function') this._flush = options.flush;
16102 } // When the writable side finishes, then flush out anything remaining.
16103
16104
16105 this.on('prefinish', prefinish);
16106}
16107
16108function prefinish() {
16109 var _this = this;
16110
16111 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
16112 this._flush(function (er, data) {
16113 done(_this, er, data);
16114 });
16115 } else {
16116 done(this, null, null);
16117 }
16118}
16119
16120Transform.prototype.push = function (chunk, encoding) {
16121 this._transformState.needTransform = false;
16122 return Duplex.prototype.push.call(this, chunk, encoding);
16123}; // This is the part where you do stuff!
16124// override this function in implementation classes.
16125// 'chunk' is an input chunk.
16126//
16127// Call `push(newChunk)` to pass along transformed output
16128// to the readable side. You may call 'push' zero or more times.
16129//
16130// Call `cb(err)` when you are done with this chunk. If you pass
16131// an error, then that'll put the hurt on the whole operation. If you
16132// never call cb(), then you'll never get another chunk.
16133
16134
16135Transform.prototype._transform = function (chunk, encoding, cb) {
16136 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
16137};
16138
16139Transform.prototype._write = function (chunk, encoding, cb) {
16140 var ts = this._transformState;
16141 ts.writecb = cb;
16142 ts.writechunk = chunk;
16143 ts.writeencoding = encoding;
16144
16145 if (!ts.transforming) {
16146 var rs = this._readableState;
16147 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
16148 }
16149}; // Doesn't matter what the args are here.
16150// _transform does all the work.
16151// That we got here means that the readable side wants more data.
16152
16153
16154Transform.prototype._read = function (n) {
16155 var ts = this._transformState;
16156
16157 if (ts.writechunk !== null && !ts.transforming) {
16158 ts.transforming = true;
16159
16160 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
16161 } else {
16162 // mark that we need a transform, so that any data that comes in
16163 // will get processed, now that we've asked for it.
16164 ts.needTransform = true;
16165 }
16166};
16167
16168Transform.prototype._destroy = function (err, cb) {
16169 Duplex.prototype._destroy.call(this, err, function (err2) {
16170 cb(err2);
16171 });
16172};
16173
16174function done(stream, er, data) {
16175 if (er) return stream.emit('error', er);
16176 if (data != null) // single equals check for both `null` and `undefined`
16177 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
16178 // if there's nothing in the write buffer, then that means
16179 // that nothing more will ever be provided
16180
16181 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
16182 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
16183 return stream.push(null);
16184}
16185},{"../errors":61,"./_stream_duplex":62,"inherits":152}],66:[function(require,module,exports){
16186(function (process,global){(function (){
16187// Copyright Joyent, Inc. and other Node contributors.
16188//
16189// Permission is hereby granted, free of charge, to any person obtaining a
16190// copy of this software and associated documentation files (the
16191// "Software"), to deal in the Software without restriction, including
16192// without limitation the rights to use, copy, modify, merge, publish,
16193// distribute, sublicense, and/or sell copies of the Software, and to permit
16194// persons to whom the Software is furnished to do so, subject to the
16195// following conditions:
16196//
16197// The above copyright notice and this permission notice shall be included
16198// in all copies or substantial portions of the Software.
16199//
16200// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16201// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16202// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
16203// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
16204// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16205// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
16206// USE OR OTHER DEALINGS IN THE SOFTWARE.
16207// A bit simpler than readable streams.
16208// Implement an async ._write(chunk, encoding, cb), and it'll handle all
16209// the drain event emission and buffering.
16210'use strict';
16211
16212module.exports = Writable;
16213/* <replacement> */
16214
16215function WriteReq(chunk, encoding, cb) {
16216 this.chunk = chunk;
16217 this.encoding = encoding;
16218 this.callback = cb;
16219 this.next = null;
16220} // It seems a linked list but it is not
16221// there will be only 2 of these for each stream
16222
16223
16224function CorkedRequest(state) {
16225 var _this = this;
16226
16227 this.next = null;
16228 this.entry = null;
16229
16230 this.finish = function () {
16231 onCorkedFinish(_this, state);
16232 };
16233}
16234/* </replacement> */
16235
16236/*<replacement>*/
16237
16238
16239var Duplex;
16240/*</replacement>*/
16241
16242Writable.WritableState = WritableState;
16243/*<replacement>*/
16244
16245var internalUtil = {
16246 deprecate: require('util-deprecate')
16247};
16248/*</replacement>*/
16249
16250/*<replacement>*/
16251
16252var Stream = require('./internal/streams/stream');
16253/*</replacement>*/
16254
16255
16256var Buffer = require('buffer').Buffer;
16257
16258var OurUint8Array = global.Uint8Array || function () {};
16259
16260function _uint8ArrayToBuffer(chunk) {
16261 return Buffer.from(chunk);
16262}
16263
16264function _isUint8Array(obj) {
16265 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
16266}
16267
16268var destroyImpl = require('./internal/streams/destroy');
16269
16270var _require = require('./internal/streams/state'),
16271 getHighWaterMark = _require.getHighWaterMark;
16272
16273var _require$codes = require('../errors').codes,
16274 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
16275 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
16276 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
16277 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
16278 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
16279 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
16280 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
16281 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
16282
16283var errorOrDestroy = destroyImpl.errorOrDestroy;
16284
16285require('inherits')(Writable, Stream);
16286
16287function nop() {}
16288
16289function WritableState(options, stream, isDuplex) {
16290 Duplex = Duplex || require('./_stream_duplex');
16291 options = options || {}; // Duplex streams are both readable and writable, but share
16292 // the same options object.
16293 // However, some cases require setting options to different
16294 // values for the readable and the writable sides of the duplex stream,
16295 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
16296
16297 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
16298 // contains buffers or objects.
16299
16300 this.objectMode = !!options.objectMode;
16301 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
16302 // Note: 0 is a valid value, means that we always return false if
16303 // the entire buffer is not flushed immediately on write()
16304
16305 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
16306
16307 this.finalCalled = false; // drain event flag.
16308
16309 this.needDrain = false; // at the start of calling end()
16310
16311 this.ending = false; // when end() has been called, and returned
16312
16313 this.ended = false; // when 'finish' is emitted
16314
16315 this.finished = false; // has it been destroyed
16316
16317 this.destroyed = false; // should we decode strings into buffers before passing to _write?
16318 // this is here so that some node-core streams can optimize string
16319 // handling at a lower level.
16320
16321 var noDecode = options.decodeStrings === false;
16322 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
16323 // encoding is 'binary' so we have to make this configurable.
16324 // Everything else in the universe uses 'utf8', though.
16325
16326 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
16327 // of how much we're waiting to get pushed to some underlying
16328 // socket or file.
16329
16330 this.length = 0; // a flag to see when we're in the middle of a write.
16331
16332 this.writing = false; // when true all writes will be buffered until .uncork() call
16333
16334 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
16335 // or on a later tick. We set this to true at first, because any
16336 // actions that shouldn't happen until "later" should generally also
16337 // not happen before the first write call.
16338
16339 this.sync = true; // a flag to know if we're processing previously buffered items, which
16340 // may call the _write() callback in the same tick, so that we don't
16341 // end up in an overlapped onwrite situation.
16342
16343 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
16344
16345 this.onwrite = function (er) {
16346 onwrite(stream, er);
16347 }; // the callback that the user supplies to write(chunk,encoding,cb)
16348
16349
16350 this.writecb = null; // the amount that is being written when _write is called.
16351
16352 this.writelen = 0;
16353 this.bufferedRequest = null;
16354 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
16355 // this must be 0 before 'finish' can be emitted
16356
16357 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
16358 // This is relevant for synchronous Transform streams
16359
16360 this.prefinished = false; // True if the error was already emitted and should not be thrown again
16361
16362 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
16363
16364 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
16365
16366 this.autoDestroy = !!options.autoDestroy; // count buffered requests
16367
16368 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
16369 // one allocated and free to use, and we maintain at most two
16370
16371 this.corkedRequestsFree = new CorkedRequest(this);
16372}
16373
16374WritableState.prototype.getBuffer = function getBuffer() {
16375 var current = this.bufferedRequest;
16376 var out = [];
16377
16378 while (current) {
16379 out.push(current);
16380 current = current.next;
16381 }
16382
16383 return out;
16384};
16385
16386(function () {
16387 try {
16388 Object.defineProperty(WritableState.prototype, 'buffer', {
16389 get: internalUtil.deprecate(function writableStateBufferGetter() {
16390 return this.getBuffer();
16391 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
16392 });
16393 } catch (_) {}
16394})(); // Test _writableState for inheritance to account for Duplex streams,
16395// whose prototype chain only points to Readable.
16396
16397
16398var realHasInstance;
16399
16400if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
16401 realHasInstance = Function.prototype[Symbol.hasInstance];
16402 Object.defineProperty(Writable, Symbol.hasInstance, {
16403 value: function value(object) {
16404 if (realHasInstance.call(this, object)) return true;
16405 if (this !== Writable) return false;
16406 return object && object._writableState instanceof WritableState;
16407 }
16408 });
16409} else {
16410 realHasInstance = function realHasInstance(object) {
16411 return object instanceof this;
16412 };
16413}
16414
16415function Writable(options) {
16416 Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
16417 // `realHasInstance` is necessary because using plain `instanceof`
16418 // would return false, as no `_writableState` property is attached.
16419 // Trying to use the custom `instanceof` for Writable here will also break the
16420 // Node.js LazyTransform implementation, which has a non-trivial getter for
16421 // `_writableState` that would lead to infinite recursion.
16422 // Checking for a Stream.Duplex instance is faster here instead of inside
16423 // the WritableState constructor, at least with V8 6.5
16424
16425 var isDuplex = this instanceof Duplex;
16426 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
16427 this._writableState = new WritableState(options, this, isDuplex); // legacy.
16428
16429 this.writable = true;
16430
16431 if (options) {
16432 if (typeof options.write === 'function') this._write = options.write;
16433 if (typeof options.writev === 'function') this._writev = options.writev;
16434 if (typeof options.destroy === 'function') this._destroy = options.destroy;
16435 if (typeof options.final === 'function') this._final = options.final;
16436 }
16437
16438 Stream.call(this);
16439} // Otherwise people can pipe Writable streams, which is just wrong.
16440
16441
16442Writable.prototype.pipe = function () {
16443 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
16444};
16445
16446function writeAfterEnd(stream, cb) {
16447 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
16448
16449 errorOrDestroy(stream, er);
16450 process.nextTick(cb, er);
16451} // Checks that a user-supplied chunk is valid, especially for the particular
16452// mode the stream is in. Currently this means that `null` is never accepted
16453// and undefined/non-string values are only allowed in object mode.
16454
16455
16456function validChunk(stream, state, chunk, cb) {
16457 var er;
16458
16459 if (chunk === null) {
16460 er = new ERR_STREAM_NULL_VALUES();
16461 } else if (typeof chunk !== 'string' && !state.objectMode) {
16462 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
16463 }
16464
16465 if (er) {
16466 errorOrDestroy(stream, er);
16467 process.nextTick(cb, er);
16468 return false;
16469 }
16470
16471 return true;
16472}
16473
16474Writable.prototype.write = function (chunk, encoding, cb) {
16475 var state = this._writableState;
16476 var ret = false;
16477
16478 var isBuf = !state.objectMode && _isUint8Array(chunk);
16479
16480 if (isBuf && !Buffer.isBuffer(chunk)) {
16481 chunk = _uint8ArrayToBuffer(chunk);
16482 }
16483
16484 if (typeof encoding === 'function') {
16485 cb = encoding;
16486 encoding = null;
16487 }
16488
16489 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
16490 if (typeof cb !== 'function') cb = nop;
16491 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
16492 state.pendingcb++;
16493 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
16494 }
16495 return ret;
16496};
16497
16498Writable.prototype.cork = function () {
16499 this._writableState.corked++;
16500};
16501
16502Writable.prototype.uncork = function () {
16503 var state = this._writableState;
16504
16505 if (state.corked) {
16506 state.corked--;
16507 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
16508 }
16509};
16510
16511Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
16512 // node::ParseEncoding() requires lower case.
16513 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
16514 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
16515 this._writableState.defaultEncoding = encoding;
16516 return this;
16517};
16518
16519Object.defineProperty(Writable.prototype, 'writableBuffer', {
16520 // making it explicit this property is not enumerable
16521 // because otherwise some prototype manipulation in
16522 // userland will fail
16523 enumerable: false,
16524 get: function get() {
16525 return this._writableState && this._writableState.getBuffer();
16526 }
16527});
16528
16529function decodeChunk(state, chunk, encoding) {
16530 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
16531 chunk = Buffer.from(chunk, encoding);
16532 }
16533
16534 return chunk;
16535}
16536
16537Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
16538 // making it explicit this property is not enumerable
16539 // because otherwise some prototype manipulation in
16540 // userland will fail
16541 enumerable: false,
16542 get: function get() {
16543 return this._writableState.highWaterMark;
16544 }
16545}); // if we're already writing something, then just put this
16546// in the queue, and wait our turn. Otherwise, call _write
16547// If we return false, then we need a drain event, so set that flag.
16548
16549function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
16550 if (!isBuf) {
16551 var newChunk = decodeChunk(state, chunk, encoding);
16552
16553 if (chunk !== newChunk) {
16554 isBuf = true;
16555 encoding = 'buffer';
16556 chunk = newChunk;
16557 }
16558 }
16559
16560 var len = state.objectMode ? 1 : chunk.length;
16561 state.length += len;
16562 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
16563
16564 if (!ret) state.needDrain = true;
16565
16566 if (state.writing || state.corked) {
16567 var last = state.lastBufferedRequest;
16568 state.lastBufferedRequest = {
16569 chunk: chunk,
16570 encoding: encoding,
16571 isBuf: isBuf,
16572 callback: cb,
16573 next: null
16574 };
16575
16576 if (last) {
16577 last.next = state.lastBufferedRequest;
16578 } else {
16579 state.bufferedRequest = state.lastBufferedRequest;
16580 }
16581
16582 state.bufferedRequestCount += 1;
16583 } else {
16584 doWrite(stream, state, false, len, chunk, encoding, cb);
16585 }
16586
16587 return ret;
16588}
16589
16590function doWrite(stream, state, writev, len, chunk, encoding, cb) {
16591 state.writelen = len;
16592 state.writecb = cb;
16593 state.writing = true;
16594 state.sync = true;
16595 if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
16596 state.sync = false;
16597}
16598
16599function onwriteError(stream, state, sync, er, cb) {
16600 --state.pendingcb;
16601
16602 if (sync) {
16603 // defer the callback if we are being called synchronously
16604 // to avoid piling up things on the stack
16605 process.nextTick(cb, er); // this can emit finish, and it will always happen
16606 // after error
16607
16608 process.nextTick(finishMaybe, stream, state);
16609 stream._writableState.errorEmitted = true;
16610 errorOrDestroy(stream, er);
16611 } else {
16612 // the caller expect this to happen before if
16613 // it is async
16614 cb(er);
16615 stream._writableState.errorEmitted = true;
16616 errorOrDestroy(stream, er); // this can emit finish, but finish must
16617 // always follow error
16618
16619 finishMaybe(stream, state);
16620 }
16621}
16622
16623function onwriteStateUpdate(state) {
16624 state.writing = false;
16625 state.writecb = null;
16626 state.length -= state.writelen;
16627 state.writelen = 0;
16628}
16629
16630function onwrite(stream, er) {
16631 var state = stream._writableState;
16632 var sync = state.sync;
16633 var cb = state.writecb;
16634 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
16635 onwriteStateUpdate(state);
16636 if (er) onwriteError(stream, state, sync, er, cb);else {
16637 // Check if we're actually ready to finish, but don't emit yet
16638 var finished = needFinish(state) || stream.destroyed;
16639
16640 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
16641 clearBuffer(stream, state);
16642 }
16643
16644 if (sync) {
16645 process.nextTick(afterWrite, stream, state, finished, cb);
16646 } else {
16647 afterWrite(stream, state, finished, cb);
16648 }
16649 }
16650}
16651
16652function afterWrite(stream, state, finished, cb) {
16653 if (!finished) onwriteDrain(stream, state);
16654 state.pendingcb--;
16655 cb();
16656 finishMaybe(stream, state);
16657} // Must force callback to be called on nextTick, so that we don't
16658// emit 'drain' before the write() consumer gets the 'false' return
16659// value, and has a chance to attach a 'drain' listener.
16660
16661
16662function onwriteDrain(stream, state) {
16663 if (state.length === 0 && state.needDrain) {
16664 state.needDrain = false;
16665 stream.emit('drain');
16666 }
16667} // if there's something in the buffer waiting, then process it
16668
16669
16670function clearBuffer(stream, state) {
16671 state.bufferProcessing = true;
16672 var entry = state.bufferedRequest;
16673
16674 if (stream._writev && entry && entry.next) {
16675 // Fast case, write everything using _writev()
16676 var l = state.bufferedRequestCount;
16677 var buffer = new Array(l);
16678 var holder = state.corkedRequestsFree;
16679 holder.entry = entry;
16680 var count = 0;
16681 var allBuffers = true;
16682
16683 while (entry) {
16684 buffer[count] = entry;
16685 if (!entry.isBuf) allBuffers = false;
16686 entry = entry.next;
16687 count += 1;
16688 }
16689
16690 buffer.allBuffers = allBuffers;
16691 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
16692 // as the hot path ends with doWrite
16693
16694 state.pendingcb++;
16695 state.lastBufferedRequest = null;
16696
16697 if (holder.next) {
16698 state.corkedRequestsFree = holder.next;
16699 holder.next = null;
16700 } else {
16701 state.corkedRequestsFree = new CorkedRequest(state);
16702 }
16703
16704 state.bufferedRequestCount = 0;
16705 } else {
16706 // Slow case, write chunks one-by-one
16707 while (entry) {
16708 var chunk = entry.chunk;
16709 var encoding = entry.encoding;
16710 var cb = entry.callback;
16711 var len = state.objectMode ? 1 : chunk.length;
16712 doWrite(stream, state, false, len, chunk, encoding, cb);
16713 entry = entry.next;
16714 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
16715 // it means that we need to wait until it does.
16716 // also, that means that the chunk and cb are currently
16717 // being processed, so move the buffer counter past them.
16718
16719 if (state.writing) {
16720 break;
16721 }
16722 }
16723
16724 if (entry === null) state.lastBufferedRequest = null;
16725 }
16726
16727 state.bufferedRequest = entry;
16728 state.bufferProcessing = false;
16729}
16730
16731Writable.prototype._write = function (chunk, encoding, cb) {
16732 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
16733};
16734
16735Writable.prototype._writev = null;
16736
16737Writable.prototype.end = function (chunk, encoding, cb) {
16738 var state = this._writableState;
16739
16740 if (typeof chunk === 'function') {
16741 cb = chunk;
16742 chunk = null;
16743 encoding = null;
16744 } else if (typeof encoding === 'function') {
16745 cb = encoding;
16746 encoding = null;
16747 }
16748
16749 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
16750
16751 if (state.corked) {
16752 state.corked = 1;
16753 this.uncork();
16754 } // ignore unnecessary end() calls.
16755
16756
16757 if (!state.ending) endWritable(this, state, cb);
16758 return this;
16759};
16760
16761Object.defineProperty(Writable.prototype, 'writableLength', {
16762 // making it explicit this property is not enumerable
16763 // because otherwise some prototype manipulation in
16764 // userland will fail
16765 enumerable: false,
16766 get: function get() {
16767 return this._writableState.length;
16768 }
16769});
16770
16771function needFinish(state) {
16772 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
16773}
16774
16775function callFinal(stream, state) {
16776 stream._final(function (err) {
16777 state.pendingcb--;
16778
16779 if (err) {
16780 errorOrDestroy(stream, err);
16781 }
16782
16783 state.prefinished = true;
16784 stream.emit('prefinish');
16785 finishMaybe(stream, state);
16786 });
16787}
16788
16789function prefinish(stream, state) {
16790 if (!state.prefinished && !state.finalCalled) {
16791 if (typeof stream._final === 'function' && !state.destroyed) {
16792 state.pendingcb++;
16793 state.finalCalled = true;
16794 process.nextTick(callFinal, stream, state);
16795 } else {
16796 state.prefinished = true;
16797 stream.emit('prefinish');
16798 }
16799 }
16800}
16801
16802function finishMaybe(stream, state) {
16803 var need = needFinish(state);
16804
16805 if (need) {
16806 prefinish(stream, state);
16807
16808 if (state.pendingcb === 0) {
16809 state.finished = true;
16810 stream.emit('finish');
16811
16812 if (state.autoDestroy) {
16813 // In case of duplex streams we need a way to detect
16814 // if the readable side is ready for autoDestroy as well
16815 var rState = stream._readableState;
16816
16817 if (!rState || rState.autoDestroy && rState.endEmitted) {
16818 stream.destroy();
16819 }
16820 }
16821 }
16822 }
16823
16824 return need;
16825}
16826
16827function endWritable(stream, state, cb) {
16828 state.ending = true;
16829 finishMaybe(stream, state);
16830
16831 if (cb) {
16832 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
16833 }
16834
16835 state.ended = true;
16836 stream.writable = false;
16837}
16838
16839function onCorkedFinish(corkReq, state, err) {
16840 var entry = corkReq.entry;
16841 corkReq.entry = null;
16842
16843 while (entry) {
16844 var cb = entry.callback;
16845 state.pendingcb--;
16846 cb(err);
16847 entry = entry.next;
16848 } // reuse the free corkReq.
16849
16850
16851 state.corkedRequestsFree.next = corkReq;
16852}
16853
16854Object.defineProperty(Writable.prototype, 'destroyed', {
16855 // making it explicit this property is not enumerable
16856 // because otherwise some prototype manipulation in
16857 // userland will fail
16858 enumerable: false,
16859 get: function get() {
16860 if (this._writableState === undefined) {
16861 return false;
16862 }
16863
16864 return this._writableState.destroyed;
16865 },
16866 set: function set(value) {
16867 // we ignore the value if the stream
16868 // has not been initialized yet
16869 if (!this._writableState) {
16870 return;
16871 } // backward compatibility, the user is explicitly
16872 // managing destroyed
16873
16874
16875 this._writableState.destroyed = value;
16876 }
16877});
16878Writable.prototype.destroy = destroyImpl.destroy;
16879Writable.prototype._undestroy = destroyImpl.undestroy;
16880
16881Writable.prototype._destroy = function (err, cb) {
16882 cb(err);
16883};
16884}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16885},{"../errors":61,"./_stream_duplex":62,"./internal/streams/destroy":69,"./internal/streams/state":73,"./internal/streams/stream":74,"_process":174,"buffer":77,"inherits":152,"util-deprecate":213}],67:[function(require,module,exports){
16886(function (process){(function (){
16887'use strict';
16888
16889var _Object$setPrototypeO;
16890
16891function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
16892
16893var finished = require('./end-of-stream');
16894
16895var kLastResolve = Symbol('lastResolve');
16896var kLastReject = Symbol('lastReject');
16897var kError = Symbol('error');
16898var kEnded = Symbol('ended');
16899var kLastPromise = Symbol('lastPromise');
16900var kHandlePromise = Symbol('handlePromise');
16901var kStream = Symbol('stream');
16902
16903function createIterResult(value, done) {
16904 return {
16905 value: value,
16906 done: done
16907 };
16908}
16909
16910function readAndResolve(iter) {
16911 var resolve = iter[kLastResolve];
16912
16913 if (resolve !== null) {
16914 var data = iter[kStream].read(); // we defer if data is null
16915 // we can be expecting either 'end' or
16916 // 'error'
16917
16918 if (data !== null) {
16919 iter[kLastPromise] = null;
16920 iter[kLastResolve] = null;
16921 iter[kLastReject] = null;
16922 resolve(createIterResult(data, false));
16923 }
16924 }
16925}
16926
16927function onReadable(iter) {
16928 // we wait for the next tick, because it might
16929 // emit an error with process.nextTick
16930 process.nextTick(readAndResolve, iter);
16931}
16932
16933function wrapForNext(lastPromise, iter) {
16934 return function (resolve, reject) {
16935 lastPromise.then(function () {
16936 if (iter[kEnded]) {
16937 resolve(createIterResult(undefined, true));
16938 return;
16939 }
16940
16941 iter[kHandlePromise](resolve, reject);
16942 }, reject);
16943 };
16944}
16945
16946var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
16947var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
16948 get stream() {
16949 return this[kStream];
16950 },
16951
16952 next: function next() {
16953 var _this = this;
16954
16955 // if we have detected an error in the meanwhile
16956 // reject straight away
16957 var error = this[kError];
16958
16959 if (error !== null) {
16960 return Promise.reject(error);
16961 }
16962
16963 if (this[kEnded]) {
16964 return Promise.resolve(createIterResult(undefined, true));
16965 }
16966
16967 if (this[kStream].destroyed) {
16968 // We need to defer via nextTick because if .destroy(err) is
16969 // called, the error will be emitted via nextTick, and
16970 // we cannot guarantee that there is no error lingering around
16971 // waiting to be emitted.
16972 return new Promise(function (resolve, reject) {
16973 process.nextTick(function () {
16974 if (_this[kError]) {
16975 reject(_this[kError]);
16976 } else {
16977 resolve(createIterResult(undefined, true));
16978 }
16979 });
16980 });
16981 } // if we have multiple next() calls
16982 // we will wait for the previous Promise to finish
16983 // this logic is optimized to support for await loops,
16984 // where next() is only called once at a time
16985
16986
16987 var lastPromise = this[kLastPromise];
16988 var promise;
16989
16990 if (lastPromise) {
16991 promise = new Promise(wrapForNext(lastPromise, this));
16992 } else {
16993 // fast path needed to support multiple this.push()
16994 // without triggering the next() queue
16995 var data = this[kStream].read();
16996
16997 if (data !== null) {
16998 return Promise.resolve(createIterResult(data, false));
16999 }
17000
17001 promise = new Promise(this[kHandlePromise]);
17002 }
17003
17004 this[kLastPromise] = promise;
17005 return promise;
17006 }
17007}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
17008 return this;
17009}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
17010 var _this2 = this;
17011
17012 // destroy(err, cb) is a private API
17013 // we can guarantee we have that here, because we control the
17014 // Readable class this is attached to
17015 return new Promise(function (resolve, reject) {
17016 _this2[kStream].destroy(null, function (err) {
17017 if (err) {
17018 reject(err);
17019 return;
17020 }
17021
17022 resolve(createIterResult(undefined, true));
17023 });
17024 });
17025}), _Object$setPrototypeO), AsyncIteratorPrototype);
17026
17027var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
17028 var _Object$create;
17029
17030 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
17031 value: stream,
17032 writable: true
17033 }), _defineProperty(_Object$create, kLastResolve, {
17034 value: null,
17035 writable: true
17036 }), _defineProperty(_Object$create, kLastReject, {
17037 value: null,
17038 writable: true
17039 }), _defineProperty(_Object$create, kError, {
17040 value: null,
17041 writable: true
17042 }), _defineProperty(_Object$create, kEnded, {
17043 value: stream._readableState.endEmitted,
17044 writable: true
17045 }), _defineProperty(_Object$create, kHandlePromise, {
17046 value: function value(resolve, reject) {
17047 var data = iterator[kStream].read();
17048
17049 if (data) {
17050 iterator[kLastPromise] = null;
17051 iterator[kLastResolve] = null;
17052 iterator[kLastReject] = null;
17053 resolve(createIterResult(data, false));
17054 } else {
17055 iterator[kLastResolve] = resolve;
17056 iterator[kLastReject] = reject;
17057 }
17058 },
17059 writable: true
17060 }), _Object$create));
17061 iterator[kLastPromise] = null;
17062 finished(stream, function (err) {
17063 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
17064 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
17065 // returned by next() and store the error
17066
17067 if (reject !== null) {
17068 iterator[kLastPromise] = null;
17069 iterator[kLastResolve] = null;
17070 iterator[kLastReject] = null;
17071 reject(err);
17072 }
17073
17074 iterator[kError] = err;
17075 return;
17076 }
17077
17078 var resolve = iterator[kLastResolve];
17079
17080 if (resolve !== null) {
17081 iterator[kLastPromise] = null;
17082 iterator[kLastResolve] = null;
17083 iterator[kLastReject] = null;
17084 resolve(createIterResult(undefined, true));
17085 }
17086
17087 iterator[kEnded] = true;
17088 });
17089 stream.on('readable', onReadable.bind(null, iterator));
17090 return iterator;
17091};
17092
17093module.exports = createReadableStreamAsyncIterator;
17094}).call(this)}).call(this,require('_process'))
17095},{"./end-of-stream":70,"_process":174}],68:[function(require,module,exports){
17096'use strict';
17097
17098function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
17099
17100function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
17101
17102function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
17103
17104function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17105
17106function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
17107
17108function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
17109
17110var _require = require('buffer'),
17111 Buffer = _require.Buffer;
17112
17113var _require2 = require('util'),
17114 inspect = _require2.inspect;
17115
17116var custom = inspect && inspect.custom || 'inspect';
17117
17118function copyBuffer(src, target, offset) {
17119 Buffer.prototype.copy.call(src, target, offset);
17120}
17121
17122module.exports =
17123/*#__PURE__*/
17124function () {
17125 function BufferList() {
17126 _classCallCheck(this, BufferList);
17127
17128 this.head = null;
17129 this.tail = null;
17130 this.length = 0;
17131 }
17132
17133 _createClass(BufferList, [{
17134 key: "push",
17135 value: function push(v) {
17136 var entry = {
17137 data: v,
17138 next: null
17139 };
17140 if (this.length > 0) this.tail.next = entry;else this.head = entry;
17141 this.tail = entry;
17142 ++this.length;
17143 }
17144 }, {
17145 key: "unshift",
17146 value: function unshift(v) {
17147 var entry = {
17148 data: v,
17149 next: this.head
17150 };
17151 if (this.length === 0) this.tail = entry;
17152 this.head = entry;
17153 ++this.length;
17154 }
17155 }, {
17156 key: "shift",
17157 value: function shift() {
17158 if (this.length === 0) return;
17159 var ret = this.head.data;
17160 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
17161 --this.length;
17162 return ret;
17163 }
17164 }, {
17165 key: "clear",
17166 value: function clear() {
17167 this.head = this.tail = null;
17168 this.length = 0;
17169 }
17170 }, {
17171 key: "join",
17172 value: function join(s) {
17173 if (this.length === 0) return '';
17174 var p = this.head;
17175 var ret = '' + p.data;
17176
17177 while (p = p.next) {
17178 ret += s + p.data;
17179 }
17180
17181 return ret;
17182 }
17183 }, {
17184 key: "concat",
17185 value: function concat(n) {
17186 if (this.length === 0) return Buffer.alloc(0);
17187 var ret = Buffer.allocUnsafe(n >>> 0);
17188 var p = this.head;
17189 var i = 0;
17190
17191 while (p) {
17192 copyBuffer(p.data, ret, i);
17193 i += p.data.length;
17194 p = p.next;
17195 }
17196
17197 return ret;
17198 } // Consumes a specified amount of bytes or characters from the buffered data.
17199
17200 }, {
17201 key: "consume",
17202 value: function consume(n, hasStrings) {
17203 var ret;
17204
17205 if (n < this.head.data.length) {
17206 // `slice` is the same for buffers and strings.
17207 ret = this.head.data.slice(0, n);
17208 this.head.data = this.head.data.slice(n);
17209 } else if (n === this.head.data.length) {
17210 // First chunk is a perfect match.
17211 ret = this.shift();
17212 } else {
17213 // Result spans more than one buffer.
17214 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
17215 }
17216
17217 return ret;
17218 }
17219 }, {
17220 key: "first",
17221 value: function first() {
17222 return this.head.data;
17223 } // Consumes a specified amount of characters from the buffered data.
17224
17225 }, {
17226 key: "_getString",
17227 value: function _getString(n) {
17228 var p = this.head;
17229 var c = 1;
17230 var ret = p.data;
17231 n -= ret.length;
17232
17233 while (p = p.next) {
17234 var str = p.data;
17235 var nb = n > str.length ? str.length : n;
17236 if (nb === str.length) ret += str;else ret += str.slice(0, n);
17237 n -= nb;
17238
17239 if (n === 0) {
17240 if (nb === str.length) {
17241 ++c;
17242 if (p.next) this.head = p.next;else this.head = this.tail = null;
17243 } else {
17244 this.head = p;
17245 p.data = str.slice(nb);
17246 }
17247
17248 break;
17249 }
17250
17251 ++c;
17252 }
17253
17254 this.length -= c;
17255 return ret;
17256 } // Consumes a specified amount of bytes from the buffered data.
17257
17258 }, {
17259 key: "_getBuffer",
17260 value: function _getBuffer(n) {
17261 var ret = Buffer.allocUnsafe(n);
17262 var p = this.head;
17263 var c = 1;
17264 p.data.copy(ret);
17265 n -= p.data.length;
17266
17267 while (p = p.next) {
17268 var buf = p.data;
17269 var nb = n > buf.length ? buf.length : n;
17270 buf.copy(ret, ret.length - n, 0, nb);
17271 n -= nb;
17272
17273 if (n === 0) {
17274 if (nb === buf.length) {
17275 ++c;
17276 if (p.next) this.head = p.next;else this.head = this.tail = null;
17277 } else {
17278 this.head = p;
17279 p.data = buf.slice(nb);
17280 }
17281
17282 break;
17283 }
17284
17285 ++c;
17286 }
17287
17288 this.length -= c;
17289 return ret;
17290 } // Make sure the linked list only shows the minimal necessary information.
17291
17292 }, {
17293 key: custom,
17294 value: function value(_, options) {
17295 return inspect(this, _objectSpread({}, options, {
17296 // Only inspect one level.
17297 depth: 0,
17298 // It should not recurse.
17299 customInspect: false
17300 }));
17301 }
17302 }]);
17303
17304 return BufferList;
17305}();
17306},{"buffer":77,"util":33}],69:[function(require,module,exports){
17307(function (process){(function (){
17308'use strict'; // undocumented cb() API, needed for core, not for public API
17309
17310function destroy(err, cb) {
17311 var _this = this;
17312
17313 var readableDestroyed = this._readableState && this._readableState.destroyed;
17314 var writableDestroyed = this._writableState && this._writableState.destroyed;
17315
17316 if (readableDestroyed || writableDestroyed) {
17317 if (cb) {
17318 cb(err);
17319 } else if (err) {
17320 if (!this._writableState) {
17321 process.nextTick(emitErrorNT, this, err);
17322 } else if (!this._writableState.errorEmitted) {
17323 this._writableState.errorEmitted = true;
17324 process.nextTick(emitErrorNT, this, err);
17325 }
17326 }
17327
17328 return this;
17329 } // we set destroyed to true before firing error callbacks in order
17330 // to make it re-entrance safe in case destroy() is called within callbacks
17331
17332
17333 if (this._readableState) {
17334 this._readableState.destroyed = true;
17335 } // if this is a duplex stream mark the writable part as destroyed as well
17336
17337
17338 if (this._writableState) {
17339 this._writableState.destroyed = true;
17340 }
17341
17342 this._destroy(err || null, function (err) {
17343 if (!cb && err) {
17344 if (!_this._writableState) {
17345 process.nextTick(emitErrorAndCloseNT, _this, err);
17346 } else if (!_this._writableState.errorEmitted) {
17347 _this._writableState.errorEmitted = true;
17348 process.nextTick(emitErrorAndCloseNT, _this, err);
17349 } else {
17350 process.nextTick(emitCloseNT, _this);
17351 }
17352 } else if (cb) {
17353 process.nextTick(emitCloseNT, _this);
17354 cb(err);
17355 } else {
17356 process.nextTick(emitCloseNT, _this);
17357 }
17358 });
17359
17360 return this;
17361}
17362
17363function emitErrorAndCloseNT(self, err) {
17364 emitErrorNT(self, err);
17365 emitCloseNT(self);
17366}
17367
17368function emitCloseNT(self) {
17369 if (self._writableState && !self._writableState.emitClose) return;
17370 if (self._readableState && !self._readableState.emitClose) return;
17371 self.emit('close');
17372}
17373
17374function undestroy() {
17375 if (this._readableState) {
17376 this._readableState.destroyed = false;
17377 this._readableState.reading = false;
17378 this._readableState.ended = false;
17379 this._readableState.endEmitted = false;
17380 }
17381
17382 if (this._writableState) {
17383 this._writableState.destroyed = false;
17384 this._writableState.ended = false;
17385 this._writableState.ending = false;
17386 this._writableState.finalCalled = false;
17387 this._writableState.prefinished = false;
17388 this._writableState.finished = false;
17389 this._writableState.errorEmitted = false;
17390 }
17391}
17392
17393function emitErrorNT(self, err) {
17394 self.emit('error', err);
17395}
17396
17397function errorOrDestroy(stream, err) {
17398 // We have tests that rely on errors being emitted
17399 // in the same tick, so changing this is semver major.
17400 // For now when you opt-in to autoDestroy we allow
17401 // the error to be emitted nextTick. In a future
17402 // semver major update we should change the default to this.
17403 var rState = stream._readableState;
17404 var wState = stream._writableState;
17405 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
17406}
17407
17408module.exports = {
17409 destroy: destroy,
17410 undestroy: undestroy,
17411 errorOrDestroy: errorOrDestroy
17412};
17413}).call(this)}).call(this,require('_process'))
17414},{"_process":174}],70:[function(require,module,exports){
17415// Ported from https://github.com/mafintosh/end-of-stream with
17416// permission from the author, Mathias Buus (@mafintosh).
17417'use strict';
17418
17419var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
17420
17421function once(callback) {
17422 var called = false;
17423 return function () {
17424 if (called) return;
17425 called = true;
17426
17427 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
17428 args[_key] = arguments[_key];
17429 }
17430
17431 callback.apply(this, args);
17432 };
17433}
17434
17435function noop() {}
17436
17437function isRequest(stream) {
17438 return stream.setHeader && typeof stream.abort === 'function';
17439}
17440
17441function eos(stream, opts, callback) {
17442 if (typeof opts === 'function') return eos(stream, null, opts);
17443 if (!opts) opts = {};
17444 callback = once(callback || noop);
17445 var readable = opts.readable || opts.readable !== false && stream.readable;
17446 var writable = opts.writable || opts.writable !== false && stream.writable;
17447
17448 var onlegacyfinish = function onlegacyfinish() {
17449 if (!stream.writable) onfinish();
17450 };
17451
17452 var writableEnded = stream._writableState && stream._writableState.finished;
17453
17454 var onfinish = function onfinish() {
17455 writable = false;
17456 writableEnded = true;
17457 if (!readable) callback.call(stream);
17458 };
17459
17460 var readableEnded = stream._readableState && stream._readableState.endEmitted;
17461
17462 var onend = function onend() {
17463 readable = false;
17464 readableEnded = true;
17465 if (!writable) callback.call(stream);
17466 };
17467
17468 var onerror = function onerror(err) {
17469 callback.call(stream, err);
17470 };
17471
17472 var onclose = function onclose() {
17473 var err;
17474
17475 if (readable && !readableEnded) {
17476 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
17477 return callback.call(stream, err);
17478 }
17479
17480 if (writable && !writableEnded) {
17481 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
17482 return callback.call(stream, err);
17483 }
17484 };
17485
17486 var onrequest = function onrequest() {
17487 stream.req.on('finish', onfinish);
17488 };
17489
17490 if (isRequest(stream)) {
17491 stream.on('complete', onfinish);
17492 stream.on('abort', onclose);
17493 if (stream.req) onrequest();else stream.on('request', onrequest);
17494 } else if (writable && !stream._writableState) {
17495 // legacy streams
17496 stream.on('end', onlegacyfinish);
17497 stream.on('close', onlegacyfinish);
17498 }
17499
17500 stream.on('end', onend);
17501 stream.on('finish', onfinish);
17502 if (opts.error !== false) stream.on('error', onerror);
17503 stream.on('close', onclose);
17504 return function () {
17505 stream.removeListener('complete', onfinish);
17506 stream.removeListener('abort', onclose);
17507 stream.removeListener('request', onrequest);
17508 if (stream.req) stream.req.removeListener('finish', onfinish);
17509 stream.removeListener('end', onlegacyfinish);
17510 stream.removeListener('close', onlegacyfinish);
17511 stream.removeListener('finish', onfinish);
17512 stream.removeListener('end', onend);
17513 stream.removeListener('error', onerror);
17514 stream.removeListener('close', onclose);
17515 };
17516}
17517
17518module.exports = eos;
17519},{"../../../errors":61}],71:[function(require,module,exports){
17520module.exports = function () {
17521 throw new Error('Readable.from is not available in the browser')
17522};
17523
17524},{}],72:[function(require,module,exports){
17525// Ported from https://github.com/mafintosh/pump with
17526// permission from the author, Mathias Buus (@mafintosh).
17527'use strict';
17528
17529var eos;
17530
17531function once(callback) {
17532 var called = false;
17533 return function () {
17534 if (called) return;
17535 called = true;
17536 callback.apply(void 0, arguments);
17537 };
17538}
17539
17540var _require$codes = require('../../../errors').codes,
17541 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
17542 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
17543
17544function noop(err) {
17545 // Rethrow the error if it exists to avoid swallowing it
17546 if (err) throw err;
17547}
17548
17549function isRequest(stream) {
17550 return stream.setHeader && typeof stream.abort === 'function';
17551}
17552
17553function destroyer(stream, reading, writing, callback) {
17554 callback = once(callback);
17555 var closed = false;
17556 stream.on('close', function () {
17557 closed = true;
17558 });
17559 if (eos === undefined) eos = require('./end-of-stream');
17560 eos(stream, {
17561 readable: reading,
17562 writable: writing
17563 }, function (err) {
17564 if (err) return callback(err);
17565 closed = true;
17566 callback();
17567 });
17568 var destroyed = false;
17569 return function (err) {
17570 if (closed) return;
17571 if (destroyed) return;
17572 destroyed = true; // request.destroy just do .end - .abort is what we want
17573
17574 if (isRequest(stream)) return stream.abort();
17575 if (typeof stream.destroy === 'function') return stream.destroy();
17576 callback(err || new ERR_STREAM_DESTROYED('pipe'));
17577 };
17578}
17579
17580function call(fn) {
17581 fn();
17582}
17583
17584function pipe(from, to) {
17585 return from.pipe(to);
17586}
17587
17588function popCallback(streams) {
17589 if (!streams.length) return noop;
17590 if (typeof streams[streams.length - 1] !== 'function') return noop;
17591 return streams.pop();
17592}
17593
17594function pipeline() {
17595 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
17596 streams[_key] = arguments[_key];
17597 }
17598
17599 var callback = popCallback(streams);
17600 if (Array.isArray(streams[0])) streams = streams[0];
17601
17602 if (streams.length < 2) {
17603 throw new ERR_MISSING_ARGS('streams');
17604 }
17605
17606 var error;
17607 var destroys = streams.map(function (stream, i) {
17608 var reading = i < streams.length - 1;
17609 var writing = i > 0;
17610 return destroyer(stream, reading, writing, function (err) {
17611 if (!error) error = err;
17612 if (err) destroys.forEach(call);
17613 if (reading) return;
17614 destroys.forEach(call);
17615 callback(error);
17616 });
17617 });
17618 return streams.reduce(pipe);
17619}
17620
17621module.exports = pipeline;
17622},{"../../../errors":61,"./end-of-stream":70}],73:[function(require,module,exports){
17623'use strict';
17624
17625var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
17626
17627function highWaterMarkFrom(options, isDuplex, duplexKey) {
17628 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
17629}
17630
17631function getHighWaterMark(state, options, duplexKey, isDuplex) {
17632 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
17633
17634 if (hwm != null) {
17635 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
17636 var name = isDuplex ? duplexKey : 'highWaterMark';
17637 throw new ERR_INVALID_OPT_VALUE(name, hwm);
17638 }
17639
17640 return Math.floor(hwm);
17641 } // Default value
17642
17643
17644 return state.objectMode ? 16 : 16 * 1024;
17645}
17646
17647module.exports = {
17648 getHighWaterMark: getHighWaterMark
17649};
17650},{"../../../errors":61}],74:[function(require,module,exports){
17651module.exports = require('events').EventEmitter;
17652
17653},{"events":120}],75:[function(require,module,exports){
17654exports = module.exports = require('./lib/_stream_readable.js');
17655exports.Stream = exports;
17656exports.Readable = exports;
17657exports.Writable = require('./lib/_stream_writable.js');
17658exports.Duplex = require('./lib/_stream_duplex.js');
17659exports.Transform = require('./lib/_stream_transform.js');
17660exports.PassThrough = require('./lib/_stream_passthrough.js');
17661exports.finished = require('./lib/internal/streams/end-of-stream.js');
17662exports.pipeline = require('./lib/internal/streams/pipeline.js');
17663
17664},{"./lib/_stream_duplex.js":62,"./lib/_stream_passthrough.js":63,"./lib/_stream_readable.js":64,"./lib/_stream_transform.js":65,"./lib/_stream_writable.js":66,"./lib/internal/streams/end-of-stream.js":70,"./lib/internal/streams/pipeline.js":72}],76:[function(require,module,exports){
17665(function (Buffer){(function (){
17666module.exports = function xor (a, b) {
17667 var length = Math.min(a.length, b.length)
17668 var buffer = new Buffer(length)
17669
17670 for (var i = 0; i < length; ++i) {
17671 buffer[i] = a[i] ^ b[i]
17672 }
17673
17674 return buffer
17675}
17676
17677}).call(this)}).call(this,require("buffer").Buffer)
17678},{"buffer":77}],77:[function(require,module,exports){
17679(function (Buffer){(function (){
17680/*!
17681 * The buffer module from node.js, for the browser.
17682 *
17683 * @author Feross Aboukhadijeh <https://feross.org>
17684 * @license MIT
17685 */
17686/* eslint-disable no-proto */
17687
17688'use strict'
17689
17690var base64 = require('base64-js')
17691var ieee754 = require('ieee754')
17692
17693exports.Buffer = Buffer
17694exports.SlowBuffer = SlowBuffer
17695exports.INSPECT_MAX_BYTES = 50
17696
17697var K_MAX_LENGTH = 0x7fffffff
17698exports.kMaxLength = K_MAX_LENGTH
17699
17700/**
17701 * If `Buffer.TYPED_ARRAY_SUPPORT`:
17702 * === true Use Uint8Array implementation (fastest)
17703 * === false Print warning and recommend using `buffer` v4.x which has an Object
17704 * implementation (most compatible, even IE6)
17705 *
17706 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
17707 * Opera 11.6+, iOS 4.2+.
17708 *
17709 * We report that the browser does not support typed arrays if the are not subclassable
17710 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
17711 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
17712 * for __proto__ and has a buggy typed array implementation.
17713 */
17714Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
17715
17716if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
17717 typeof console.error === 'function') {
17718 console.error(
17719 'This browser lacks typed array (Uint8Array) support which is required by ' +
17720 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
17721 )
17722}
17723
17724function typedArraySupport () {
17725 // Can typed array instances can be augmented?
17726 try {
17727 var arr = new Uint8Array(1)
17728 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
17729 return arr.foo() === 42
17730 } catch (e) {
17731 return false
17732 }
17733}
17734
17735Object.defineProperty(Buffer.prototype, 'parent', {
17736 enumerable: true,
17737 get: function () {
17738 if (!Buffer.isBuffer(this)) return undefined
17739 return this.buffer
17740 }
17741})
17742
17743Object.defineProperty(Buffer.prototype, 'offset', {
17744 enumerable: true,
17745 get: function () {
17746 if (!Buffer.isBuffer(this)) return undefined
17747 return this.byteOffset
17748 }
17749})
17750
17751function createBuffer (length) {
17752 if (length > K_MAX_LENGTH) {
17753 throw new RangeError('The value "' + length + '" is invalid for option "size"')
17754 }
17755 // Return an augmented `Uint8Array` instance
17756 var buf = new Uint8Array(length)
17757 buf.__proto__ = Buffer.prototype
17758 return buf
17759}
17760
17761/**
17762 * The Buffer constructor returns instances of `Uint8Array` that have their
17763 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
17764 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
17765 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
17766 * returns a single octet.
17767 *
17768 * The `Uint8Array` prototype remains unmodified.
17769 */
17770
17771function Buffer (arg, encodingOrOffset, length) {
17772 // Common case.
17773 if (typeof arg === 'number') {
17774 if (typeof encodingOrOffset === 'string') {
17775 throw new TypeError(
17776 'The "string" argument must be of type string. Received type number'
17777 )
17778 }
17779 return allocUnsafe(arg)
17780 }
17781 return from(arg, encodingOrOffset, length)
17782}
17783
17784// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
17785if (typeof Symbol !== 'undefined' && Symbol.species != null &&
17786 Buffer[Symbol.species] === Buffer) {
17787 Object.defineProperty(Buffer, Symbol.species, {
17788 value: null,
17789 configurable: true,
17790 enumerable: false,
17791 writable: false
17792 })
17793}
17794
17795Buffer.poolSize = 8192 // not used by this implementation
17796
17797function from (value, encodingOrOffset, length) {
17798 if (typeof value === 'string') {
17799 return fromString(value, encodingOrOffset)
17800 }
17801
17802 if (ArrayBuffer.isView(value)) {
17803 return fromArrayLike(value)
17804 }
17805
17806 if (value == null) {
17807 throw TypeError(
17808 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
17809 'or Array-like Object. Received type ' + (typeof value)
17810 )
17811 }
17812
17813 if (isInstance(value, ArrayBuffer) ||
17814 (value && isInstance(value.buffer, ArrayBuffer))) {
17815 return fromArrayBuffer(value, encodingOrOffset, length)
17816 }
17817
17818 if (typeof value === 'number') {
17819 throw new TypeError(
17820 'The "value" argument must not be of type number. Received type number'
17821 )
17822 }
17823
17824 var valueOf = value.valueOf && value.valueOf()
17825 if (valueOf != null && valueOf !== value) {
17826 return Buffer.from(valueOf, encodingOrOffset, length)
17827 }
17828
17829 var b = fromObject(value)
17830 if (b) return b
17831
17832 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
17833 typeof value[Symbol.toPrimitive] === 'function') {
17834 return Buffer.from(
17835 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
17836 )
17837 }
17838
17839 throw new TypeError(
17840 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
17841 'or Array-like Object. Received type ' + (typeof value)
17842 )
17843}
17844
17845/**
17846 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
17847 * if value is a number.
17848 * Buffer.from(str[, encoding])
17849 * Buffer.from(array)
17850 * Buffer.from(buffer)
17851 * Buffer.from(arrayBuffer[, byteOffset[, length]])
17852 **/
17853Buffer.from = function (value, encodingOrOffset, length) {
17854 return from(value, encodingOrOffset, length)
17855}
17856
17857// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
17858// https://github.com/feross/buffer/pull/148
17859Buffer.prototype.__proto__ = Uint8Array.prototype
17860Buffer.__proto__ = Uint8Array
17861
17862function assertSize (size) {
17863 if (typeof size !== 'number') {
17864 throw new TypeError('"size" argument must be of type number')
17865 } else if (size < 0) {
17866 throw new RangeError('The value "' + size + '" is invalid for option "size"')
17867 }
17868}
17869
17870function alloc (size, fill, encoding) {
17871 assertSize(size)
17872 if (size <= 0) {
17873 return createBuffer(size)
17874 }
17875 if (fill !== undefined) {
17876 // Only pay attention to encoding if it's a string. This
17877 // prevents accidentally sending in a number that would
17878 // be interpretted as a start offset.
17879 return typeof encoding === 'string'
17880 ? createBuffer(size).fill(fill, encoding)
17881 : createBuffer(size).fill(fill)
17882 }
17883 return createBuffer(size)
17884}
17885
17886/**
17887 * Creates a new filled Buffer instance.
17888 * alloc(size[, fill[, encoding]])
17889 **/
17890Buffer.alloc = function (size, fill, encoding) {
17891 return alloc(size, fill, encoding)
17892}
17893
17894function allocUnsafe (size) {
17895 assertSize(size)
17896 return createBuffer(size < 0 ? 0 : checked(size) | 0)
17897}
17898
17899/**
17900 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
17901 * */
17902Buffer.allocUnsafe = function (size) {
17903 return allocUnsafe(size)
17904}
17905/**
17906 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
17907 */
17908Buffer.allocUnsafeSlow = function (size) {
17909 return allocUnsafe(size)
17910}
17911
17912function fromString (string, encoding) {
17913 if (typeof encoding !== 'string' || encoding === '') {
17914 encoding = 'utf8'
17915 }
17916
17917 if (!Buffer.isEncoding(encoding)) {
17918 throw new TypeError('Unknown encoding: ' + encoding)
17919 }
17920
17921 var length = byteLength(string, encoding) | 0
17922 var buf = createBuffer(length)
17923
17924 var actual = buf.write(string, encoding)
17925
17926 if (actual !== length) {
17927 // Writing a hex string, for example, that contains invalid characters will
17928 // cause everything after the first invalid character to be ignored. (e.g.
17929 // 'abxxcd' will be treated as 'ab')
17930 buf = buf.slice(0, actual)
17931 }
17932
17933 return buf
17934}
17935
17936function fromArrayLike (array) {
17937 var length = array.length < 0 ? 0 : checked(array.length) | 0
17938 var buf = createBuffer(length)
17939 for (var i = 0; i < length; i += 1) {
17940 buf[i] = array[i] & 255
17941 }
17942 return buf
17943}
17944
17945function fromArrayBuffer (array, byteOffset, length) {
17946 if (byteOffset < 0 || array.byteLength < byteOffset) {
17947 throw new RangeError('"offset" is outside of buffer bounds')
17948 }
17949
17950 if (array.byteLength < byteOffset + (length || 0)) {
17951 throw new RangeError('"length" is outside of buffer bounds')
17952 }
17953
17954 var buf
17955 if (byteOffset === undefined && length === undefined) {
17956 buf = new Uint8Array(array)
17957 } else if (length === undefined) {
17958 buf = new Uint8Array(array, byteOffset)
17959 } else {
17960 buf = new Uint8Array(array, byteOffset, length)
17961 }
17962
17963 // Return an augmented `Uint8Array` instance
17964 buf.__proto__ = Buffer.prototype
17965 return buf
17966}
17967
17968function fromObject (obj) {
17969 if (Buffer.isBuffer(obj)) {
17970 var len = checked(obj.length) | 0
17971 var buf = createBuffer(len)
17972
17973 if (buf.length === 0) {
17974 return buf
17975 }
17976
17977 obj.copy(buf, 0, 0, len)
17978 return buf
17979 }
17980
17981 if (obj.length !== undefined) {
17982 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
17983 return createBuffer(0)
17984 }
17985 return fromArrayLike(obj)
17986 }
17987
17988 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
17989 return fromArrayLike(obj.data)
17990 }
17991}
17992
17993function checked (length) {
17994 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
17995 // length is NaN (which is otherwise coerced to zero.)
17996 if (length >= K_MAX_LENGTH) {
17997 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
17998 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
17999 }
18000 return length | 0
18001}
18002
18003function SlowBuffer (length) {
18004 if (+length != length) { // eslint-disable-line eqeqeq
18005 length = 0
18006 }
18007 return Buffer.alloc(+length)
18008}
18009
18010Buffer.isBuffer = function isBuffer (b) {
18011 return b != null && b._isBuffer === true &&
18012 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
18013}
18014
18015Buffer.compare = function compare (a, b) {
18016 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
18017 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
18018 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
18019 throw new TypeError(
18020 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
18021 )
18022 }
18023
18024 if (a === b) return 0
18025
18026 var x = a.length
18027 var y = b.length
18028
18029 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
18030 if (a[i] !== b[i]) {
18031 x = a[i]
18032 y = b[i]
18033 break
18034 }
18035 }
18036
18037 if (x < y) return -1
18038 if (y < x) return 1
18039 return 0
18040}
18041
18042Buffer.isEncoding = function isEncoding (encoding) {
18043 switch (String(encoding).toLowerCase()) {
18044 case 'hex':
18045 case 'utf8':
18046 case 'utf-8':
18047 case 'ascii':
18048 case 'latin1':
18049 case 'binary':
18050 case 'base64':
18051 case 'ucs2':
18052 case 'ucs-2':
18053 case 'utf16le':
18054 case 'utf-16le':
18055 return true
18056 default:
18057 return false
18058 }
18059}
18060
18061Buffer.concat = function concat (list, length) {
18062 if (!Array.isArray(list)) {
18063 throw new TypeError('"list" argument must be an Array of Buffers')
18064 }
18065
18066 if (list.length === 0) {
18067 return Buffer.alloc(0)
18068 }
18069
18070 var i
18071 if (length === undefined) {
18072 length = 0
18073 for (i = 0; i < list.length; ++i) {
18074 length += list[i].length
18075 }
18076 }
18077
18078 var buffer = Buffer.allocUnsafe(length)
18079 var pos = 0
18080 for (i = 0; i < list.length; ++i) {
18081 var buf = list[i]
18082 if (isInstance(buf, Uint8Array)) {
18083 buf = Buffer.from(buf)
18084 }
18085 if (!Buffer.isBuffer(buf)) {
18086 throw new TypeError('"list" argument must be an Array of Buffers')
18087 }
18088 buf.copy(buffer, pos)
18089 pos += buf.length
18090 }
18091 return buffer
18092}
18093
18094function byteLength (string, encoding) {
18095 if (Buffer.isBuffer(string)) {
18096 return string.length
18097 }
18098 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
18099 return string.byteLength
18100 }
18101 if (typeof string !== 'string') {
18102 throw new TypeError(
18103 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
18104 'Received type ' + typeof string
18105 )
18106 }
18107
18108 var len = string.length
18109 var mustMatch = (arguments.length > 2 && arguments[2] === true)
18110 if (!mustMatch && len === 0) return 0
18111
18112 // Use a for loop to avoid recursion
18113 var loweredCase = false
18114 for (;;) {
18115 switch (encoding) {
18116 case 'ascii':
18117 case 'latin1':
18118 case 'binary':
18119 return len
18120 case 'utf8':
18121 case 'utf-8':
18122 return utf8ToBytes(string).length
18123 case 'ucs2':
18124 case 'ucs-2':
18125 case 'utf16le':
18126 case 'utf-16le':
18127 return len * 2
18128 case 'hex':
18129 return len >>> 1
18130 case 'base64':
18131 return base64ToBytes(string).length
18132 default:
18133 if (loweredCase) {
18134 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
18135 }
18136 encoding = ('' + encoding).toLowerCase()
18137 loweredCase = true
18138 }
18139 }
18140}
18141Buffer.byteLength = byteLength
18142
18143function slowToString (encoding, start, end) {
18144 var loweredCase = false
18145
18146 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
18147 // property of a typed array.
18148
18149 // This behaves neither like String nor Uint8Array in that we set start/end
18150 // to their upper/lower bounds if the value passed is out of range.
18151 // undefined is handled specially as per ECMA-262 6th Edition,
18152 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
18153 if (start === undefined || start < 0) {
18154 start = 0
18155 }
18156 // Return early if start > this.length. Done here to prevent potential uint32
18157 // coercion fail below.
18158 if (start > this.length) {
18159 return ''
18160 }
18161
18162 if (end === undefined || end > this.length) {
18163 end = this.length
18164 }
18165
18166 if (end <= 0) {
18167 return ''
18168 }
18169
18170 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
18171 end >>>= 0
18172 start >>>= 0
18173
18174 if (end <= start) {
18175 return ''
18176 }
18177
18178 if (!encoding) encoding = 'utf8'
18179
18180 while (true) {
18181 switch (encoding) {
18182 case 'hex':
18183 return hexSlice(this, start, end)
18184
18185 case 'utf8':
18186 case 'utf-8':
18187 return utf8Slice(this, start, end)
18188
18189 case 'ascii':
18190 return asciiSlice(this, start, end)
18191
18192 case 'latin1':
18193 case 'binary':
18194 return latin1Slice(this, start, end)
18195
18196 case 'base64':
18197 return base64Slice(this, start, end)
18198
18199 case 'ucs2':
18200 case 'ucs-2':
18201 case 'utf16le':
18202 case 'utf-16le':
18203 return utf16leSlice(this, start, end)
18204
18205 default:
18206 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
18207 encoding = (encoding + '').toLowerCase()
18208 loweredCase = true
18209 }
18210 }
18211}
18212
18213// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
18214// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
18215// reliably in a browserify context because there could be multiple different
18216// copies of the 'buffer' package in use. This method works even for Buffer
18217// instances that were created from another copy of the `buffer` package.
18218// See: https://github.com/feross/buffer/issues/154
18219Buffer.prototype._isBuffer = true
18220
18221function swap (b, n, m) {
18222 var i = b[n]
18223 b[n] = b[m]
18224 b[m] = i
18225}
18226
18227Buffer.prototype.swap16 = function swap16 () {
18228 var len = this.length
18229 if (len % 2 !== 0) {
18230 throw new RangeError('Buffer size must be a multiple of 16-bits')
18231 }
18232 for (var i = 0; i < len; i += 2) {
18233 swap(this, i, i + 1)
18234 }
18235 return this
18236}
18237
18238Buffer.prototype.swap32 = function swap32 () {
18239 var len = this.length
18240 if (len % 4 !== 0) {
18241 throw new RangeError('Buffer size must be a multiple of 32-bits')
18242 }
18243 for (var i = 0; i < len; i += 4) {
18244 swap(this, i, i + 3)
18245 swap(this, i + 1, i + 2)
18246 }
18247 return this
18248}
18249
18250Buffer.prototype.swap64 = function swap64 () {
18251 var len = this.length
18252 if (len % 8 !== 0) {
18253 throw new RangeError('Buffer size must be a multiple of 64-bits')
18254 }
18255 for (var i = 0; i < len; i += 8) {
18256 swap(this, i, i + 7)
18257 swap(this, i + 1, i + 6)
18258 swap(this, i + 2, i + 5)
18259 swap(this, i + 3, i + 4)
18260 }
18261 return this
18262}
18263
18264Buffer.prototype.toString = function toString () {
18265 var length = this.length
18266 if (length === 0) return ''
18267 if (arguments.length === 0) return utf8Slice(this, 0, length)
18268 return slowToString.apply(this, arguments)
18269}
18270
18271Buffer.prototype.toLocaleString = Buffer.prototype.toString
18272
18273Buffer.prototype.equals = function equals (b) {
18274 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
18275 if (this === b) return true
18276 return Buffer.compare(this, b) === 0
18277}
18278
18279Buffer.prototype.inspect = function inspect () {
18280 var str = ''
18281 var max = exports.INSPECT_MAX_BYTES
18282 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
18283 if (this.length > max) str += ' ... '
18284 return '<Buffer ' + str + '>'
18285}
18286
18287Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
18288 if (isInstance(target, Uint8Array)) {
18289 target = Buffer.from(target, target.offset, target.byteLength)
18290 }
18291 if (!Buffer.isBuffer(target)) {
18292 throw new TypeError(
18293 'The "target" argument must be one of type Buffer or Uint8Array. ' +
18294 'Received type ' + (typeof target)
18295 )
18296 }
18297
18298 if (start === undefined) {
18299 start = 0
18300 }
18301 if (end === undefined) {
18302 end = target ? target.length : 0
18303 }
18304 if (thisStart === undefined) {
18305 thisStart = 0
18306 }
18307 if (thisEnd === undefined) {
18308 thisEnd = this.length
18309 }
18310
18311 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
18312 throw new RangeError('out of range index')
18313 }
18314
18315 if (thisStart >= thisEnd && start >= end) {
18316 return 0
18317 }
18318 if (thisStart >= thisEnd) {
18319 return -1
18320 }
18321 if (start >= end) {
18322 return 1
18323 }
18324
18325 start >>>= 0
18326 end >>>= 0
18327 thisStart >>>= 0
18328 thisEnd >>>= 0
18329
18330 if (this === target) return 0
18331
18332 var x = thisEnd - thisStart
18333 var y = end - start
18334 var len = Math.min(x, y)
18335
18336 var thisCopy = this.slice(thisStart, thisEnd)
18337 var targetCopy = target.slice(start, end)
18338
18339 for (var i = 0; i < len; ++i) {
18340 if (thisCopy[i] !== targetCopy[i]) {
18341 x = thisCopy[i]
18342 y = targetCopy[i]
18343 break
18344 }
18345 }
18346
18347 if (x < y) return -1
18348 if (y < x) return 1
18349 return 0
18350}
18351
18352// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
18353// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
18354//
18355// Arguments:
18356// - buffer - a Buffer to search
18357// - val - a string, Buffer, or number
18358// - byteOffset - an index into `buffer`; will be clamped to an int32
18359// - encoding - an optional encoding, relevant is val is a string
18360// - dir - true for indexOf, false for lastIndexOf
18361function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
18362 // Empty buffer means no match
18363 if (buffer.length === 0) return -1
18364
18365 // Normalize byteOffset
18366 if (typeof byteOffset === 'string') {
18367 encoding = byteOffset
18368 byteOffset = 0
18369 } else if (byteOffset > 0x7fffffff) {
18370 byteOffset = 0x7fffffff
18371 } else if (byteOffset < -0x80000000) {
18372 byteOffset = -0x80000000
18373 }
18374 byteOffset = +byteOffset // Coerce to Number.
18375 if (numberIsNaN(byteOffset)) {
18376 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
18377 byteOffset = dir ? 0 : (buffer.length - 1)
18378 }
18379
18380 // Normalize byteOffset: negative offsets start from the end of the buffer
18381 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
18382 if (byteOffset >= buffer.length) {
18383 if (dir) return -1
18384 else byteOffset = buffer.length - 1
18385 } else if (byteOffset < 0) {
18386 if (dir) byteOffset = 0
18387 else return -1
18388 }
18389
18390 // Normalize val
18391 if (typeof val === 'string') {
18392 val = Buffer.from(val, encoding)
18393 }
18394
18395 // Finally, search either indexOf (if dir is true) or lastIndexOf
18396 if (Buffer.isBuffer(val)) {
18397 // Special case: looking for empty string/buffer always fails
18398 if (val.length === 0) {
18399 return -1
18400 }
18401 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
18402 } else if (typeof val === 'number') {
18403 val = val & 0xFF // Search for a byte value [0-255]
18404 if (typeof Uint8Array.prototype.indexOf === 'function') {
18405 if (dir) {
18406 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
18407 } else {
18408 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
18409 }
18410 }
18411 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
18412 }
18413
18414 throw new TypeError('val must be string, number or Buffer')
18415}
18416
18417function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
18418 var indexSize = 1
18419 var arrLength = arr.length
18420 var valLength = val.length
18421
18422 if (encoding !== undefined) {
18423 encoding = String(encoding).toLowerCase()
18424 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
18425 encoding === 'utf16le' || encoding === 'utf-16le') {
18426 if (arr.length < 2 || val.length < 2) {
18427 return -1
18428 }
18429 indexSize = 2
18430 arrLength /= 2
18431 valLength /= 2
18432 byteOffset /= 2
18433 }
18434 }
18435
18436 function read (buf, i) {
18437 if (indexSize === 1) {
18438 return buf[i]
18439 } else {
18440 return buf.readUInt16BE(i * indexSize)
18441 }
18442 }
18443
18444 var i
18445 if (dir) {
18446 var foundIndex = -1
18447 for (i = byteOffset; i < arrLength; i++) {
18448 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
18449 if (foundIndex === -1) foundIndex = i
18450 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
18451 } else {
18452 if (foundIndex !== -1) i -= i - foundIndex
18453 foundIndex = -1
18454 }
18455 }
18456 } else {
18457 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
18458 for (i = byteOffset; i >= 0; i--) {
18459 var found = true
18460 for (var j = 0; j < valLength; j++) {
18461 if (read(arr, i + j) !== read(val, j)) {
18462 found = false
18463 break
18464 }
18465 }
18466 if (found) return i
18467 }
18468 }
18469
18470 return -1
18471}
18472
18473Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
18474 return this.indexOf(val, byteOffset, encoding) !== -1
18475}
18476
18477Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
18478 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
18479}
18480
18481Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
18482 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
18483}
18484
18485function hexWrite (buf, string, offset, length) {
18486 offset = Number(offset) || 0
18487 var remaining = buf.length - offset
18488 if (!length) {
18489 length = remaining
18490 } else {
18491 length = Number(length)
18492 if (length > remaining) {
18493 length = remaining
18494 }
18495 }
18496
18497 var strLen = string.length
18498
18499 if (length > strLen / 2) {
18500 length = strLen / 2
18501 }
18502 for (var i = 0; i < length; ++i) {
18503 var parsed = parseInt(string.substr(i * 2, 2), 16)
18504 if (numberIsNaN(parsed)) return i
18505 buf[offset + i] = parsed
18506 }
18507 return i
18508}
18509
18510function utf8Write (buf, string, offset, length) {
18511 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
18512}
18513
18514function asciiWrite (buf, string, offset, length) {
18515 return blitBuffer(asciiToBytes(string), buf, offset, length)
18516}
18517
18518function latin1Write (buf, string, offset, length) {
18519 return asciiWrite(buf, string, offset, length)
18520}
18521
18522function base64Write (buf, string, offset, length) {
18523 return blitBuffer(base64ToBytes(string), buf, offset, length)
18524}
18525
18526function ucs2Write (buf, string, offset, length) {
18527 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
18528}
18529
18530Buffer.prototype.write = function write (string, offset, length, encoding) {
18531 // Buffer#write(string)
18532 if (offset === undefined) {
18533 encoding = 'utf8'
18534 length = this.length
18535 offset = 0
18536 // Buffer#write(string, encoding)
18537 } else if (length === undefined && typeof offset === 'string') {
18538 encoding = offset
18539 length = this.length
18540 offset = 0
18541 // Buffer#write(string, offset[, length][, encoding])
18542 } else if (isFinite(offset)) {
18543 offset = offset >>> 0
18544 if (isFinite(length)) {
18545 length = length >>> 0
18546 if (encoding === undefined) encoding = 'utf8'
18547 } else {
18548 encoding = length
18549 length = undefined
18550 }
18551 } else {
18552 throw new Error(
18553 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
18554 )
18555 }
18556
18557 var remaining = this.length - offset
18558 if (length === undefined || length > remaining) length = remaining
18559
18560 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
18561 throw new RangeError('Attempt to write outside buffer bounds')
18562 }
18563
18564 if (!encoding) encoding = 'utf8'
18565
18566 var loweredCase = false
18567 for (;;) {
18568 switch (encoding) {
18569 case 'hex':
18570 return hexWrite(this, string, offset, length)
18571
18572 case 'utf8':
18573 case 'utf-8':
18574 return utf8Write(this, string, offset, length)
18575
18576 case 'ascii':
18577 return asciiWrite(this, string, offset, length)
18578
18579 case 'latin1':
18580 case 'binary':
18581 return latin1Write(this, string, offset, length)
18582
18583 case 'base64':
18584 // Warning: maxLength not taken into account in base64Write
18585 return base64Write(this, string, offset, length)
18586
18587 case 'ucs2':
18588 case 'ucs-2':
18589 case 'utf16le':
18590 case 'utf-16le':
18591 return ucs2Write(this, string, offset, length)
18592
18593 default:
18594 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
18595 encoding = ('' + encoding).toLowerCase()
18596 loweredCase = true
18597 }
18598 }
18599}
18600
18601Buffer.prototype.toJSON = function toJSON () {
18602 return {
18603 type: 'Buffer',
18604 data: Array.prototype.slice.call(this._arr || this, 0)
18605 }
18606}
18607
18608function base64Slice (buf, start, end) {
18609 if (start === 0 && end === buf.length) {
18610 return base64.fromByteArray(buf)
18611 } else {
18612 return base64.fromByteArray(buf.slice(start, end))
18613 }
18614}
18615
18616function utf8Slice (buf, start, end) {
18617 end = Math.min(buf.length, end)
18618 var res = []
18619
18620 var i = start
18621 while (i < end) {
18622 var firstByte = buf[i]
18623 var codePoint = null
18624 var bytesPerSequence = (firstByte > 0xEF) ? 4
18625 : (firstByte > 0xDF) ? 3
18626 : (firstByte > 0xBF) ? 2
18627 : 1
18628
18629 if (i + bytesPerSequence <= end) {
18630 var secondByte, thirdByte, fourthByte, tempCodePoint
18631
18632 switch (bytesPerSequence) {
18633 case 1:
18634 if (firstByte < 0x80) {
18635 codePoint = firstByte
18636 }
18637 break
18638 case 2:
18639 secondByte = buf[i + 1]
18640 if ((secondByte & 0xC0) === 0x80) {
18641 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
18642 if (tempCodePoint > 0x7F) {
18643 codePoint = tempCodePoint
18644 }
18645 }
18646 break
18647 case 3:
18648 secondByte = buf[i + 1]
18649 thirdByte = buf[i + 2]
18650 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
18651 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
18652 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
18653 codePoint = tempCodePoint
18654 }
18655 }
18656 break
18657 case 4:
18658 secondByte = buf[i + 1]
18659 thirdByte = buf[i + 2]
18660 fourthByte = buf[i + 3]
18661 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
18662 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
18663 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
18664 codePoint = tempCodePoint
18665 }
18666 }
18667 }
18668 }
18669
18670 if (codePoint === null) {
18671 // we did not generate a valid codePoint so insert a
18672 // replacement char (U+FFFD) and advance only 1 byte
18673 codePoint = 0xFFFD
18674 bytesPerSequence = 1
18675 } else if (codePoint > 0xFFFF) {
18676 // encode to utf16 (surrogate pair dance)
18677 codePoint -= 0x10000
18678 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
18679 codePoint = 0xDC00 | codePoint & 0x3FF
18680 }
18681
18682 res.push(codePoint)
18683 i += bytesPerSequence
18684 }
18685
18686 return decodeCodePointsArray(res)
18687}
18688
18689// Based on http://stackoverflow.com/a/22747272/680742, the browser with
18690// the lowest limit is Chrome, with 0x10000 args.
18691// We go 1 magnitude less, for safety
18692var MAX_ARGUMENTS_LENGTH = 0x1000
18693
18694function decodeCodePointsArray (codePoints) {
18695 var len = codePoints.length
18696 if (len <= MAX_ARGUMENTS_LENGTH) {
18697 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
18698 }
18699
18700 // Decode in chunks to avoid "call stack size exceeded".
18701 var res = ''
18702 var i = 0
18703 while (i < len) {
18704 res += String.fromCharCode.apply(
18705 String,
18706 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
18707 )
18708 }
18709 return res
18710}
18711
18712function asciiSlice (buf, start, end) {
18713 var ret = ''
18714 end = Math.min(buf.length, end)
18715
18716 for (var i = start; i < end; ++i) {
18717 ret += String.fromCharCode(buf[i] & 0x7F)
18718 }
18719 return ret
18720}
18721
18722function latin1Slice (buf, start, end) {
18723 var ret = ''
18724 end = Math.min(buf.length, end)
18725
18726 for (var i = start; i < end; ++i) {
18727 ret += String.fromCharCode(buf[i])
18728 }
18729 return ret
18730}
18731
18732function hexSlice (buf, start, end) {
18733 var len = buf.length
18734
18735 if (!start || start < 0) start = 0
18736 if (!end || end < 0 || end > len) end = len
18737
18738 var out = ''
18739 for (var i = start; i < end; ++i) {
18740 out += toHex(buf[i])
18741 }
18742 return out
18743}
18744
18745function utf16leSlice (buf, start, end) {
18746 var bytes = buf.slice(start, end)
18747 var res = ''
18748 for (var i = 0; i < bytes.length; i += 2) {
18749 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
18750 }
18751 return res
18752}
18753
18754Buffer.prototype.slice = function slice (start, end) {
18755 var len = this.length
18756 start = ~~start
18757 end = end === undefined ? len : ~~end
18758
18759 if (start < 0) {
18760 start += len
18761 if (start < 0) start = 0
18762 } else if (start > len) {
18763 start = len
18764 }
18765
18766 if (end < 0) {
18767 end += len
18768 if (end < 0) end = 0
18769 } else if (end > len) {
18770 end = len
18771 }
18772
18773 if (end < start) end = start
18774
18775 var newBuf = this.subarray(start, end)
18776 // Return an augmented `Uint8Array` instance
18777 newBuf.__proto__ = Buffer.prototype
18778 return newBuf
18779}
18780
18781/*
18782 * Need to make sure that buffer isn't trying to write out of bounds.
18783 */
18784function checkOffset (offset, ext, length) {
18785 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
18786 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
18787}
18788
18789Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
18790 offset = offset >>> 0
18791 byteLength = byteLength >>> 0
18792 if (!noAssert) checkOffset(offset, byteLength, this.length)
18793
18794 var val = this[offset]
18795 var mul = 1
18796 var i = 0
18797 while (++i < byteLength && (mul *= 0x100)) {
18798 val += this[offset + i] * mul
18799 }
18800
18801 return val
18802}
18803
18804Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
18805 offset = offset >>> 0
18806 byteLength = byteLength >>> 0
18807 if (!noAssert) {
18808 checkOffset(offset, byteLength, this.length)
18809 }
18810
18811 var val = this[offset + --byteLength]
18812 var mul = 1
18813 while (byteLength > 0 && (mul *= 0x100)) {
18814 val += this[offset + --byteLength] * mul
18815 }
18816
18817 return val
18818}
18819
18820Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
18821 offset = offset >>> 0
18822 if (!noAssert) checkOffset(offset, 1, this.length)
18823 return this[offset]
18824}
18825
18826Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
18827 offset = offset >>> 0
18828 if (!noAssert) checkOffset(offset, 2, this.length)
18829 return this[offset] | (this[offset + 1] << 8)
18830}
18831
18832Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
18833 offset = offset >>> 0
18834 if (!noAssert) checkOffset(offset, 2, this.length)
18835 return (this[offset] << 8) | this[offset + 1]
18836}
18837
18838Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
18839 offset = offset >>> 0
18840 if (!noAssert) checkOffset(offset, 4, this.length)
18841
18842 return ((this[offset]) |
18843 (this[offset + 1] << 8) |
18844 (this[offset + 2] << 16)) +
18845 (this[offset + 3] * 0x1000000)
18846}
18847
18848Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
18849 offset = offset >>> 0
18850 if (!noAssert) checkOffset(offset, 4, this.length)
18851
18852 return (this[offset] * 0x1000000) +
18853 ((this[offset + 1] << 16) |
18854 (this[offset + 2] << 8) |
18855 this[offset + 3])
18856}
18857
18858Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
18859 offset = offset >>> 0
18860 byteLength = byteLength >>> 0
18861 if (!noAssert) checkOffset(offset, byteLength, this.length)
18862
18863 var val = this[offset]
18864 var mul = 1
18865 var i = 0
18866 while (++i < byteLength && (mul *= 0x100)) {
18867 val += this[offset + i] * mul
18868 }
18869 mul *= 0x80
18870
18871 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
18872
18873 return val
18874}
18875
18876Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
18877 offset = offset >>> 0
18878 byteLength = byteLength >>> 0
18879 if (!noAssert) checkOffset(offset, byteLength, this.length)
18880
18881 var i = byteLength
18882 var mul = 1
18883 var val = this[offset + --i]
18884 while (i > 0 && (mul *= 0x100)) {
18885 val += this[offset + --i] * mul
18886 }
18887 mul *= 0x80
18888
18889 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
18890
18891 return val
18892}
18893
18894Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
18895 offset = offset >>> 0
18896 if (!noAssert) checkOffset(offset, 1, this.length)
18897 if (!(this[offset] & 0x80)) return (this[offset])
18898 return ((0xff - this[offset] + 1) * -1)
18899}
18900
18901Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
18902 offset = offset >>> 0
18903 if (!noAssert) checkOffset(offset, 2, this.length)
18904 var val = this[offset] | (this[offset + 1] << 8)
18905 return (val & 0x8000) ? val | 0xFFFF0000 : val
18906}
18907
18908Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
18909 offset = offset >>> 0
18910 if (!noAssert) checkOffset(offset, 2, this.length)
18911 var val = this[offset + 1] | (this[offset] << 8)
18912 return (val & 0x8000) ? val | 0xFFFF0000 : val
18913}
18914
18915Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
18916 offset = offset >>> 0
18917 if (!noAssert) checkOffset(offset, 4, this.length)
18918
18919 return (this[offset]) |
18920 (this[offset + 1] << 8) |
18921 (this[offset + 2] << 16) |
18922 (this[offset + 3] << 24)
18923}
18924
18925Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
18926 offset = offset >>> 0
18927 if (!noAssert) checkOffset(offset, 4, this.length)
18928
18929 return (this[offset] << 24) |
18930 (this[offset + 1] << 16) |
18931 (this[offset + 2] << 8) |
18932 (this[offset + 3])
18933}
18934
18935Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
18936 offset = offset >>> 0
18937 if (!noAssert) checkOffset(offset, 4, this.length)
18938 return ieee754.read(this, offset, true, 23, 4)
18939}
18940
18941Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
18942 offset = offset >>> 0
18943 if (!noAssert) checkOffset(offset, 4, this.length)
18944 return ieee754.read(this, offset, false, 23, 4)
18945}
18946
18947Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
18948 offset = offset >>> 0
18949 if (!noAssert) checkOffset(offset, 8, this.length)
18950 return ieee754.read(this, offset, true, 52, 8)
18951}
18952
18953Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
18954 offset = offset >>> 0
18955 if (!noAssert) checkOffset(offset, 8, this.length)
18956 return ieee754.read(this, offset, false, 52, 8)
18957}
18958
18959function checkInt (buf, value, offset, ext, max, min) {
18960 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
18961 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
18962 if (offset + ext > buf.length) throw new RangeError('Index out of range')
18963}
18964
18965Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
18966 value = +value
18967 offset = offset >>> 0
18968 byteLength = byteLength >>> 0
18969 if (!noAssert) {
18970 var maxBytes = Math.pow(2, 8 * byteLength) - 1
18971 checkInt(this, value, offset, byteLength, maxBytes, 0)
18972 }
18973
18974 var mul = 1
18975 var i = 0
18976 this[offset] = value & 0xFF
18977 while (++i < byteLength && (mul *= 0x100)) {
18978 this[offset + i] = (value / mul) & 0xFF
18979 }
18980
18981 return offset + byteLength
18982}
18983
18984Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
18985 value = +value
18986 offset = offset >>> 0
18987 byteLength = byteLength >>> 0
18988 if (!noAssert) {
18989 var maxBytes = Math.pow(2, 8 * byteLength) - 1
18990 checkInt(this, value, offset, byteLength, maxBytes, 0)
18991 }
18992
18993 var i = byteLength - 1
18994 var mul = 1
18995 this[offset + i] = value & 0xFF
18996 while (--i >= 0 && (mul *= 0x100)) {
18997 this[offset + i] = (value / mul) & 0xFF
18998 }
18999
19000 return offset + byteLength
19001}
19002
19003Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
19004 value = +value
19005 offset = offset >>> 0
19006 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
19007 this[offset] = (value & 0xff)
19008 return offset + 1
19009}
19010
19011Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
19012 value = +value
19013 offset = offset >>> 0
19014 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
19015 this[offset] = (value & 0xff)
19016 this[offset + 1] = (value >>> 8)
19017 return offset + 2
19018}
19019
19020Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
19021 value = +value
19022 offset = offset >>> 0
19023 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
19024 this[offset] = (value >>> 8)
19025 this[offset + 1] = (value & 0xff)
19026 return offset + 2
19027}
19028
19029Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
19030 value = +value
19031 offset = offset >>> 0
19032 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
19033 this[offset + 3] = (value >>> 24)
19034 this[offset + 2] = (value >>> 16)
19035 this[offset + 1] = (value >>> 8)
19036 this[offset] = (value & 0xff)
19037 return offset + 4
19038}
19039
19040Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
19041 value = +value
19042 offset = offset >>> 0
19043 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
19044 this[offset] = (value >>> 24)
19045 this[offset + 1] = (value >>> 16)
19046 this[offset + 2] = (value >>> 8)
19047 this[offset + 3] = (value & 0xff)
19048 return offset + 4
19049}
19050
19051Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
19052 value = +value
19053 offset = offset >>> 0
19054 if (!noAssert) {
19055 var limit = Math.pow(2, (8 * byteLength) - 1)
19056
19057 checkInt(this, value, offset, byteLength, limit - 1, -limit)
19058 }
19059
19060 var i = 0
19061 var mul = 1
19062 var sub = 0
19063 this[offset] = value & 0xFF
19064 while (++i < byteLength && (mul *= 0x100)) {
19065 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
19066 sub = 1
19067 }
19068 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
19069 }
19070
19071 return offset + byteLength
19072}
19073
19074Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
19075 value = +value
19076 offset = offset >>> 0
19077 if (!noAssert) {
19078 var limit = Math.pow(2, (8 * byteLength) - 1)
19079
19080 checkInt(this, value, offset, byteLength, limit - 1, -limit)
19081 }
19082
19083 var i = byteLength - 1
19084 var mul = 1
19085 var sub = 0
19086 this[offset + i] = value & 0xFF
19087 while (--i >= 0 && (mul *= 0x100)) {
19088 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
19089 sub = 1
19090 }
19091 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
19092 }
19093
19094 return offset + byteLength
19095}
19096
19097Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
19098 value = +value
19099 offset = offset >>> 0
19100 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
19101 if (value < 0) value = 0xff + value + 1
19102 this[offset] = (value & 0xff)
19103 return offset + 1
19104}
19105
19106Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
19107 value = +value
19108 offset = offset >>> 0
19109 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
19110 this[offset] = (value & 0xff)
19111 this[offset + 1] = (value >>> 8)
19112 return offset + 2
19113}
19114
19115Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
19116 value = +value
19117 offset = offset >>> 0
19118 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
19119 this[offset] = (value >>> 8)
19120 this[offset + 1] = (value & 0xff)
19121 return offset + 2
19122}
19123
19124Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
19125 value = +value
19126 offset = offset >>> 0
19127 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
19128 this[offset] = (value & 0xff)
19129 this[offset + 1] = (value >>> 8)
19130 this[offset + 2] = (value >>> 16)
19131 this[offset + 3] = (value >>> 24)
19132 return offset + 4
19133}
19134
19135Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
19136 value = +value
19137 offset = offset >>> 0
19138 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
19139 if (value < 0) value = 0xffffffff + value + 1
19140 this[offset] = (value >>> 24)
19141 this[offset + 1] = (value >>> 16)
19142 this[offset + 2] = (value >>> 8)
19143 this[offset + 3] = (value & 0xff)
19144 return offset + 4
19145}
19146
19147function checkIEEE754 (buf, value, offset, ext, max, min) {
19148 if (offset + ext > buf.length) throw new RangeError('Index out of range')
19149 if (offset < 0) throw new RangeError('Index out of range')
19150}
19151
19152function writeFloat (buf, value, offset, littleEndian, noAssert) {
19153 value = +value
19154 offset = offset >>> 0
19155 if (!noAssert) {
19156 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
19157 }
19158 ieee754.write(buf, value, offset, littleEndian, 23, 4)
19159 return offset + 4
19160}
19161
19162Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
19163 return writeFloat(this, value, offset, true, noAssert)
19164}
19165
19166Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
19167 return writeFloat(this, value, offset, false, noAssert)
19168}
19169
19170function writeDouble (buf, value, offset, littleEndian, noAssert) {
19171 value = +value
19172 offset = offset >>> 0
19173 if (!noAssert) {
19174 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
19175 }
19176 ieee754.write(buf, value, offset, littleEndian, 52, 8)
19177 return offset + 8
19178}
19179
19180Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
19181 return writeDouble(this, value, offset, true, noAssert)
19182}
19183
19184Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
19185 return writeDouble(this, value, offset, false, noAssert)
19186}
19187
19188// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
19189Buffer.prototype.copy = function copy (target, targetStart, start, end) {
19190 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
19191 if (!start) start = 0
19192 if (!end && end !== 0) end = this.length
19193 if (targetStart >= target.length) targetStart = target.length
19194 if (!targetStart) targetStart = 0
19195 if (end > 0 && end < start) end = start
19196
19197 // Copy 0 bytes; we're done
19198 if (end === start) return 0
19199 if (target.length === 0 || this.length === 0) return 0
19200
19201 // Fatal error conditions
19202 if (targetStart < 0) {
19203 throw new RangeError('targetStart out of bounds')
19204 }
19205 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
19206 if (end < 0) throw new RangeError('sourceEnd out of bounds')
19207
19208 // Are we oob?
19209 if (end > this.length) end = this.length
19210 if (target.length - targetStart < end - start) {
19211 end = target.length - targetStart + start
19212 }
19213
19214 var len = end - start
19215
19216 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
19217 // Use built-in when available, missing from IE11
19218 this.copyWithin(targetStart, start, end)
19219 } else if (this === target && start < targetStart && targetStart < end) {
19220 // descending copy from end
19221 for (var i = len - 1; i >= 0; --i) {
19222 target[i + targetStart] = this[i + start]
19223 }
19224 } else {
19225 Uint8Array.prototype.set.call(
19226 target,
19227 this.subarray(start, end),
19228 targetStart
19229 )
19230 }
19231
19232 return len
19233}
19234
19235// Usage:
19236// buffer.fill(number[, offset[, end]])
19237// buffer.fill(buffer[, offset[, end]])
19238// buffer.fill(string[, offset[, end]][, encoding])
19239Buffer.prototype.fill = function fill (val, start, end, encoding) {
19240 // Handle string cases:
19241 if (typeof val === 'string') {
19242 if (typeof start === 'string') {
19243 encoding = start
19244 start = 0
19245 end = this.length
19246 } else if (typeof end === 'string') {
19247 encoding = end
19248 end = this.length
19249 }
19250 if (encoding !== undefined && typeof encoding !== 'string') {
19251 throw new TypeError('encoding must be a string')
19252 }
19253 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
19254 throw new TypeError('Unknown encoding: ' + encoding)
19255 }
19256 if (val.length === 1) {
19257 var code = val.charCodeAt(0)
19258 if ((encoding === 'utf8' && code < 128) ||
19259 encoding === 'latin1') {
19260 // Fast path: If `val` fits into a single byte, use that numeric value.
19261 val = code
19262 }
19263 }
19264 } else if (typeof val === 'number') {
19265 val = val & 255
19266 }
19267
19268 // Invalid ranges are not set to a default, so can range check early.
19269 if (start < 0 || this.length < start || this.length < end) {
19270 throw new RangeError('Out of range index')
19271 }
19272
19273 if (end <= start) {
19274 return this
19275 }
19276
19277 start = start >>> 0
19278 end = end === undefined ? this.length : end >>> 0
19279
19280 if (!val) val = 0
19281
19282 var i
19283 if (typeof val === 'number') {
19284 for (i = start; i < end; ++i) {
19285 this[i] = val
19286 }
19287 } else {
19288 var bytes = Buffer.isBuffer(val)
19289 ? val
19290 : Buffer.from(val, encoding)
19291 var len = bytes.length
19292 if (len === 0) {
19293 throw new TypeError('The value "' + val +
19294 '" is invalid for argument "value"')
19295 }
19296 for (i = 0; i < end - start; ++i) {
19297 this[i + start] = bytes[i % len]
19298 }
19299 }
19300
19301 return this
19302}
19303
19304// HELPER FUNCTIONS
19305// ================
19306
19307var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
19308
19309function base64clean (str) {
19310 // Node takes equal signs as end of the Base64 encoding
19311 str = str.split('=')[0]
19312 // Node strips out invalid characters like \n and \t from the string, base64-js does not
19313 str = str.trim().replace(INVALID_BASE64_RE, '')
19314 // Node converts strings with length < 2 to ''
19315 if (str.length < 2) return ''
19316 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
19317 while (str.length % 4 !== 0) {
19318 str = str + '='
19319 }
19320 return str
19321}
19322
19323function toHex (n) {
19324 if (n < 16) return '0' + n.toString(16)
19325 return n.toString(16)
19326}
19327
19328function utf8ToBytes (string, units) {
19329 units = units || Infinity
19330 var codePoint
19331 var length = string.length
19332 var leadSurrogate = null
19333 var bytes = []
19334
19335 for (var i = 0; i < length; ++i) {
19336 codePoint = string.charCodeAt(i)
19337
19338 // is surrogate component
19339 if (codePoint > 0xD7FF && codePoint < 0xE000) {
19340 // last char was a lead
19341 if (!leadSurrogate) {
19342 // no lead yet
19343 if (codePoint > 0xDBFF) {
19344 // unexpected trail
19345 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
19346 continue
19347 } else if (i + 1 === length) {
19348 // unpaired lead
19349 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
19350 continue
19351 }
19352
19353 // valid lead
19354 leadSurrogate = codePoint
19355
19356 continue
19357 }
19358
19359 // 2 leads in a row
19360 if (codePoint < 0xDC00) {
19361 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
19362 leadSurrogate = codePoint
19363 continue
19364 }
19365
19366 // valid surrogate pair
19367 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
19368 } else if (leadSurrogate) {
19369 // valid bmp char, but last char was a lead
19370 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
19371 }
19372
19373 leadSurrogate = null
19374
19375 // encode utf8
19376 if (codePoint < 0x80) {
19377 if ((units -= 1) < 0) break
19378 bytes.push(codePoint)
19379 } else if (codePoint < 0x800) {
19380 if ((units -= 2) < 0) break
19381 bytes.push(
19382 codePoint >> 0x6 | 0xC0,
19383 codePoint & 0x3F | 0x80
19384 )
19385 } else if (codePoint < 0x10000) {
19386 if ((units -= 3) < 0) break
19387 bytes.push(
19388 codePoint >> 0xC | 0xE0,
19389 codePoint >> 0x6 & 0x3F | 0x80,
19390 codePoint & 0x3F | 0x80
19391 )
19392 } else if (codePoint < 0x110000) {
19393 if ((units -= 4) < 0) break
19394 bytes.push(
19395 codePoint >> 0x12 | 0xF0,
19396 codePoint >> 0xC & 0x3F | 0x80,
19397 codePoint >> 0x6 & 0x3F | 0x80,
19398 codePoint & 0x3F | 0x80
19399 )
19400 } else {
19401 throw new Error('Invalid code point')
19402 }
19403 }
19404
19405 return bytes
19406}
19407
19408function asciiToBytes (str) {
19409 var byteArray = []
19410 for (var i = 0; i < str.length; ++i) {
19411 // Node's code seems to be doing this and not & 0x7F..
19412 byteArray.push(str.charCodeAt(i) & 0xFF)
19413 }
19414 return byteArray
19415}
19416
19417function utf16leToBytes (str, units) {
19418 var c, hi, lo
19419 var byteArray = []
19420 for (var i = 0; i < str.length; ++i) {
19421 if ((units -= 2) < 0) break
19422
19423 c = str.charCodeAt(i)
19424 hi = c >> 8
19425 lo = c % 256
19426 byteArray.push(lo)
19427 byteArray.push(hi)
19428 }
19429
19430 return byteArray
19431}
19432
19433function base64ToBytes (str) {
19434 return base64.toByteArray(base64clean(str))
19435}
19436
19437function blitBuffer (src, dst, offset, length) {
19438 for (var i = 0; i < length; ++i) {
19439 if ((i + offset >= dst.length) || (i >= src.length)) break
19440 dst[i + offset] = src[i]
19441 }
19442 return i
19443}
19444
19445// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
19446// the `instanceof` check but they should be treated as of that type.
19447// See: https://github.com/feross/buffer/issues/166
19448function isInstance (obj, type) {
19449 return obj instanceof type ||
19450 (obj != null && obj.constructor != null && obj.constructor.name != null &&
19451 obj.constructor.name === type.name)
19452}
19453function numberIsNaN (obj) {
19454 // For IE11 support
19455 return obj !== obj // eslint-disable-line no-self-compare
19456}
19457
19458}).call(this)}).call(this,require("buffer").Buffer)
19459},{"base64-js":26,"buffer":77,"ieee754":151}],78:[function(require,module,exports){
19460var Buffer = require('safe-buffer').Buffer
19461var Transform = require('stream').Transform
19462var StringDecoder = require('string_decoder').StringDecoder
19463var inherits = require('inherits')
19464
19465function CipherBase (hashMode) {
19466 Transform.call(this)
19467 this.hashMode = typeof hashMode === 'string'
19468 if (this.hashMode) {
19469 this[hashMode] = this._finalOrDigest
19470 } else {
19471 this.final = this._finalOrDigest
19472 }
19473 if (this._final) {
19474 this.__final = this._final
19475 this._final = null
19476 }
19477 this._decoder = null
19478 this._encoding = null
19479}
19480inherits(CipherBase, Transform)
19481
19482CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
19483 if (typeof data === 'string') {
19484 data = Buffer.from(data, inputEnc)
19485 }
19486
19487 var outData = this._update(data)
19488 if (this.hashMode) return this
19489
19490 if (outputEnc) {
19491 outData = this._toString(outData, outputEnc)
19492 }
19493
19494 return outData
19495}
19496
19497CipherBase.prototype.setAutoPadding = function () {}
19498CipherBase.prototype.getAuthTag = function () {
19499 throw new Error('trying to get auth tag in unsupported state')
19500}
19501
19502CipherBase.prototype.setAuthTag = function () {
19503 throw new Error('trying to set auth tag in unsupported state')
19504}
19505
19506CipherBase.prototype.setAAD = function () {
19507 throw new Error('trying to set aad in unsupported state')
19508}
19509
19510CipherBase.prototype._transform = function (data, _, next) {
19511 var err
19512 try {
19513 if (this.hashMode) {
19514 this._update(data)
19515 } else {
19516 this.push(this._update(data))
19517 }
19518 } catch (e) {
19519 err = e
19520 } finally {
19521 next(err)
19522 }
19523}
19524CipherBase.prototype._flush = function (done) {
19525 var err
19526 try {
19527 this.push(this.__final())
19528 } catch (e) {
19529 err = e
19530 }
19531
19532 done(err)
19533}
19534CipherBase.prototype._finalOrDigest = function (outputEnc) {
19535 var outData = this.__final() || Buffer.alloc(0)
19536 if (outputEnc) {
19537 outData = this._toString(outData, outputEnc, true)
19538 }
19539 return outData
19540}
19541
19542CipherBase.prototype._toString = function (value, enc, fin) {
19543 if (!this._decoder) {
19544 this._decoder = new StringDecoder(enc)
19545 this._encoding = enc
19546 }
19547
19548 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
19549
19550 var out = this._decoder.write(value)
19551 if (fin) {
19552 out += this._decoder.end()
19553 }
19554
19555 return out
19556}
19557
19558module.exports = CipherBase
19559
19560},{"inherits":152,"safe-buffer":200,"stream":210,"string_decoder":211}],79:[function(require,module,exports){
19561(function (Buffer){(function (){
19562// Copyright Joyent, Inc. and other Node contributors.
19563//
19564// Permission is hereby granted, free of charge, to any person obtaining a
19565// copy of this software and associated documentation files (the
19566// "Software"), to deal in the Software without restriction, including
19567// without limitation the rights to use, copy, modify, merge, publish,
19568// distribute, sublicense, and/or sell copies of the Software, and to permit
19569// persons to whom the Software is furnished to do so, subject to the
19570// following conditions:
19571//
19572// The above copyright notice and this permission notice shall be included
19573// in all copies or substantial portions of the Software.
19574//
19575// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19576// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19577// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
19578// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
19579// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19580// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19581// USE OR OTHER DEALINGS IN THE SOFTWARE.
19582
19583// NOTE: These type checking functions intentionally don't use `instanceof`
19584// because it is fragile and can be easily faked with `Object.create()`.
19585
19586function isArray(arg) {
19587 if (Array.isArray) {
19588 return Array.isArray(arg);
19589 }
19590 return objectToString(arg) === '[object Array]';
19591}
19592exports.isArray = isArray;
19593
19594function isBoolean(arg) {
19595 return typeof arg === 'boolean';
19596}
19597exports.isBoolean = isBoolean;
19598
19599function isNull(arg) {
19600 return arg === null;
19601}
19602exports.isNull = isNull;
19603
19604function isNullOrUndefined(arg) {
19605 return arg == null;
19606}
19607exports.isNullOrUndefined = isNullOrUndefined;
19608
19609function isNumber(arg) {
19610 return typeof arg === 'number';
19611}
19612exports.isNumber = isNumber;
19613
19614function isString(arg) {
19615 return typeof arg === 'string';
19616}
19617exports.isString = isString;
19618
19619function isSymbol(arg) {
19620 return typeof arg === 'symbol';
19621}
19622exports.isSymbol = isSymbol;
19623
19624function isUndefined(arg) {
19625 return arg === void 0;
19626}
19627exports.isUndefined = isUndefined;
19628
19629function isRegExp(re) {
19630 return objectToString(re) === '[object RegExp]';
19631}
19632exports.isRegExp = isRegExp;
19633
19634function isObject(arg) {
19635 return typeof arg === 'object' && arg !== null;
19636}
19637exports.isObject = isObject;
19638
19639function isDate(d) {
19640 return objectToString(d) === '[object Date]';
19641}
19642exports.isDate = isDate;
19643
19644function isError(e) {
19645 return (objectToString(e) === '[object Error]' || e instanceof Error);
19646}
19647exports.isError = isError;
19648
19649function isFunction(arg) {
19650 return typeof arg === 'function';
19651}
19652exports.isFunction = isFunction;
19653
19654function isPrimitive(arg) {
19655 return arg === null ||
19656 typeof arg === 'boolean' ||
19657 typeof arg === 'number' ||
19658 typeof arg === 'string' ||
19659 typeof arg === 'symbol' || // ES6 symbol
19660 typeof arg === 'undefined';
19661}
19662exports.isPrimitive = isPrimitive;
19663
19664exports.isBuffer = Buffer.isBuffer;
19665
19666function objectToString(o) {
19667 return Object.prototype.toString.call(o);
19668}
19669
19670}).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
19671},{"../../is-buffer/index.js":153}],80:[function(require,module,exports){
19672(function (Buffer){(function (){
19673var elliptic = require('elliptic')
19674var BN = require('bn.js')
19675
19676module.exports = function createECDH (curve) {
19677 return new ECDH(curve)
19678}
19679
19680var aliases = {
19681 secp256k1: {
19682 name: 'secp256k1',
19683 byteLength: 32
19684 },
19685 secp224r1: {
19686 name: 'p224',
19687 byteLength: 28
19688 },
19689 prime256v1: {
19690 name: 'p256',
19691 byteLength: 32
19692 },
19693 prime192v1: {
19694 name: 'p192',
19695 byteLength: 24
19696 },
19697 ed25519: {
19698 name: 'ed25519',
19699 byteLength: 32
19700 },
19701 secp384r1: {
19702 name: 'p384',
19703 byteLength: 48
19704 },
19705 secp521r1: {
19706 name: 'p521',
19707 byteLength: 66
19708 }
19709}
19710
19711aliases.p224 = aliases.secp224r1
19712aliases.p256 = aliases.secp256r1 = aliases.prime256v1
19713aliases.p192 = aliases.secp192r1 = aliases.prime192v1
19714aliases.p384 = aliases.secp384r1
19715aliases.p521 = aliases.secp521r1
19716
19717function ECDH (curve) {
19718 this.curveType = aliases[curve]
19719 if (!this.curveType) {
19720 this.curveType = {
19721 name: curve
19722 }
19723 }
19724 this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
19725 this.keys = void 0
19726}
19727
19728ECDH.prototype.generateKeys = function (enc, format) {
19729 this.keys = this.curve.genKeyPair()
19730 return this.getPublicKey(enc, format)
19731}
19732
19733ECDH.prototype.computeSecret = function (other, inenc, enc) {
19734 inenc = inenc || 'utf8'
19735 if (!Buffer.isBuffer(other)) {
19736 other = new Buffer(other, inenc)
19737 }
19738 var otherPub = this.curve.keyFromPublic(other).getPublic()
19739 var out = otherPub.mul(this.keys.getPrivate()).getX()
19740 return formatReturnValue(out, enc, this.curveType.byteLength)
19741}
19742
19743ECDH.prototype.getPublicKey = function (enc, format) {
19744 var key = this.keys.getPublic(format === 'compressed', true)
19745 if (format === 'hybrid') {
19746 if (key[key.length - 1] % 2) {
19747 key[0] = 7
19748 } else {
19749 key[0] = 6
19750 }
19751 }
19752 return formatReturnValue(key, enc)
19753}
19754
19755ECDH.prototype.getPrivateKey = function (enc) {
19756 return formatReturnValue(this.keys.getPrivate(), enc)
19757}
19758
19759ECDH.prototype.setPublicKey = function (pub, enc) {
19760 enc = enc || 'utf8'
19761 if (!Buffer.isBuffer(pub)) {
19762 pub = new Buffer(pub, enc)
19763 }
19764 this.keys._importPublic(pub)
19765 return this
19766}
19767
19768ECDH.prototype.setPrivateKey = function (priv, enc) {
19769 enc = enc || 'utf8'
19770 if (!Buffer.isBuffer(priv)) {
19771 priv = new Buffer(priv, enc)
19772 }
19773
19774 var _priv = new BN(priv)
19775 _priv = _priv.toString(16)
19776 this.keys = this.curve.genKeyPair()
19777 this.keys._importPrivate(_priv)
19778 return this
19779}
19780
19781function formatReturnValue (bn, enc, len) {
19782 if (!Array.isArray(bn)) {
19783 bn = bn.toArray()
19784 }
19785 var buf = new Buffer(bn)
19786 if (len && buf.length < len) {
19787 var zeros = new Buffer(len - buf.length)
19788 zeros.fill(0)
19789 buf = Buffer.concat([zeros, buf])
19790 }
19791 if (!enc) {
19792 return buf
19793 } else {
19794 return buf.toString(enc)
19795 }
19796}
19797
19798}).call(this)}).call(this,require("buffer").Buffer)
19799},{"bn.js":81,"buffer":77,"elliptic":103}],81:[function(require,module,exports){
19800arguments[4][21][0].apply(exports,arguments)
19801},{"buffer":33,"dup":21}],82:[function(require,module,exports){
19802'use strict'
19803var inherits = require('inherits')
19804var MD5 = require('md5.js')
19805var RIPEMD160 = require('ripemd160')
19806var sha = require('sha.js')
19807var Base = require('cipher-base')
19808
19809function Hash (hash) {
19810 Base.call(this, 'digest')
19811
19812 this._hash = hash
19813}
19814
19815inherits(Hash, Base)
19816
19817Hash.prototype._update = function (data) {
19818 this._hash.update(data)
19819}
19820
19821Hash.prototype._final = function () {
19822 return this._hash.digest()
19823}
19824
19825module.exports = function createHash (alg) {
19826 alg = alg.toLowerCase()
19827 if (alg === 'md5') return new MD5()
19828 if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()
19829
19830 return new Hash(sha(alg))
19831}
19832
19833},{"cipher-base":78,"inherits":152,"md5.js":156,"ripemd160":199,"sha.js":203}],83:[function(require,module,exports){
19834var MD5 = require('md5.js')
19835
19836module.exports = function (buffer) {
19837 return new MD5().update(buffer).digest()
19838}
19839
19840},{"md5.js":156}],84:[function(require,module,exports){
19841'use strict'
19842var inherits = require('inherits')
19843var Legacy = require('./legacy')
19844var Base = require('cipher-base')
19845var Buffer = require('safe-buffer').Buffer
19846var md5 = require('create-hash/md5')
19847var RIPEMD160 = require('ripemd160')
19848
19849var sha = require('sha.js')
19850
19851var ZEROS = Buffer.alloc(128)
19852
19853function Hmac (alg, key) {
19854 Base.call(this, 'digest')
19855 if (typeof key === 'string') {
19856 key = Buffer.from(key)
19857 }
19858
19859 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
19860
19861 this._alg = alg
19862 this._key = key
19863 if (key.length > blocksize) {
19864 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
19865 key = hash.update(key).digest()
19866 } else if (key.length < blocksize) {
19867 key = Buffer.concat([key, ZEROS], blocksize)
19868 }
19869
19870 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
19871 var opad = this._opad = Buffer.allocUnsafe(blocksize)
19872
19873 for (var i = 0; i < blocksize; i++) {
19874 ipad[i] = key[i] ^ 0x36
19875 opad[i] = key[i] ^ 0x5C
19876 }
19877 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
19878 this._hash.update(ipad)
19879}
19880
19881inherits(Hmac, Base)
19882
19883Hmac.prototype._update = function (data) {
19884 this._hash.update(data)
19885}
19886
19887Hmac.prototype._final = function () {
19888 var h = this._hash.digest()
19889 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
19890 return hash.update(this._opad).update(h).digest()
19891}
19892
19893module.exports = function createHmac (alg, key) {
19894 alg = alg.toLowerCase()
19895 if (alg === 'rmd160' || alg === 'ripemd160') {
19896 return new Hmac('rmd160', key)
19897 }
19898 if (alg === 'md5') {
19899 return new Legacy(md5, key)
19900 }
19901 return new Hmac(alg, key)
19902}
19903
19904},{"./legacy":85,"cipher-base":78,"create-hash/md5":83,"inherits":152,"ripemd160":199,"safe-buffer":200,"sha.js":203}],85:[function(require,module,exports){
19905'use strict'
19906var inherits = require('inherits')
19907var Buffer = require('safe-buffer').Buffer
19908
19909var Base = require('cipher-base')
19910
19911var ZEROS = Buffer.alloc(128)
19912var blocksize = 64
19913
19914function Hmac (alg, key) {
19915 Base.call(this, 'digest')
19916 if (typeof key === 'string') {
19917 key = Buffer.from(key)
19918 }
19919
19920 this._alg = alg
19921 this._key = key
19922
19923 if (key.length > blocksize) {
19924 key = alg(key)
19925 } else if (key.length < blocksize) {
19926 key = Buffer.concat([key, ZEROS], blocksize)
19927 }
19928
19929 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
19930 var opad = this._opad = Buffer.allocUnsafe(blocksize)
19931
19932 for (var i = 0; i < blocksize; i++) {
19933 ipad[i] = key[i] ^ 0x36
19934 opad[i] = key[i] ^ 0x5C
19935 }
19936
19937 this._hash = [ipad]
19938}
19939
19940inherits(Hmac, Base)
19941
19942Hmac.prototype._update = function (data) {
19943 this._hash.push(data)
19944}
19945
19946Hmac.prototype._final = function () {
19947 var h = this._alg(Buffer.concat(this._hash))
19948 return this._alg(Buffer.concat([this._opad, h]))
19949}
19950module.exports = Hmac
19951
19952},{"cipher-base":78,"inherits":152,"safe-buffer":200}],86:[function(require,module,exports){
19953'use strict'
19954
19955exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
19956exports.createHash = exports.Hash = require('create-hash')
19957exports.createHmac = exports.Hmac = require('create-hmac')
19958
19959var algos = require('browserify-sign/algos')
19960var algoKeys = Object.keys(algos)
19961var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
19962exports.getHashes = function () {
19963 return hashes
19964}
19965
19966var p = require('pbkdf2')
19967exports.pbkdf2 = p.pbkdf2
19968exports.pbkdf2Sync = p.pbkdf2Sync
19969
19970var aes = require('browserify-cipher')
19971
19972exports.Cipher = aes.Cipher
19973exports.createCipher = aes.createCipher
19974exports.Cipheriv = aes.Cipheriv
19975exports.createCipheriv = aes.createCipheriv
19976exports.Decipher = aes.Decipher
19977exports.createDecipher = aes.createDecipher
19978exports.Decipheriv = aes.Decipheriv
19979exports.createDecipheriv = aes.createDecipheriv
19980exports.getCiphers = aes.getCiphers
19981exports.listCiphers = aes.listCiphers
19982
19983var dh = require('diffie-hellman')
19984
19985exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
19986exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
19987exports.getDiffieHellman = dh.getDiffieHellman
19988exports.createDiffieHellman = dh.createDiffieHellman
19989exports.DiffieHellman = dh.DiffieHellman
19990
19991var sign = require('browserify-sign')
19992
19993exports.createSign = sign.createSign
19994exports.Sign = sign.Sign
19995exports.createVerify = sign.createVerify
19996exports.Verify = sign.Verify
19997
19998exports.createECDH = require('create-ecdh')
19999
20000var publicEncrypt = require('public-encrypt')
20001
20002exports.publicEncrypt = publicEncrypt.publicEncrypt
20003exports.privateEncrypt = publicEncrypt.privateEncrypt
20004exports.publicDecrypt = publicEncrypt.publicDecrypt
20005exports.privateDecrypt = publicEncrypt.privateDecrypt
20006
20007// the least I can do is make error messages for the rest of the node.js/crypto api.
20008// ;[
20009// 'createCredentials'
20010// ].forEach(function (name) {
20011// exports[name] = function () {
20012// throw new Error([
20013// 'sorry, ' + name + ' is not implemented yet',
20014// 'we accept pull requests',
20015// 'https://github.com/crypto-browserify/crypto-browserify'
20016// ].join('\n'))
20017// }
20018// })
20019
20020var rf = require('randomfill')
20021
20022exports.randomFill = rf.randomFill
20023exports.randomFillSync = rf.randomFillSync
20024
20025exports.createCredentials = function () {
20026 throw new Error([
20027 'sorry, createCredentials is not implemented yet',
20028 'we accept pull requests',
20029 'https://github.com/crypto-browserify/crypto-browserify'
20030 ].join('\n'))
20031}
20032
20033exports.constants = {
20034 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
20035 'DH_CHECK_P_NOT_PRIME': 1,
20036 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
20037 'DH_NOT_SUITABLE_GENERATOR': 8,
20038 'NPN_ENABLED': 1,
20039 'ALPN_ENABLED': 1,
20040 'RSA_PKCS1_PADDING': 1,
20041 'RSA_SSLV23_PADDING': 2,
20042 'RSA_NO_PADDING': 3,
20043 'RSA_PKCS1_OAEP_PADDING': 4,
20044 'RSA_X931_PADDING': 5,
20045 'RSA_PKCS1_PSS_PADDING': 6,
20046 'POINT_CONVERSION_COMPRESSED': 2,
20047 'POINT_CONVERSION_UNCOMPRESSED': 4,
20048 'POINT_CONVERSION_HYBRID': 6
20049}
20050
20051},{"browserify-cipher":51,"browserify-sign":58,"browserify-sign/algos":55,"create-ecdh":80,"create-hash":82,"create-hmac":84,"diffie-hellman":93,"pbkdf2":167,"public-encrypt":175,"randombytes":182,"randomfill":183}],87:[function(require,module,exports){
20052'use strict';
20053
20054exports.utils = require('./des/utils');
20055exports.Cipher = require('./des/cipher');
20056exports.DES = require('./des/des');
20057exports.CBC = require('./des/cbc');
20058exports.EDE = require('./des/ede');
20059
20060},{"./des/cbc":88,"./des/cipher":89,"./des/des":90,"./des/ede":91,"./des/utils":92}],88:[function(require,module,exports){
20061'use strict';
20062
20063var assert = require('minimalistic-assert');
20064var inherits = require('inherits');
20065
20066var proto = {};
20067
20068function CBCState(iv) {
20069 assert.equal(iv.length, 8, 'Invalid IV length');
20070
20071 this.iv = new Array(8);
20072 for (var i = 0; i < this.iv.length; i++)
20073 this.iv[i] = iv[i];
20074}
20075
20076function instantiate(Base) {
20077 function CBC(options) {
20078 Base.call(this, options);
20079 this._cbcInit();
20080 }
20081 inherits(CBC, Base);
20082
20083 var keys = Object.keys(proto);
20084 for (var i = 0; i < keys.length; i++) {
20085 var key = keys[i];
20086 CBC.prototype[key] = proto[key];
20087 }
20088
20089 CBC.create = function create(options) {
20090 return new CBC(options);
20091 };
20092
20093 return CBC;
20094}
20095
20096exports.instantiate = instantiate;
20097
20098proto._cbcInit = function _cbcInit() {
20099 var state = new CBCState(this.options.iv);
20100 this._cbcState = state;
20101};
20102
20103proto._update = function _update(inp, inOff, out, outOff) {
20104 var state = this._cbcState;
20105 var superProto = this.constructor.super_.prototype;
20106
20107 var iv = state.iv;
20108 if (this.type === 'encrypt') {
20109 for (var i = 0; i < this.blockSize; i++)
20110 iv[i] ^= inp[inOff + i];
20111
20112 superProto._update.call(this, iv, 0, out, outOff);
20113
20114 for (var i = 0; i < this.blockSize; i++)
20115 iv[i] = out[outOff + i];
20116 } else {
20117 superProto._update.call(this, inp, inOff, out, outOff);
20118
20119 for (var i = 0; i < this.blockSize; i++)
20120 out[outOff + i] ^= iv[i];
20121
20122 for (var i = 0; i < this.blockSize; i++)
20123 iv[i] = inp[inOff + i];
20124 }
20125};
20126
20127},{"inherits":152,"minimalistic-assert":159}],89:[function(require,module,exports){
20128'use strict';
20129
20130var assert = require('minimalistic-assert');
20131
20132function Cipher(options) {
20133 this.options = options;
20134
20135 this.type = this.options.type;
20136 this.blockSize = 8;
20137 this._init();
20138
20139 this.buffer = new Array(this.blockSize);
20140 this.bufferOff = 0;
20141}
20142module.exports = Cipher;
20143
20144Cipher.prototype._init = function _init() {
20145 // Might be overrided
20146};
20147
20148Cipher.prototype.update = function update(data) {
20149 if (data.length === 0)
20150 return [];
20151
20152 if (this.type === 'decrypt')
20153 return this._updateDecrypt(data);
20154 else
20155 return this._updateEncrypt(data);
20156};
20157
20158Cipher.prototype._buffer = function _buffer(data, off) {
20159 // Append data to buffer
20160 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
20161 for (var i = 0; i < min; i++)
20162 this.buffer[this.bufferOff + i] = data[off + i];
20163 this.bufferOff += min;
20164
20165 // Shift next
20166 return min;
20167};
20168
20169Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
20170 this._update(this.buffer, 0, out, off);
20171 this.bufferOff = 0;
20172 return this.blockSize;
20173};
20174
20175Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
20176 var inputOff = 0;
20177 var outputOff = 0;
20178
20179 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
20180 var out = new Array(count * this.blockSize);
20181
20182 if (this.bufferOff !== 0) {
20183 inputOff += this._buffer(data, inputOff);
20184
20185 if (this.bufferOff === this.buffer.length)
20186 outputOff += this._flushBuffer(out, outputOff);
20187 }
20188
20189 // Write blocks
20190 var max = data.length - ((data.length - inputOff) % this.blockSize);
20191 for (; inputOff < max; inputOff += this.blockSize) {
20192 this._update(data, inputOff, out, outputOff);
20193 outputOff += this.blockSize;
20194 }
20195
20196 // Queue rest
20197 for (; inputOff < data.length; inputOff++, this.bufferOff++)
20198 this.buffer[this.bufferOff] = data[inputOff];
20199
20200 return out;
20201};
20202
20203Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
20204 var inputOff = 0;
20205 var outputOff = 0;
20206
20207 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
20208 var out = new Array(count * this.blockSize);
20209
20210 // TODO(indutny): optimize it, this is far from optimal
20211 for (; count > 0; count--) {
20212 inputOff += this._buffer(data, inputOff);
20213 outputOff += this._flushBuffer(out, outputOff);
20214 }
20215
20216 // Buffer rest of the input
20217 inputOff += this._buffer(data, inputOff);
20218
20219 return out;
20220};
20221
20222Cipher.prototype.final = function final(buffer) {
20223 var first;
20224 if (buffer)
20225 first = this.update(buffer);
20226
20227 var last;
20228 if (this.type === 'encrypt')
20229 last = this._finalEncrypt();
20230 else
20231 last = this._finalDecrypt();
20232
20233 if (first)
20234 return first.concat(last);
20235 else
20236 return last;
20237};
20238
20239Cipher.prototype._pad = function _pad(buffer, off) {
20240 if (off === 0)
20241 return false;
20242
20243 while (off < buffer.length)
20244 buffer[off++] = 0;
20245
20246 return true;
20247};
20248
20249Cipher.prototype._finalEncrypt = function _finalEncrypt() {
20250 if (!this._pad(this.buffer, this.bufferOff))
20251 return [];
20252
20253 var out = new Array(this.blockSize);
20254 this._update(this.buffer, 0, out, 0);
20255 return out;
20256};
20257
20258Cipher.prototype._unpad = function _unpad(buffer) {
20259 return buffer;
20260};
20261
20262Cipher.prototype._finalDecrypt = function _finalDecrypt() {
20263 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
20264 var out = new Array(this.blockSize);
20265 this._flushBuffer(out, 0);
20266
20267 return this._unpad(out);
20268};
20269
20270},{"minimalistic-assert":159}],90:[function(require,module,exports){
20271'use strict';
20272
20273var assert = require('minimalistic-assert');
20274var inherits = require('inherits');
20275
20276var utils = require('./utils');
20277var Cipher = require('./cipher');
20278
20279function DESState() {
20280 this.tmp = new Array(2);
20281 this.keys = null;
20282}
20283
20284function DES(options) {
20285 Cipher.call(this, options);
20286
20287 var state = new DESState();
20288 this._desState = state;
20289
20290 this.deriveKeys(state, options.key);
20291}
20292inherits(DES, Cipher);
20293module.exports = DES;
20294
20295DES.create = function create(options) {
20296 return new DES(options);
20297};
20298
20299var shiftTable = [
20300 1, 1, 2, 2, 2, 2, 2, 2,
20301 1, 2, 2, 2, 2, 2, 2, 1
20302];
20303
20304DES.prototype.deriveKeys = function deriveKeys(state, key) {
20305 state.keys = new Array(16 * 2);
20306
20307 assert.equal(key.length, this.blockSize, 'Invalid key length');
20308
20309 var kL = utils.readUInt32BE(key, 0);
20310 var kR = utils.readUInt32BE(key, 4);
20311
20312 utils.pc1(kL, kR, state.tmp, 0);
20313 kL = state.tmp[0];
20314 kR = state.tmp[1];
20315 for (var i = 0; i < state.keys.length; i += 2) {
20316 var shift = shiftTable[i >>> 1];
20317 kL = utils.r28shl(kL, shift);
20318 kR = utils.r28shl(kR, shift);
20319 utils.pc2(kL, kR, state.keys, i);
20320 }
20321};
20322
20323DES.prototype._update = function _update(inp, inOff, out, outOff) {
20324 var state = this._desState;
20325
20326 var l = utils.readUInt32BE(inp, inOff);
20327 var r = utils.readUInt32BE(inp, inOff + 4);
20328
20329 // Initial Permutation
20330 utils.ip(l, r, state.tmp, 0);
20331 l = state.tmp[0];
20332 r = state.tmp[1];
20333
20334 if (this.type === 'encrypt')
20335 this._encrypt(state, l, r, state.tmp, 0);
20336 else
20337 this._decrypt(state, l, r, state.tmp, 0);
20338
20339 l = state.tmp[0];
20340 r = state.tmp[1];
20341
20342 utils.writeUInt32BE(out, l, outOff);
20343 utils.writeUInt32BE(out, r, outOff + 4);
20344};
20345
20346DES.prototype._pad = function _pad(buffer, off) {
20347 var value = buffer.length - off;
20348 for (var i = off; i < buffer.length; i++)
20349 buffer[i] = value;
20350
20351 return true;
20352};
20353
20354DES.prototype._unpad = function _unpad(buffer) {
20355 var pad = buffer[buffer.length - 1];
20356 for (var i = buffer.length - pad; i < buffer.length; i++)
20357 assert.equal(buffer[i], pad);
20358
20359 return buffer.slice(0, buffer.length - pad);
20360};
20361
20362DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
20363 var l = lStart;
20364 var r = rStart;
20365
20366 // Apply f() x16 times
20367 for (var i = 0; i < state.keys.length; i += 2) {
20368 var keyL = state.keys[i];
20369 var keyR = state.keys[i + 1];
20370
20371 // f(r, k)
20372 utils.expand(r, state.tmp, 0);
20373
20374 keyL ^= state.tmp[0];
20375 keyR ^= state.tmp[1];
20376 var s = utils.substitute(keyL, keyR);
20377 var f = utils.permute(s);
20378
20379 var t = r;
20380 r = (l ^ f) >>> 0;
20381 l = t;
20382 }
20383
20384 // Reverse Initial Permutation
20385 utils.rip(r, l, out, off);
20386};
20387
20388DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
20389 var l = rStart;
20390 var r = lStart;
20391
20392 // Apply f() x16 times
20393 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
20394 var keyL = state.keys[i];
20395 var keyR = state.keys[i + 1];
20396
20397 // f(r, k)
20398 utils.expand(l, state.tmp, 0);
20399
20400 keyL ^= state.tmp[0];
20401 keyR ^= state.tmp[1];
20402 var s = utils.substitute(keyL, keyR);
20403 var f = utils.permute(s);
20404
20405 var t = l;
20406 l = (r ^ f) >>> 0;
20407 r = t;
20408 }
20409
20410 // Reverse Initial Permutation
20411 utils.rip(l, r, out, off);
20412};
20413
20414},{"./cipher":89,"./utils":92,"inherits":152,"minimalistic-assert":159}],91:[function(require,module,exports){
20415'use strict';
20416
20417var assert = require('minimalistic-assert');
20418var inherits = require('inherits');
20419
20420var Cipher = require('./cipher');
20421var DES = require('./des');
20422
20423function EDEState(type, key) {
20424 assert.equal(key.length, 24, 'Invalid key length');
20425
20426 var k1 = key.slice(0, 8);
20427 var k2 = key.slice(8, 16);
20428 var k3 = key.slice(16, 24);
20429
20430 if (type === 'encrypt') {
20431 this.ciphers = [
20432 DES.create({ type: 'encrypt', key: k1 }),
20433 DES.create({ type: 'decrypt', key: k2 }),
20434 DES.create({ type: 'encrypt', key: k3 })
20435 ];
20436 } else {
20437 this.ciphers = [
20438 DES.create({ type: 'decrypt', key: k3 }),
20439 DES.create({ type: 'encrypt', key: k2 }),
20440 DES.create({ type: 'decrypt', key: k1 })
20441 ];
20442 }
20443}
20444
20445function EDE(options) {
20446 Cipher.call(this, options);
20447
20448 var state = new EDEState(this.type, this.options.key);
20449 this._edeState = state;
20450}
20451inherits(EDE, Cipher);
20452
20453module.exports = EDE;
20454
20455EDE.create = function create(options) {
20456 return new EDE(options);
20457};
20458
20459EDE.prototype._update = function _update(inp, inOff, out, outOff) {
20460 var state = this._edeState;
20461
20462 state.ciphers[0]._update(inp, inOff, out, outOff);
20463 state.ciphers[1]._update(out, outOff, out, outOff);
20464 state.ciphers[2]._update(out, outOff, out, outOff);
20465};
20466
20467EDE.prototype._pad = DES.prototype._pad;
20468EDE.prototype._unpad = DES.prototype._unpad;
20469
20470},{"./cipher":89,"./des":90,"inherits":152,"minimalistic-assert":159}],92:[function(require,module,exports){
20471'use strict';
20472
20473exports.readUInt32BE = function readUInt32BE(bytes, off) {
20474 var res = (bytes[0 + off] << 24) |
20475 (bytes[1 + off] << 16) |
20476 (bytes[2 + off] << 8) |
20477 bytes[3 + off];
20478 return res >>> 0;
20479};
20480
20481exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
20482 bytes[0 + off] = value >>> 24;
20483 bytes[1 + off] = (value >>> 16) & 0xff;
20484 bytes[2 + off] = (value >>> 8) & 0xff;
20485 bytes[3 + off] = value & 0xff;
20486};
20487
20488exports.ip = function ip(inL, inR, out, off) {
20489 var outL = 0;
20490 var outR = 0;
20491
20492 for (var i = 6; i >= 0; i -= 2) {
20493 for (var j = 0; j <= 24; j += 8) {
20494 outL <<= 1;
20495 outL |= (inR >>> (j + i)) & 1;
20496 }
20497 for (var j = 0; j <= 24; j += 8) {
20498 outL <<= 1;
20499 outL |= (inL >>> (j + i)) & 1;
20500 }
20501 }
20502
20503 for (var i = 6; i >= 0; i -= 2) {
20504 for (var j = 1; j <= 25; j += 8) {
20505 outR <<= 1;
20506 outR |= (inR >>> (j + i)) & 1;
20507 }
20508 for (var j = 1; j <= 25; j += 8) {
20509 outR <<= 1;
20510 outR |= (inL >>> (j + i)) & 1;
20511 }
20512 }
20513
20514 out[off + 0] = outL >>> 0;
20515 out[off + 1] = outR >>> 0;
20516};
20517
20518exports.rip = function rip(inL, inR, out, off) {
20519 var outL = 0;
20520 var outR = 0;
20521
20522 for (var i = 0; i < 4; i++) {
20523 for (var j = 24; j >= 0; j -= 8) {
20524 outL <<= 1;
20525 outL |= (inR >>> (j + i)) & 1;
20526 outL <<= 1;
20527 outL |= (inL >>> (j + i)) & 1;
20528 }
20529 }
20530 for (var i = 4; i < 8; i++) {
20531 for (var j = 24; j >= 0; j -= 8) {
20532 outR <<= 1;
20533 outR |= (inR >>> (j + i)) & 1;
20534 outR <<= 1;
20535 outR |= (inL >>> (j + i)) & 1;
20536 }
20537 }
20538
20539 out[off + 0] = outL >>> 0;
20540 out[off + 1] = outR >>> 0;
20541};
20542
20543exports.pc1 = function pc1(inL, inR, out, off) {
20544 var outL = 0;
20545 var outR = 0;
20546
20547 // 7, 15, 23, 31, 39, 47, 55, 63
20548 // 6, 14, 22, 30, 39, 47, 55, 63
20549 // 5, 13, 21, 29, 39, 47, 55, 63
20550 // 4, 12, 20, 28
20551 for (var i = 7; i >= 5; i--) {
20552 for (var j = 0; j <= 24; j += 8) {
20553 outL <<= 1;
20554 outL |= (inR >> (j + i)) & 1;
20555 }
20556 for (var j = 0; j <= 24; j += 8) {
20557 outL <<= 1;
20558 outL |= (inL >> (j + i)) & 1;
20559 }
20560 }
20561 for (var j = 0; j <= 24; j += 8) {
20562 outL <<= 1;
20563 outL |= (inR >> (j + i)) & 1;
20564 }
20565
20566 // 1, 9, 17, 25, 33, 41, 49, 57
20567 // 2, 10, 18, 26, 34, 42, 50, 58
20568 // 3, 11, 19, 27, 35, 43, 51, 59
20569 // 36, 44, 52, 60
20570 for (var i = 1; i <= 3; i++) {
20571 for (var j = 0; j <= 24; j += 8) {
20572 outR <<= 1;
20573 outR |= (inR >> (j + i)) & 1;
20574 }
20575 for (var j = 0; j <= 24; j += 8) {
20576 outR <<= 1;
20577 outR |= (inL >> (j + i)) & 1;
20578 }
20579 }
20580 for (var j = 0; j <= 24; j += 8) {
20581 outR <<= 1;
20582 outR |= (inL >> (j + i)) & 1;
20583 }
20584
20585 out[off + 0] = outL >>> 0;
20586 out[off + 1] = outR >>> 0;
20587};
20588
20589exports.r28shl = function r28shl(num, shift) {
20590 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
20591};
20592
20593var pc2table = [
20594 // inL => outL
20595 14, 11, 17, 4, 27, 23, 25, 0,
20596 13, 22, 7, 18, 5, 9, 16, 24,
20597 2, 20, 12, 21, 1, 8, 15, 26,
20598
20599 // inR => outR
20600 15, 4, 25, 19, 9, 1, 26, 16,
20601 5, 11, 23, 8, 12, 7, 17, 0,
20602 22, 3, 10, 14, 6, 20, 27, 24
20603];
20604
20605exports.pc2 = function pc2(inL, inR, out, off) {
20606 var outL = 0;
20607 var outR = 0;
20608
20609 var len = pc2table.length >>> 1;
20610 for (var i = 0; i < len; i++) {
20611 outL <<= 1;
20612 outL |= (inL >>> pc2table[i]) & 0x1;
20613 }
20614 for (var i = len; i < pc2table.length; i++) {
20615 outR <<= 1;
20616 outR |= (inR >>> pc2table[i]) & 0x1;
20617 }
20618
20619 out[off + 0] = outL >>> 0;
20620 out[off + 1] = outR >>> 0;
20621};
20622
20623exports.expand = function expand(r, out, off) {
20624 var outL = 0;
20625 var outR = 0;
20626
20627 outL = ((r & 1) << 5) | (r >>> 27);
20628 for (var i = 23; i >= 15; i -= 4) {
20629 outL <<= 6;
20630 outL |= (r >>> i) & 0x3f;
20631 }
20632 for (var i = 11; i >= 3; i -= 4) {
20633 outR |= (r >>> i) & 0x3f;
20634 outR <<= 6;
20635 }
20636 outR |= ((r & 0x1f) << 1) | (r >>> 31);
20637
20638 out[off + 0] = outL >>> 0;
20639 out[off + 1] = outR >>> 0;
20640};
20641
20642var sTable = [
20643 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
20644 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
20645 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
20646 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
20647
20648 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
20649 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
20650 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
20651 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
20652
20653 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
20654 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
20655 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
20656 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
20657
20658 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
20659 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
20660 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
20661 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
20662
20663 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
20664 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
20665 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
20666 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
20667
20668 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
20669 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
20670 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
20671 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
20672
20673 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
20674 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
20675 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
20676 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
20677
20678 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
20679 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
20680 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
20681 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
20682];
20683
20684exports.substitute = function substitute(inL, inR) {
20685 var out = 0;
20686 for (var i = 0; i < 4; i++) {
20687 var b = (inL >>> (18 - i * 6)) & 0x3f;
20688 var sb = sTable[i * 0x40 + b];
20689
20690 out <<= 4;
20691 out |= sb;
20692 }
20693 for (var i = 0; i < 4; i++) {
20694 var b = (inR >>> (18 - i * 6)) & 0x3f;
20695 var sb = sTable[4 * 0x40 + i * 0x40 + b];
20696
20697 out <<= 4;
20698 out |= sb;
20699 }
20700 return out >>> 0;
20701};
20702
20703var permuteTable = [
20704 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
20705 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
20706];
20707
20708exports.permute = function permute(num) {
20709 var out = 0;
20710 for (var i = 0; i < permuteTable.length; i++) {
20711 out <<= 1;
20712 out |= (num >>> permuteTable[i]) & 0x1;
20713 }
20714 return out >>> 0;
20715};
20716
20717exports.padSplit = function padSplit(num, size, group) {
20718 var str = num.toString(2);
20719 while (str.length < size)
20720 str = '0' + str;
20721
20722 var out = [];
20723 for (var i = 0; i < size; i += group)
20724 out.push(str.slice(i, i + group));
20725 return out.join(' ');
20726};
20727
20728},{}],93:[function(require,module,exports){
20729(function (Buffer){(function (){
20730var generatePrime = require('./lib/generatePrime')
20731var primes = require('./lib/primes.json')
20732
20733var DH = require('./lib/dh')
20734
20735function getDiffieHellman (mod) {
20736 var prime = new Buffer(primes[mod].prime, 'hex')
20737 var gen = new Buffer(primes[mod].gen, 'hex')
20738
20739 return new DH(prime, gen)
20740}
20741
20742var ENCODINGS = {
20743 'binary': true, 'hex': true, 'base64': true
20744}
20745
20746function createDiffieHellman (prime, enc, generator, genc) {
20747 if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
20748 return createDiffieHellman(prime, 'binary', enc, generator)
20749 }
20750
20751 enc = enc || 'binary'
20752 genc = genc || 'binary'
20753 generator = generator || new Buffer([2])
20754
20755 if (!Buffer.isBuffer(generator)) {
20756 generator = new Buffer(generator, genc)
20757 }
20758
20759 if (typeof prime === 'number') {
20760 return new DH(generatePrime(prime, generator), generator, true)
20761 }
20762
20763 if (!Buffer.isBuffer(prime)) {
20764 prime = new Buffer(prime, enc)
20765 }
20766
20767 return new DH(prime, generator, true)
20768}
20769
20770exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
20771exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
20772
20773}).call(this)}).call(this,require("buffer").Buffer)
20774},{"./lib/dh":94,"./lib/generatePrime":95,"./lib/primes.json":96,"buffer":77}],94:[function(require,module,exports){
20775(function (Buffer){(function (){
20776var BN = require('bn.js');
20777var MillerRabin = require('miller-rabin');
20778var millerRabin = new MillerRabin();
20779var TWENTYFOUR = new BN(24);
20780var ELEVEN = new BN(11);
20781var TEN = new BN(10);
20782var THREE = new BN(3);
20783var SEVEN = new BN(7);
20784var primes = require('./generatePrime');
20785var randomBytes = require('randombytes');
20786module.exports = DH;
20787
20788function setPublicKey(pub, enc) {
20789 enc = enc || 'utf8';
20790 if (!Buffer.isBuffer(pub)) {
20791 pub = new Buffer(pub, enc);
20792 }
20793 this._pub = new BN(pub);
20794 return this;
20795}
20796
20797function setPrivateKey(priv, enc) {
20798 enc = enc || 'utf8';
20799 if (!Buffer.isBuffer(priv)) {
20800 priv = new Buffer(priv, enc);
20801 }
20802 this._priv = new BN(priv);
20803 return this;
20804}
20805
20806var primeCache = {};
20807function checkPrime(prime, generator) {
20808 var gen = generator.toString('hex');
20809 var hex = [gen, prime.toString(16)].join('_');
20810 if (hex in primeCache) {
20811 return primeCache[hex];
20812 }
20813 var error = 0;
20814
20815 if (prime.isEven() ||
20816 !primes.simpleSieve ||
20817 !primes.fermatTest(prime) ||
20818 !millerRabin.test(prime)) {
20819 //not a prime so +1
20820 error += 1;
20821
20822 if (gen === '02' || gen === '05') {
20823 // we'd be able to check the generator
20824 // it would fail so +8
20825 error += 8;
20826 } else {
20827 //we wouldn't be able to test the generator
20828 // so +4
20829 error += 4;
20830 }
20831 primeCache[hex] = error;
20832 return error;
20833 }
20834 if (!millerRabin.test(prime.shrn(1))) {
20835 //not a safe prime
20836 error += 2;
20837 }
20838 var rem;
20839 switch (gen) {
20840 case '02':
20841 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
20842 // unsuidable generator
20843 error += 8;
20844 }
20845 break;
20846 case '05':
20847 rem = prime.mod(TEN);
20848 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
20849 // prime mod 10 needs to equal 3 or 7
20850 error += 8;
20851 }
20852 break;
20853 default:
20854 error += 4;
20855 }
20856 primeCache[hex] = error;
20857 return error;
20858}
20859
20860function DH(prime, generator, malleable) {
20861 this.setGenerator(generator);
20862 this.__prime = new BN(prime);
20863 this._prime = BN.mont(this.__prime);
20864 this._primeLen = prime.length;
20865 this._pub = undefined;
20866 this._priv = undefined;
20867 this._primeCode = undefined;
20868 if (malleable) {
20869 this.setPublicKey = setPublicKey;
20870 this.setPrivateKey = setPrivateKey;
20871 } else {
20872 this._primeCode = 8;
20873 }
20874}
20875Object.defineProperty(DH.prototype, 'verifyError', {
20876 enumerable: true,
20877 get: function () {
20878 if (typeof this._primeCode !== 'number') {
20879 this._primeCode = checkPrime(this.__prime, this.__gen);
20880 }
20881 return this._primeCode;
20882 }
20883});
20884DH.prototype.generateKeys = function () {
20885 if (!this._priv) {
20886 this._priv = new BN(randomBytes(this._primeLen));
20887 }
20888 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
20889 return this.getPublicKey();
20890};
20891
20892DH.prototype.computeSecret = function (other) {
20893 other = new BN(other);
20894 other = other.toRed(this._prime);
20895 var secret = other.redPow(this._priv).fromRed();
20896 var out = new Buffer(secret.toArray());
20897 var prime = this.getPrime();
20898 if (out.length < prime.length) {
20899 var front = new Buffer(prime.length - out.length);
20900 front.fill(0);
20901 out = Buffer.concat([front, out]);
20902 }
20903 return out;
20904};
20905
20906DH.prototype.getPublicKey = function getPublicKey(enc) {
20907 return formatReturnValue(this._pub, enc);
20908};
20909
20910DH.prototype.getPrivateKey = function getPrivateKey(enc) {
20911 return formatReturnValue(this._priv, enc);
20912};
20913
20914DH.prototype.getPrime = function (enc) {
20915 return formatReturnValue(this.__prime, enc);
20916};
20917
20918DH.prototype.getGenerator = function (enc) {
20919 return formatReturnValue(this._gen, enc);
20920};
20921
20922DH.prototype.setGenerator = function (gen, enc) {
20923 enc = enc || 'utf8';
20924 if (!Buffer.isBuffer(gen)) {
20925 gen = new Buffer(gen, enc);
20926 }
20927 this.__gen = gen;
20928 this._gen = new BN(gen);
20929 return this;
20930};
20931
20932function formatReturnValue(bn, enc) {
20933 var buf = new Buffer(bn.toArray());
20934 if (!enc) {
20935 return buf;
20936 } else {
20937 return buf.toString(enc);
20938 }
20939}
20940
20941}).call(this)}).call(this,require("buffer").Buffer)
20942},{"./generatePrime":95,"bn.js":97,"buffer":77,"miller-rabin":157,"randombytes":182}],95:[function(require,module,exports){
20943var randomBytes = require('randombytes');
20944module.exports = findPrime;
20945findPrime.simpleSieve = simpleSieve;
20946findPrime.fermatTest = fermatTest;
20947var BN = require('bn.js');
20948var TWENTYFOUR = new BN(24);
20949var MillerRabin = require('miller-rabin');
20950var millerRabin = new MillerRabin();
20951var ONE = new BN(1);
20952var TWO = new BN(2);
20953var FIVE = new BN(5);
20954var SIXTEEN = new BN(16);
20955var EIGHT = new BN(8);
20956var TEN = new BN(10);
20957var THREE = new BN(3);
20958var SEVEN = new BN(7);
20959var ELEVEN = new BN(11);
20960var FOUR = new BN(4);
20961var TWELVE = new BN(12);
20962var primes = null;
20963
20964function _getPrimes() {
20965 if (primes !== null)
20966 return primes;
20967
20968 var limit = 0x100000;
20969 var res = [];
20970 res[0] = 2;
20971 for (var i = 1, k = 3; k < limit; k += 2) {
20972 var sqrt = Math.ceil(Math.sqrt(k));
20973 for (var j = 0; j < i && res[j] <= sqrt; j++)
20974 if (k % res[j] === 0)
20975 break;
20976
20977 if (i !== j && res[j] <= sqrt)
20978 continue;
20979
20980 res[i++] = k;
20981 }
20982 primes = res;
20983 return res;
20984}
20985
20986function simpleSieve(p) {
20987 var primes = _getPrimes();
20988
20989 for (var i = 0; i < primes.length; i++)
20990 if (p.modn(primes[i]) === 0) {
20991 if (p.cmpn(primes[i]) === 0) {
20992 return true;
20993 } else {
20994 return false;
20995 }
20996 }
20997
20998 return true;
20999}
21000
21001function fermatTest(p) {
21002 var red = BN.mont(p);
21003 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
21004}
21005
21006function findPrime(bits, gen) {
21007 if (bits < 16) {
21008 // this is what openssl does
21009 if (gen === 2 || gen === 5) {
21010 return new BN([0x8c, 0x7b]);
21011 } else {
21012 return new BN([0x8c, 0x27]);
21013 }
21014 }
21015 gen = new BN(gen);
21016
21017 var num, n2;
21018
21019 while (true) {
21020 num = new BN(randomBytes(Math.ceil(bits / 8)));
21021 while (num.bitLength() > bits) {
21022 num.ishrn(1);
21023 }
21024 if (num.isEven()) {
21025 num.iadd(ONE);
21026 }
21027 if (!num.testn(1)) {
21028 num.iadd(TWO);
21029 }
21030 if (!gen.cmp(TWO)) {
21031 while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
21032 num.iadd(FOUR);
21033 }
21034 } else if (!gen.cmp(FIVE)) {
21035 while (num.mod(TEN).cmp(THREE)) {
21036 num.iadd(FOUR);
21037 }
21038 }
21039 n2 = num.shrn(1);
21040 if (simpleSieve(n2) && simpleSieve(num) &&
21041 fermatTest(n2) && fermatTest(num) &&
21042 millerRabin.test(n2) && millerRabin.test(num)) {
21043 return num;
21044 }
21045 }
21046
21047}
21048
21049},{"bn.js":97,"miller-rabin":157,"randombytes":182}],96:[function(require,module,exports){
21050module.exports={
21051 "modp1": {
21052 "gen": "02",
21053 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
21054 },
21055 "modp2": {
21056 "gen": "02",
21057 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
21058 },
21059 "modp5": {
21060 "gen": "02",
21061 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
21062 },
21063 "modp14": {
21064 "gen": "02",
21065 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
21066 },
21067 "modp15": {
21068 "gen": "02",
21069 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
21070 },
21071 "modp16": {
21072 "gen": "02",
21073 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
21074 },
21075 "modp17": {
21076 "gen": "02",
21077 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
21078 },
21079 "modp18": {
21080 "gen": "02",
21081 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
21082 }
21083}
21084},{}],97:[function(require,module,exports){
21085arguments[4][21][0].apply(exports,arguments)
21086},{"buffer":33,"dup":21}],98:[function(require,module,exports){
21087var assert = require('assert')
21088var BigInteger = require('bigi')
21089
21090var Point = require('./point')
21091
21092function Curve(p, a, b, Gx, Gy, n, h) {
21093 this.p = p
21094 this.a = a
21095 this.b = b
21096 this.G = Point.fromAffine(this, Gx, Gy)
21097 this.n = n
21098 this.h = h
21099
21100 this.infinity = new Point(this, null, null, BigInteger.ZERO)
21101
21102 // result caching
21103 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
21104}
21105
21106Curve.prototype.pointFromX = function(isOdd, x) {
21107 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
21108 var beta = alpha.modPow(this.pOverFour, this.p)
21109
21110 var y = beta
21111 if (beta.isEven() ^ !isOdd) {
21112 y = this.p.subtract(y) // -y % p
21113 }
21114
21115 return Point.fromAffine(this, x, y)
21116}
21117
21118Curve.prototype.isInfinity = function(Q) {
21119 if (Q === this.infinity) return true
21120
21121 return Q.z.signum() === 0 && Q.y.signum() !== 0
21122}
21123
21124Curve.prototype.isOnCurve = function(Q) {
21125 if (this.isInfinity(Q)) return true
21126
21127 var x = Q.affineX
21128 var y = Q.affineY
21129 var a = this.a
21130 var b = this.b
21131 var p = this.p
21132
21133 // Check that xQ and yQ are integers in the interval [0, p - 1]
21134 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
21135 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
21136
21137 // and check that y^2 = x^3 + ax + b (mod p)
21138 var lhs = y.square().mod(p)
21139 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
21140 return lhs.equals(rhs)
21141}
21142
21143/**
21144 * Validate an elliptic curve point.
21145 *
21146 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
21147 */
21148Curve.prototype.validate = function(Q) {
21149 // Check Q != O
21150 assert(!this.isInfinity(Q), 'Point is at infinity')
21151 assert(this.isOnCurve(Q), 'Point is not on the curve')
21152
21153 // Check nQ = O (where Q is a scalar multiple of G)
21154 var nQ = Q.multiply(this.n)
21155 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
21156
21157 return true
21158}
21159
21160module.exports = Curve
21161
21162},{"./point":102,"assert":22,"bigi":29}],99:[function(require,module,exports){
21163module.exports={
21164 "secp128r1": {
21165 "p": "fffffffdffffffffffffffffffffffff",
21166 "a": "fffffffdfffffffffffffffffffffffc",
21167 "b": "e87579c11079f43dd824993c2cee5ed3",
21168 "n": "fffffffe0000000075a30d1b9038a115",
21169 "h": "01",
21170 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
21171 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
21172 },
21173 "secp160k1": {
21174 "p": "fffffffffffffffffffffffffffffffeffffac73",
21175 "a": "00",
21176 "b": "07",
21177 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
21178 "h": "01",
21179 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
21180 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
21181 },
21182 "secp160r1": {
21183 "p": "ffffffffffffffffffffffffffffffff7fffffff",
21184 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
21185 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
21186 "n": "0100000000000000000001f4c8f927aed3ca752257",
21187 "h": "01",
21188 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
21189 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
21190 },
21191 "secp192k1": {
21192 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
21193 "a": "00",
21194 "b": "03",
21195 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
21196 "h": "01",
21197 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
21198 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
21199 },
21200 "secp192r1": {
21201 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
21202 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
21203 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
21204 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
21205 "h": "01",
21206 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
21207 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
21208 },
21209 "secp256k1": {
21210 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
21211 "a": "00",
21212 "b": "07",
21213 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
21214 "h": "01",
21215 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
21216 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
21217 },
21218 "secp256r1": {
21219 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
21220 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
21221 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
21222 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
21223 "h": "01",
21224 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
21225 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
21226 }
21227}
21228
21229},{}],100:[function(require,module,exports){
21230var Point = require('./point')
21231var Curve = require('./curve')
21232
21233var getCurveByName = require('./names')
21234
21235module.exports = {
21236 Curve: Curve,
21237 Point: Point,
21238 getCurveByName: getCurveByName
21239}
21240
21241},{"./curve":98,"./names":101,"./point":102}],101:[function(require,module,exports){
21242var BigInteger = require('bigi')
21243
21244var curves = require('./curves')
21245var Curve = require('./curve')
21246
21247function getCurveByName(name) {
21248 var curve = curves[name]
21249 if (!curve) return null
21250
21251 var p = new BigInteger(curve.p, 16)
21252 var a = new BigInteger(curve.a, 16)
21253 var b = new BigInteger(curve.b, 16)
21254 var n = new BigInteger(curve.n, 16)
21255 var h = new BigInteger(curve.h, 16)
21256 var Gx = new BigInteger(curve.Gx, 16)
21257 var Gy = new BigInteger(curve.Gy, 16)
21258
21259 return new Curve(p, a, b, Gx, Gy, n, h)
21260}
21261
21262module.exports = getCurveByName
21263
21264},{"./curve":98,"./curves":99,"bigi":29}],102:[function(require,module,exports){
21265(function (Buffer){(function (){
21266var assert = require('assert')
21267var BigInteger = require('bigi')
21268
21269var THREE = BigInteger.valueOf(3)
21270
21271function Point(curve, x, y, z) {
21272 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
21273
21274 this.curve = curve
21275 this.x = x
21276 this.y = y
21277 this.z = z
21278 this._zInv = null
21279
21280 this.compressed = true
21281}
21282
21283Object.defineProperty(Point.prototype, 'zInv', {
21284 get: function() {
21285 if (this._zInv === null) {
21286 this._zInv = this.z.modInverse(this.curve.p)
21287 }
21288
21289 return this._zInv
21290 }
21291})
21292
21293Object.defineProperty(Point.prototype, 'affineX', {
21294 get: function() {
21295 return this.x.multiply(this.zInv).mod(this.curve.p)
21296 }
21297})
21298
21299Object.defineProperty(Point.prototype, 'affineY', {
21300 get: function() {
21301 return this.y.multiply(this.zInv).mod(this.curve.p)
21302 }
21303})
21304
21305Point.fromAffine = function(curve, x, y) {
21306 return new Point(curve, x, y, BigInteger.ONE)
21307}
21308
21309Point.prototype.equals = function(other) {
21310 if (other === this) return true
21311 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
21312 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
21313
21314 // u = Y2 * Z1 - Y1 * Z2
21315 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
21316
21317 if (u.signum() !== 0) return false
21318
21319 // v = X2 * Z1 - X1 * Z2
21320 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
21321
21322 return v.signum() === 0
21323}
21324
21325Point.prototype.negate = function() {
21326 var y = this.curve.p.subtract(this.y)
21327
21328 return new Point(this.curve, this.x, y, this.z)
21329}
21330
21331Point.prototype.add = function(b) {
21332 if (this.curve.isInfinity(this)) return b
21333 if (this.curve.isInfinity(b)) return this
21334
21335 var x1 = this.x
21336 var y1 = this.y
21337 var x2 = b.x
21338 var y2 = b.y
21339
21340 // u = Y2 * Z1 - Y1 * Z2
21341 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
21342 // v = X2 * Z1 - X1 * Z2
21343 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
21344
21345 if (v.signum() === 0) {
21346 if (u.signum() === 0) {
21347 return this.twice() // this == b, so double
21348 }
21349
21350 return this.curve.infinity // this = -b, so infinity
21351 }
21352
21353 var v2 = v.square()
21354 var v3 = v2.multiply(v)
21355 var x1v2 = x1.multiply(v2)
21356 var zu2 = u.square().multiply(this.z)
21357
21358 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
21359 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
21360 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
21361 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p)
21362 // z3 = v^3 * z1 * z2
21363 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
21364
21365 return new Point(this.curve, x3, y3, z3)
21366}
21367
21368Point.prototype.twice = function() {
21369 if (this.curve.isInfinity(this)) return this
21370 if (this.y.signum() === 0) return this.curve.infinity
21371
21372 var x1 = this.x
21373 var y1 = this.y
21374
21375 var y1z1 = y1.multiply(this.z)
21376 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
21377 var a = this.curve.a
21378
21379 // w = 3 * x1^2 + a * z1^2
21380 var w = x1.square().multiply(THREE)
21381
21382 if (a.signum() !== 0) {
21383 w = w.add(this.z.square().multiply(a))
21384 }
21385
21386 w = w.mod(this.curve.p)
21387 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
21388 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
21389 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
21390 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
21391 // z3 = 8 * (y1 * z1)^3
21392 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
21393
21394 return new Point(this.curve, x3, y3, z3)
21395}
21396
21397// Simple NAF (Non-Adjacent Form) multiplication algorithm
21398// TODO: modularize the multiplication algorithm
21399Point.prototype.multiply = function(k) {
21400 if (this.curve.isInfinity(this)) return this
21401 if (k.signum() === 0) return this.curve.infinity
21402
21403 var e = k
21404 var h = e.multiply(THREE)
21405
21406 var neg = this.negate()
21407 var R = this
21408
21409 for (var i = h.bitLength() - 2; i > 0; --i) {
21410 R = R.twice()
21411
21412 var hBit = h.testBit(i)
21413 var eBit = e.testBit(i)
21414
21415 if (hBit != eBit) {
21416 R = R.add(hBit ? this : neg)
21417 }
21418 }
21419
21420 return R
21421}
21422
21423// Compute this*j + x*k (simultaneous multiplication)
21424Point.prototype.multiplyTwo = function(j, x, k) {
21425 var i
21426
21427 if (j.bitLength() > k.bitLength())
21428 i = j.bitLength() - 1
21429 else
21430 i = k.bitLength() - 1
21431
21432 var R = this.curve.infinity
21433 var both = this.add(x)
21434
21435 while (i >= 0) {
21436 R = R.twice()
21437
21438 var jBit = j.testBit(i)
21439 var kBit = k.testBit(i)
21440
21441 if (jBit) {
21442 if (kBit) {
21443 R = R.add(both)
21444
21445 } else {
21446 R = R.add(this)
21447 }
21448
21449 } else {
21450 if (kBit) {
21451 R = R.add(x)
21452 }
21453 }
21454 --i
21455 }
21456
21457 return R
21458}
21459
21460Point.prototype.getEncoded = function(compressed) {
21461 if (compressed == undefined) compressed = this.compressed
21462 if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00'
21463
21464 var x = this.affineX
21465 var y = this.affineY
21466
21467 var buffer
21468
21469 // Determine size of q in bytes
21470 var byteLength = Math.floor((this.curve.p.bitLength() + 7) / 8)
21471
21472 // 0x02/0x03 | X
21473 if (compressed) {
21474 buffer = new Buffer(1 + byteLength)
21475 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
21476
21477 // 0x04 | X | Y
21478 } else {
21479 buffer = new Buffer(1 + byteLength + byteLength)
21480 buffer.writeUInt8(0x04, 0)
21481
21482 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
21483 }
21484
21485 x.toBuffer(byteLength).copy(buffer, 1)
21486
21487 return buffer
21488}
21489
21490Point.decodeFrom = function(curve, buffer) {
21491 var type = buffer.readUInt8(0)
21492 var compressed = (type !== 4)
21493
21494 var x = BigInteger.fromBuffer(buffer.slice(1, 33))
21495 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
21496
21497 var Q
21498 if (compressed) {
21499 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
21500 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
21501
21502 var isOdd = (type === 0x03)
21503 Q = curve.pointFromX(isOdd, x)
21504
21505 } else {
21506 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
21507
21508 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
21509 Q = Point.fromAffine(curve, x, y)
21510 }
21511
21512 Q.compressed = compressed
21513 return Q
21514}
21515
21516Point.prototype.toString = function () {
21517 if (this.curve.isInfinity(this)) return '(INFINITY)'
21518
21519 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
21520}
21521
21522module.exports = Point
21523
21524}).call(this)}).call(this,require("buffer").Buffer)
21525},{"assert":22,"bigi":29,"buffer":77}],103:[function(require,module,exports){
21526'use strict';
21527
21528var elliptic = exports;
21529
21530elliptic.version = require('../package.json').version;
21531elliptic.utils = require('./elliptic/utils');
21532elliptic.rand = require('brorand');
21533elliptic.curve = require('./elliptic/curve');
21534elliptic.curves = require('./elliptic/curves');
21535
21536// Protocols
21537elliptic.ec = require('./elliptic/ec');
21538elliptic.eddsa = require('./elliptic/eddsa');
21539
21540},{"../package.json":119,"./elliptic/curve":106,"./elliptic/curves":109,"./elliptic/ec":110,"./elliptic/eddsa":113,"./elliptic/utils":117,"brorand":32}],104:[function(require,module,exports){
21541'use strict';
21542
21543var BN = require('bn.js');
21544var utils = require('../utils');
21545var getNAF = utils.getNAF;
21546var getJSF = utils.getJSF;
21547var assert = utils.assert;
21548
21549function BaseCurve(type, conf) {
21550 this.type = type;
21551 this.p = new BN(conf.p, 16);
21552
21553 // Use Montgomery, when there is no fast reduction for the prime
21554 this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
21555
21556 // Useful for many curves
21557 this.zero = new BN(0).toRed(this.red);
21558 this.one = new BN(1).toRed(this.red);
21559 this.two = new BN(2).toRed(this.red);
21560
21561 // Curve configuration, optional
21562 this.n = conf.n && new BN(conf.n, 16);
21563 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
21564
21565 // Temporary arrays
21566 this._wnafT1 = new Array(4);
21567 this._wnafT2 = new Array(4);
21568 this._wnafT3 = new Array(4);
21569 this._wnafT4 = new Array(4);
21570
21571 this._bitLength = this.n ? this.n.bitLength() : 0;
21572
21573 // Generalized Greg Maxwell's trick
21574 var adjustCount = this.n && this.p.div(this.n);
21575 if (!adjustCount || adjustCount.cmpn(100) > 0) {
21576 this.redN = null;
21577 } else {
21578 this._maxwellTrick = true;
21579 this.redN = this.n.toRed(this.red);
21580 }
21581}
21582module.exports = BaseCurve;
21583
21584BaseCurve.prototype.point = function point() {
21585 throw new Error('Not implemented');
21586};
21587
21588BaseCurve.prototype.validate = function validate() {
21589 throw new Error('Not implemented');
21590};
21591
21592BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
21593 assert(p.precomputed);
21594 var doubles = p._getDoubles();
21595
21596 var naf = getNAF(k, 1, this._bitLength);
21597 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
21598 I /= 3;
21599
21600 // Translate into more windowed form
21601 var repr = [];
21602 var j;
21603 var nafW;
21604 for (j = 0; j < naf.length; j += doubles.step) {
21605 nafW = 0;
21606 for (var l = j + doubles.step - 1; l >= j; l--)
21607 nafW = (nafW << 1) + naf[l];
21608 repr.push(nafW);
21609 }
21610
21611 var a = this.jpoint(null, null, null);
21612 var b = this.jpoint(null, null, null);
21613 for (var i = I; i > 0; i--) {
21614 for (j = 0; j < repr.length; j++) {
21615 nafW = repr[j];
21616 if (nafW === i)
21617 b = b.mixedAdd(doubles.points[j]);
21618 else if (nafW === -i)
21619 b = b.mixedAdd(doubles.points[j].neg());
21620 }
21621 a = a.add(b);
21622 }
21623 return a.toP();
21624};
21625
21626BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
21627 var w = 4;
21628
21629 // Precompute window
21630 var nafPoints = p._getNAFPoints(w);
21631 w = nafPoints.wnd;
21632 var wnd = nafPoints.points;
21633
21634 // Get NAF form
21635 var naf = getNAF(k, w, this._bitLength);
21636
21637 // Add `this`*(N+1) for every w-NAF index
21638 var acc = this.jpoint(null, null, null);
21639 for (var i = naf.length - 1; i >= 0; i--) {
21640 // Count zeroes
21641 for (var l = 0; i >= 0 && naf[i] === 0; i--)
21642 l++;
21643 if (i >= 0)
21644 l++;
21645 acc = acc.dblp(l);
21646
21647 if (i < 0)
21648 break;
21649 var z = naf[i];
21650 assert(z !== 0);
21651 if (p.type === 'affine') {
21652 // J +- P
21653 if (z > 0)
21654 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
21655 else
21656 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
21657 } else {
21658 // J +- J
21659 if (z > 0)
21660 acc = acc.add(wnd[(z - 1) >> 1]);
21661 else
21662 acc = acc.add(wnd[(-z - 1) >> 1].neg());
21663 }
21664 }
21665 return p.type === 'affine' ? acc.toP() : acc;
21666};
21667
21668BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
21669 points,
21670 coeffs,
21671 len,
21672 jacobianResult) {
21673 var wndWidth = this._wnafT1;
21674 var wnd = this._wnafT2;
21675 var naf = this._wnafT3;
21676
21677 // Fill all arrays
21678 var max = 0;
21679 var i;
21680 var j;
21681 var p;
21682 for (i = 0; i < len; i++) {
21683 p = points[i];
21684 var nafPoints = p._getNAFPoints(defW);
21685 wndWidth[i] = nafPoints.wnd;
21686 wnd[i] = nafPoints.points;
21687 }
21688
21689 // Comb small window NAFs
21690 for (i = len - 1; i >= 1; i -= 2) {
21691 var a = i - 1;
21692 var b = i;
21693 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
21694 naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
21695 naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
21696 max = Math.max(naf[a].length, max);
21697 max = Math.max(naf[b].length, max);
21698 continue;
21699 }
21700
21701 var comb = [
21702 points[a], /* 1 */
21703 null, /* 3 */
21704 null, /* 5 */
21705 points[b], /* 7 */
21706 ];
21707
21708 // Try to avoid Projective points, if possible
21709 if (points[a].y.cmp(points[b].y) === 0) {
21710 comb[1] = points[a].add(points[b]);
21711 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
21712 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
21713 comb[1] = points[a].toJ().mixedAdd(points[b]);
21714 comb[2] = points[a].add(points[b].neg());
21715 } else {
21716 comb[1] = points[a].toJ().mixedAdd(points[b]);
21717 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
21718 }
21719
21720 var index = [
21721 -3, /* -1 -1 */
21722 -1, /* -1 0 */
21723 -5, /* -1 1 */
21724 -7, /* 0 -1 */
21725 0, /* 0 0 */
21726 7, /* 0 1 */
21727 5, /* 1 -1 */
21728 1, /* 1 0 */
21729 3, /* 1 1 */
21730 ];
21731
21732 var jsf = getJSF(coeffs[a], coeffs[b]);
21733 max = Math.max(jsf[0].length, max);
21734 naf[a] = new Array(max);
21735 naf[b] = new Array(max);
21736 for (j = 0; j < max; j++) {
21737 var ja = jsf[0][j] | 0;
21738 var jb = jsf[1][j] | 0;
21739
21740 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
21741 naf[b][j] = 0;
21742 wnd[a] = comb;
21743 }
21744 }
21745
21746 var acc = this.jpoint(null, null, null);
21747 var tmp = this._wnafT4;
21748 for (i = max; i >= 0; i--) {
21749 var k = 0;
21750
21751 while (i >= 0) {
21752 var zero = true;
21753 for (j = 0; j < len; j++) {
21754 tmp[j] = naf[j][i] | 0;
21755 if (tmp[j] !== 0)
21756 zero = false;
21757 }
21758 if (!zero)
21759 break;
21760 k++;
21761 i--;
21762 }
21763 if (i >= 0)
21764 k++;
21765 acc = acc.dblp(k);
21766 if (i < 0)
21767 break;
21768
21769 for (j = 0; j < len; j++) {
21770 var z = tmp[j];
21771 p;
21772 if (z === 0)
21773 continue;
21774 else if (z > 0)
21775 p = wnd[j][(z - 1) >> 1];
21776 else if (z < 0)
21777 p = wnd[j][(-z - 1) >> 1].neg();
21778
21779 if (p.type === 'affine')
21780 acc = acc.mixedAdd(p);
21781 else
21782 acc = acc.add(p);
21783 }
21784 }
21785 // Zeroify references
21786 for (i = 0; i < len; i++)
21787 wnd[i] = null;
21788
21789 if (jacobianResult)
21790 return acc;
21791 else
21792 return acc.toP();
21793};
21794
21795function BasePoint(curve, type) {
21796 this.curve = curve;
21797 this.type = type;
21798 this.precomputed = null;
21799}
21800BaseCurve.BasePoint = BasePoint;
21801
21802BasePoint.prototype.eq = function eq(/*other*/) {
21803 throw new Error('Not implemented');
21804};
21805
21806BasePoint.prototype.validate = function validate() {
21807 return this.curve.validate(this);
21808};
21809
21810BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
21811 bytes = utils.toArray(bytes, enc);
21812
21813 var len = this.p.byteLength();
21814
21815 // uncompressed, hybrid-odd, hybrid-even
21816 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
21817 bytes.length - 1 === 2 * len) {
21818 if (bytes[0] === 0x06)
21819 assert(bytes[bytes.length - 1] % 2 === 0);
21820 else if (bytes[0] === 0x07)
21821 assert(bytes[bytes.length - 1] % 2 === 1);
21822
21823 var res = this.point(bytes.slice(1, 1 + len),
21824 bytes.slice(1 + len, 1 + 2 * len));
21825
21826 return res;
21827 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
21828 bytes.length - 1 === len) {
21829 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
21830 }
21831 throw new Error('Unknown point format');
21832};
21833
21834BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
21835 return this.encode(enc, true);
21836};
21837
21838BasePoint.prototype._encode = function _encode(compact) {
21839 var len = this.curve.p.byteLength();
21840 var x = this.getX().toArray('be', len);
21841
21842 if (compact)
21843 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
21844
21845 return [ 0x04 ].concat(x, this.getY().toArray('be', len));
21846};
21847
21848BasePoint.prototype.encode = function encode(enc, compact) {
21849 return utils.encode(this._encode(compact), enc);
21850};
21851
21852BasePoint.prototype.precompute = function precompute(power) {
21853 if (this.precomputed)
21854 return this;
21855
21856 var precomputed = {
21857 doubles: null,
21858 naf: null,
21859 beta: null,
21860 };
21861 precomputed.naf = this._getNAFPoints(8);
21862 precomputed.doubles = this._getDoubles(4, power);
21863 precomputed.beta = this._getBeta();
21864 this.precomputed = precomputed;
21865
21866 return this;
21867};
21868
21869BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
21870 if (!this.precomputed)
21871 return false;
21872
21873 var doubles = this.precomputed.doubles;
21874 if (!doubles)
21875 return false;
21876
21877 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
21878};
21879
21880BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
21881 if (this.precomputed && this.precomputed.doubles)
21882 return this.precomputed.doubles;
21883
21884 var doubles = [ this ];
21885 var acc = this;
21886 for (var i = 0; i < power; i += step) {
21887 for (var j = 0; j < step; j++)
21888 acc = acc.dbl();
21889 doubles.push(acc);
21890 }
21891 return {
21892 step: step,
21893 points: doubles,
21894 };
21895};
21896
21897BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
21898 if (this.precomputed && this.precomputed.naf)
21899 return this.precomputed.naf;
21900
21901 var res = [ this ];
21902 var max = (1 << wnd) - 1;
21903 var dbl = max === 1 ? null : this.dbl();
21904 for (var i = 1; i < max; i++)
21905 res[i] = res[i - 1].add(dbl);
21906 return {
21907 wnd: wnd,
21908 points: res,
21909 };
21910};
21911
21912BasePoint.prototype._getBeta = function _getBeta() {
21913 return null;
21914};
21915
21916BasePoint.prototype.dblp = function dblp(k) {
21917 var r = this;
21918 for (var i = 0; i < k; i++)
21919 r = r.dbl();
21920 return r;
21921};
21922
21923},{"../utils":117,"bn.js":118}],105:[function(require,module,exports){
21924'use strict';
21925
21926var utils = require('../utils');
21927var BN = require('bn.js');
21928var inherits = require('inherits');
21929var Base = require('./base');
21930
21931var assert = utils.assert;
21932
21933function EdwardsCurve(conf) {
21934 // NOTE: Important as we are creating point in Base.call()
21935 this.twisted = (conf.a | 0) !== 1;
21936 this.mOneA = this.twisted && (conf.a | 0) === -1;
21937 this.extended = this.mOneA;
21938
21939 Base.call(this, 'edwards', conf);
21940
21941 this.a = new BN(conf.a, 16).umod(this.red.m);
21942 this.a = this.a.toRed(this.red);
21943 this.c = new BN(conf.c, 16).toRed(this.red);
21944 this.c2 = this.c.redSqr();
21945 this.d = new BN(conf.d, 16).toRed(this.red);
21946 this.dd = this.d.redAdd(this.d);
21947
21948 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
21949 this.oneC = (conf.c | 0) === 1;
21950}
21951inherits(EdwardsCurve, Base);
21952module.exports = EdwardsCurve;
21953
21954EdwardsCurve.prototype._mulA = function _mulA(num) {
21955 if (this.mOneA)
21956 return num.redNeg();
21957 else
21958 return this.a.redMul(num);
21959};
21960
21961EdwardsCurve.prototype._mulC = function _mulC(num) {
21962 if (this.oneC)
21963 return num;
21964 else
21965 return this.c.redMul(num);
21966};
21967
21968// Just for compatibility with Short curve
21969EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
21970 return this.point(x, y, z, t);
21971};
21972
21973EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
21974 x = new BN(x, 16);
21975 if (!x.red)
21976 x = x.toRed(this.red);
21977
21978 var x2 = x.redSqr();
21979 var rhs = this.c2.redSub(this.a.redMul(x2));
21980 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
21981
21982 var y2 = rhs.redMul(lhs.redInvm());
21983 var y = y2.redSqrt();
21984 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
21985 throw new Error('invalid point');
21986
21987 var isOdd = y.fromRed().isOdd();
21988 if (odd && !isOdd || !odd && isOdd)
21989 y = y.redNeg();
21990
21991 return this.point(x, y);
21992};
21993
21994EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
21995 y = new BN(y, 16);
21996 if (!y.red)
21997 y = y.toRed(this.red);
21998
21999 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
22000 var y2 = y.redSqr();
22001 var lhs = y2.redSub(this.c2);
22002 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
22003 var x2 = lhs.redMul(rhs.redInvm());
22004
22005 if (x2.cmp(this.zero) === 0) {
22006 if (odd)
22007 throw new Error('invalid point');
22008 else
22009 return this.point(this.zero, y);
22010 }
22011
22012 var x = x2.redSqrt();
22013 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
22014 throw new Error('invalid point');
22015
22016 if (x.fromRed().isOdd() !== odd)
22017 x = x.redNeg();
22018
22019 return this.point(x, y);
22020};
22021
22022EdwardsCurve.prototype.validate = function validate(point) {
22023 if (point.isInfinity())
22024 return true;
22025
22026 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
22027 point.normalize();
22028
22029 var x2 = point.x.redSqr();
22030 var y2 = point.y.redSqr();
22031 var lhs = x2.redMul(this.a).redAdd(y2);
22032 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
22033
22034 return lhs.cmp(rhs) === 0;
22035};
22036
22037function Point(curve, x, y, z, t) {
22038 Base.BasePoint.call(this, curve, 'projective');
22039 if (x === null && y === null && z === null) {
22040 this.x = this.curve.zero;
22041 this.y = this.curve.one;
22042 this.z = this.curve.one;
22043 this.t = this.curve.zero;
22044 this.zOne = true;
22045 } else {
22046 this.x = new BN(x, 16);
22047 this.y = new BN(y, 16);
22048 this.z = z ? new BN(z, 16) : this.curve.one;
22049 this.t = t && new BN(t, 16);
22050 if (!this.x.red)
22051 this.x = this.x.toRed(this.curve.red);
22052 if (!this.y.red)
22053 this.y = this.y.toRed(this.curve.red);
22054 if (!this.z.red)
22055 this.z = this.z.toRed(this.curve.red);
22056 if (this.t && !this.t.red)
22057 this.t = this.t.toRed(this.curve.red);
22058 this.zOne = this.z === this.curve.one;
22059
22060 // Use extended coordinates
22061 if (this.curve.extended && !this.t) {
22062 this.t = this.x.redMul(this.y);
22063 if (!this.zOne)
22064 this.t = this.t.redMul(this.z.redInvm());
22065 }
22066 }
22067}
22068inherits(Point, Base.BasePoint);
22069
22070EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
22071 return Point.fromJSON(this, obj);
22072};
22073
22074EdwardsCurve.prototype.point = function point(x, y, z, t) {
22075 return new Point(this, x, y, z, t);
22076};
22077
22078Point.fromJSON = function fromJSON(curve, obj) {
22079 return new Point(curve, obj[0], obj[1], obj[2]);
22080};
22081
22082Point.prototype.inspect = function inspect() {
22083 if (this.isInfinity())
22084 return '<EC Point Infinity>';
22085 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
22086 ' y: ' + this.y.fromRed().toString(16, 2) +
22087 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
22088};
22089
22090Point.prototype.isInfinity = function isInfinity() {
22091 // XXX This code assumes that zero is always zero in red
22092 return this.x.cmpn(0) === 0 &&
22093 (this.y.cmp(this.z) === 0 ||
22094 (this.zOne && this.y.cmp(this.curve.c) === 0));
22095};
22096
22097Point.prototype._extDbl = function _extDbl() {
22098 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
22099 // #doubling-dbl-2008-hwcd
22100 // 4M + 4S
22101
22102 // A = X1^2
22103 var a = this.x.redSqr();
22104 // B = Y1^2
22105 var b = this.y.redSqr();
22106 // C = 2 * Z1^2
22107 var c = this.z.redSqr();
22108 c = c.redIAdd(c);
22109 // D = a * A
22110 var d = this.curve._mulA(a);
22111 // E = (X1 + Y1)^2 - A - B
22112 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
22113 // G = D + B
22114 var g = d.redAdd(b);
22115 // F = G - C
22116 var f = g.redSub(c);
22117 // H = D - B
22118 var h = d.redSub(b);
22119 // X3 = E * F
22120 var nx = e.redMul(f);
22121 // Y3 = G * H
22122 var ny = g.redMul(h);
22123 // T3 = E * H
22124 var nt = e.redMul(h);
22125 // Z3 = F * G
22126 var nz = f.redMul(g);
22127 return this.curve.point(nx, ny, nz, nt);
22128};
22129
22130Point.prototype._projDbl = function _projDbl() {
22131 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
22132 // #doubling-dbl-2008-bbjlp
22133 // #doubling-dbl-2007-bl
22134 // and others
22135 // Generally 3M + 4S or 2M + 4S
22136
22137 // B = (X1 + Y1)^2
22138 var b = this.x.redAdd(this.y).redSqr();
22139 // C = X1^2
22140 var c = this.x.redSqr();
22141 // D = Y1^2
22142 var d = this.y.redSqr();
22143
22144 var nx;
22145 var ny;
22146 var nz;
22147 var e;
22148 var h;
22149 var j;
22150 if (this.curve.twisted) {
22151 // E = a * C
22152 e = this.curve._mulA(c);
22153 // F = E + D
22154 var f = e.redAdd(d);
22155 if (this.zOne) {
22156 // X3 = (B - C - D) * (F - 2)
22157 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
22158 // Y3 = F * (E - D)
22159 ny = f.redMul(e.redSub(d));
22160 // Z3 = F^2 - 2 * F
22161 nz = f.redSqr().redSub(f).redSub(f);
22162 } else {
22163 // H = Z1^2
22164 h = this.z.redSqr();
22165 // J = F - 2 * H
22166 j = f.redSub(h).redISub(h);
22167 // X3 = (B-C-D)*J
22168 nx = b.redSub(c).redISub(d).redMul(j);
22169 // Y3 = F * (E - D)
22170 ny = f.redMul(e.redSub(d));
22171 // Z3 = F * J
22172 nz = f.redMul(j);
22173 }
22174 } else {
22175 // E = C + D
22176 e = c.redAdd(d);
22177 // H = (c * Z1)^2
22178 h = this.curve._mulC(this.z).redSqr();
22179 // J = E - 2 * H
22180 j = e.redSub(h).redSub(h);
22181 // X3 = c * (B - E) * J
22182 nx = this.curve._mulC(b.redISub(e)).redMul(j);
22183 // Y3 = c * E * (C - D)
22184 ny = this.curve._mulC(e).redMul(c.redISub(d));
22185 // Z3 = E * J
22186 nz = e.redMul(j);
22187 }
22188 return this.curve.point(nx, ny, nz);
22189};
22190
22191Point.prototype.dbl = function dbl() {
22192 if (this.isInfinity())
22193 return this;
22194
22195 // Double in extended coordinates
22196 if (this.curve.extended)
22197 return this._extDbl();
22198 else
22199 return this._projDbl();
22200};
22201
22202Point.prototype._extAdd = function _extAdd(p) {
22203 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
22204 // #addition-add-2008-hwcd-3
22205 // 8M
22206
22207 // A = (Y1 - X1) * (Y2 - X2)
22208 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
22209 // B = (Y1 + X1) * (Y2 + X2)
22210 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
22211 // C = T1 * k * T2
22212 var c = this.t.redMul(this.curve.dd).redMul(p.t);
22213 // D = Z1 * 2 * Z2
22214 var d = this.z.redMul(p.z.redAdd(p.z));
22215 // E = B - A
22216 var e = b.redSub(a);
22217 // F = D - C
22218 var f = d.redSub(c);
22219 // G = D + C
22220 var g = d.redAdd(c);
22221 // H = B + A
22222 var h = b.redAdd(a);
22223 // X3 = E * F
22224 var nx = e.redMul(f);
22225 // Y3 = G * H
22226 var ny = g.redMul(h);
22227 // T3 = E * H
22228 var nt = e.redMul(h);
22229 // Z3 = F * G
22230 var nz = f.redMul(g);
22231 return this.curve.point(nx, ny, nz, nt);
22232};
22233
22234Point.prototype._projAdd = function _projAdd(p) {
22235 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
22236 // #addition-add-2008-bbjlp
22237 // #addition-add-2007-bl
22238 // 10M + 1S
22239
22240 // A = Z1 * Z2
22241 var a = this.z.redMul(p.z);
22242 // B = A^2
22243 var b = a.redSqr();
22244 // C = X1 * X2
22245 var c = this.x.redMul(p.x);
22246 // D = Y1 * Y2
22247 var d = this.y.redMul(p.y);
22248 // E = d * C * D
22249 var e = this.curve.d.redMul(c).redMul(d);
22250 // F = B - E
22251 var f = b.redSub(e);
22252 // G = B + E
22253 var g = b.redAdd(e);
22254 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
22255 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
22256 var nx = a.redMul(f).redMul(tmp);
22257 var ny;
22258 var nz;
22259 if (this.curve.twisted) {
22260 // Y3 = A * G * (D - a * C)
22261 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
22262 // Z3 = F * G
22263 nz = f.redMul(g);
22264 } else {
22265 // Y3 = A * G * (D - C)
22266 ny = a.redMul(g).redMul(d.redSub(c));
22267 // Z3 = c * F * G
22268 nz = this.curve._mulC(f).redMul(g);
22269 }
22270 return this.curve.point(nx, ny, nz);
22271};
22272
22273Point.prototype.add = function add(p) {
22274 if (this.isInfinity())
22275 return p;
22276 if (p.isInfinity())
22277 return this;
22278
22279 if (this.curve.extended)
22280 return this._extAdd(p);
22281 else
22282 return this._projAdd(p);
22283};
22284
22285Point.prototype.mul = function mul(k) {
22286 if (this._hasDoubles(k))
22287 return this.curve._fixedNafMul(this, k);
22288 else
22289 return this.curve._wnafMul(this, k);
22290};
22291
22292Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
22293 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
22294};
22295
22296Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
22297 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
22298};
22299
22300Point.prototype.normalize = function normalize() {
22301 if (this.zOne)
22302 return this;
22303
22304 // Normalize coordinates
22305 var zi = this.z.redInvm();
22306 this.x = this.x.redMul(zi);
22307 this.y = this.y.redMul(zi);
22308 if (this.t)
22309 this.t = this.t.redMul(zi);
22310 this.z = this.curve.one;
22311 this.zOne = true;
22312 return this;
22313};
22314
22315Point.prototype.neg = function neg() {
22316 return this.curve.point(this.x.redNeg(),
22317 this.y,
22318 this.z,
22319 this.t && this.t.redNeg());
22320};
22321
22322Point.prototype.getX = function getX() {
22323 this.normalize();
22324 return this.x.fromRed();
22325};
22326
22327Point.prototype.getY = function getY() {
22328 this.normalize();
22329 return this.y.fromRed();
22330};
22331
22332Point.prototype.eq = function eq(other) {
22333 return this === other ||
22334 this.getX().cmp(other.getX()) === 0 &&
22335 this.getY().cmp(other.getY()) === 0;
22336};
22337
22338Point.prototype.eqXToP = function eqXToP(x) {
22339 var rx = x.toRed(this.curve.red).redMul(this.z);
22340 if (this.x.cmp(rx) === 0)
22341 return true;
22342
22343 var xc = x.clone();
22344 var t = this.curve.redN.redMul(this.z);
22345 for (;;) {
22346 xc.iadd(this.curve.n);
22347 if (xc.cmp(this.curve.p) >= 0)
22348 return false;
22349
22350 rx.redIAdd(t);
22351 if (this.x.cmp(rx) === 0)
22352 return true;
22353 }
22354};
22355
22356// Compatibility with BaseCurve
22357Point.prototype.toP = Point.prototype.normalize;
22358Point.prototype.mixedAdd = Point.prototype.add;
22359
22360},{"../utils":117,"./base":104,"bn.js":118,"inherits":152}],106:[function(require,module,exports){
22361'use strict';
22362
22363var curve = exports;
22364
22365curve.base = require('./base');
22366curve.short = require('./short');
22367curve.mont = require('./mont');
22368curve.edwards = require('./edwards');
22369
22370},{"./base":104,"./edwards":105,"./mont":107,"./short":108}],107:[function(require,module,exports){
22371'use strict';
22372
22373var BN = require('bn.js');
22374var inherits = require('inherits');
22375var Base = require('./base');
22376
22377var utils = require('../utils');
22378
22379function MontCurve(conf) {
22380 Base.call(this, 'mont', conf);
22381
22382 this.a = new BN(conf.a, 16).toRed(this.red);
22383 this.b = new BN(conf.b, 16).toRed(this.red);
22384 this.i4 = new BN(4).toRed(this.red).redInvm();
22385 this.two = new BN(2).toRed(this.red);
22386 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
22387}
22388inherits(MontCurve, Base);
22389module.exports = MontCurve;
22390
22391MontCurve.prototype.validate = function validate(point) {
22392 var x = point.normalize().x;
22393 var x2 = x.redSqr();
22394 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
22395 var y = rhs.redSqrt();
22396
22397 return y.redSqr().cmp(rhs) === 0;
22398};
22399
22400function Point(curve, x, z) {
22401 Base.BasePoint.call(this, curve, 'projective');
22402 if (x === null && z === null) {
22403 this.x = this.curve.one;
22404 this.z = this.curve.zero;
22405 } else {
22406 this.x = new BN(x, 16);
22407 this.z = new BN(z, 16);
22408 if (!this.x.red)
22409 this.x = this.x.toRed(this.curve.red);
22410 if (!this.z.red)
22411 this.z = this.z.toRed(this.curve.red);
22412 }
22413}
22414inherits(Point, Base.BasePoint);
22415
22416MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
22417 return this.point(utils.toArray(bytes, enc), 1);
22418};
22419
22420MontCurve.prototype.point = function point(x, z) {
22421 return new Point(this, x, z);
22422};
22423
22424MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
22425 return Point.fromJSON(this, obj);
22426};
22427
22428Point.prototype.precompute = function precompute() {
22429 // No-op
22430};
22431
22432Point.prototype._encode = function _encode() {
22433 return this.getX().toArray('be', this.curve.p.byteLength());
22434};
22435
22436Point.fromJSON = function fromJSON(curve, obj) {
22437 return new Point(curve, obj[0], obj[1] || curve.one);
22438};
22439
22440Point.prototype.inspect = function inspect() {
22441 if (this.isInfinity())
22442 return '<EC Point Infinity>';
22443 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
22444 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
22445};
22446
22447Point.prototype.isInfinity = function isInfinity() {
22448 // XXX This code assumes that zero is always zero in red
22449 return this.z.cmpn(0) === 0;
22450};
22451
22452Point.prototype.dbl = function dbl() {
22453 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
22454 // 2M + 2S + 4A
22455
22456 // A = X1 + Z1
22457 var a = this.x.redAdd(this.z);
22458 // AA = A^2
22459 var aa = a.redSqr();
22460 // B = X1 - Z1
22461 var b = this.x.redSub(this.z);
22462 // BB = B^2
22463 var bb = b.redSqr();
22464 // C = AA - BB
22465 var c = aa.redSub(bb);
22466 // X3 = AA * BB
22467 var nx = aa.redMul(bb);
22468 // Z3 = C * (BB + A24 * C)
22469 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
22470 return this.curve.point(nx, nz);
22471};
22472
22473Point.prototype.add = function add() {
22474 throw new Error('Not supported on Montgomery curve');
22475};
22476
22477Point.prototype.diffAdd = function diffAdd(p, diff) {
22478 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
22479 // 4M + 2S + 6A
22480
22481 // A = X2 + Z2
22482 var a = this.x.redAdd(this.z);
22483 // B = X2 - Z2
22484 var b = this.x.redSub(this.z);
22485 // C = X3 + Z3
22486 var c = p.x.redAdd(p.z);
22487 // D = X3 - Z3
22488 var d = p.x.redSub(p.z);
22489 // DA = D * A
22490 var da = d.redMul(a);
22491 // CB = C * B
22492 var cb = c.redMul(b);
22493 // X5 = Z1 * (DA + CB)^2
22494 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
22495 // Z5 = X1 * (DA - CB)^2
22496 var nz = diff.x.redMul(da.redISub(cb).redSqr());
22497 return this.curve.point(nx, nz);
22498};
22499
22500Point.prototype.mul = function mul(k) {
22501 var t = k.clone();
22502 var a = this; // (N / 2) * Q + Q
22503 var b = this.curve.point(null, null); // (N / 2) * Q
22504 var c = this; // Q
22505
22506 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
22507 bits.push(t.andln(1));
22508
22509 for (var i = bits.length - 1; i >= 0; i--) {
22510 if (bits[i] === 0) {
22511 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
22512 a = a.diffAdd(b, c);
22513 // N * Q = 2 * ((N / 2) * Q + Q))
22514 b = b.dbl();
22515 } else {
22516 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
22517 b = a.diffAdd(b, c);
22518 // N * Q + Q = 2 * ((N / 2) * Q + Q)
22519 a = a.dbl();
22520 }
22521 }
22522 return b;
22523};
22524
22525Point.prototype.mulAdd = function mulAdd() {
22526 throw new Error('Not supported on Montgomery curve');
22527};
22528
22529Point.prototype.jumlAdd = function jumlAdd() {
22530 throw new Error('Not supported on Montgomery curve');
22531};
22532
22533Point.prototype.eq = function eq(other) {
22534 return this.getX().cmp(other.getX()) === 0;
22535};
22536
22537Point.prototype.normalize = function normalize() {
22538 this.x = this.x.redMul(this.z.redInvm());
22539 this.z = this.curve.one;
22540 return this;
22541};
22542
22543Point.prototype.getX = function getX() {
22544 // Normalize coordinates
22545 this.normalize();
22546
22547 return this.x.fromRed();
22548};
22549
22550},{"../utils":117,"./base":104,"bn.js":118,"inherits":152}],108:[function(require,module,exports){
22551'use strict';
22552
22553var utils = require('../utils');
22554var BN = require('bn.js');
22555var inherits = require('inherits');
22556var Base = require('./base');
22557
22558var assert = utils.assert;
22559
22560function ShortCurve(conf) {
22561 Base.call(this, 'short', conf);
22562
22563 this.a = new BN(conf.a, 16).toRed(this.red);
22564 this.b = new BN(conf.b, 16).toRed(this.red);
22565 this.tinv = this.two.redInvm();
22566
22567 this.zeroA = this.a.fromRed().cmpn(0) === 0;
22568 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
22569
22570 // If the curve is endomorphic, precalculate beta and lambda
22571 this.endo = this._getEndomorphism(conf);
22572 this._endoWnafT1 = new Array(4);
22573 this._endoWnafT2 = new Array(4);
22574}
22575inherits(ShortCurve, Base);
22576module.exports = ShortCurve;
22577
22578ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
22579 // No efficient endomorphism
22580 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
22581 return;
22582
22583 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
22584 var beta;
22585 var lambda;
22586 if (conf.beta) {
22587 beta = new BN(conf.beta, 16).toRed(this.red);
22588 } else {
22589 var betas = this._getEndoRoots(this.p);
22590 // Choose the smallest beta
22591 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
22592 beta = beta.toRed(this.red);
22593 }
22594 if (conf.lambda) {
22595 lambda = new BN(conf.lambda, 16);
22596 } else {
22597 // Choose the lambda that is matching selected beta
22598 var lambdas = this._getEndoRoots(this.n);
22599 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
22600 lambda = lambdas[0];
22601 } else {
22602 lambda = lambdas[1];
22603 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
22604 }
22605 }
22606
22607 // Get basis vectors, used for balanced length-two representation
22608 var basis;
22609 if (conf.basis) {
22610 basis = conf.basis.map(function(vec) {
22611 return {
22612 a: new BN(vec.a, 16),
22613 b: new BN(vec.b, 16),
22614 };
22615 });
22616 } else {
22617 basis = this._getEndoBasis(lambda);
22618 }
22619
22620 return {
22621 beta: beta,
22622 lambda: lambda,
22623 basis: basis,
22624 };
22625};
22626
22627ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
22628 // Find roots of for x^2 + x + 1 in F
22629 // Root = (-1 +- Sqrt(-3)) / 2
22630 //
22631 var red = num === this.p ? this.red : BN.mont(num);
22632 var tinv = new BN(2).toRed(red).redInvm();
22633 var ntinv = tinv.redNeg();
22634
22635 var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
22636
22637 var l1 = ntinv.redAdd(s).fromRed();
22638 var l2 = ntinv.redSub(s).fromRed();
22639 return [ l1, l2 ];
22640};
22641
22642ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
22643 // aprxSqrt >= sqrt(this.n)
22644 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
22645
22646 // 3.74
22647 // Run EGCD, until r(L + 1) < aprxSqrt
22648 var u = lambda;
22649 var v = this.n.clone();
22650 var x1 = new BN(1);
22651 var y1 = new BN(0);
22652 var x2 = new BN(0);
22653 var y2 = new BN(1);
22654
22655 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
22656 var a0;
22657 var b0;
22658 // First vector
22659 var a1;
22660 var b1;
22661 // Second vector
22662 var a2;
22663 var b2;
22664
22665 var prevR;
22666 var i = 0;
22667 var r;
22668 var x;
22669 while (u.cmpn(0) !== 0) {
22670 var q = v.div(u);
22671 r = v.sub(q.mul(u));
22672 x = x2.sub(q.mul(x1));
22673 var y = y2.sub(q.mul(y1));
22674
22675 if (!a1 && r.cmp(aprxSqrt) < 0) {
22676 a0 = prevR.neg();
22677 b0 = x1;
22678 a1 = r.neg();
22679 b1 = x;
22680 } else if (a1 && ++i === 2) {
22681 break;
22682 }
22683 prevR = r;
22684
22685 v = u;
22686 u = r;
22687 x2 = x1;
22688 x1 = x;
22689 y2 = y1;
22690 y1 = y;
22691 }
22692 a2 = r.neg();
22693 b2 = x;
22694
22695 var len1 = a1.sqr().add(b1.sqr());
22696 var len2 = a2.sqr().add(b2.sqr());
22697 if (len2.cmp(len1) >= 0) {
22698 a2 = a0;
22699 b2 = b0;
22700 }
22701
22702 // Normalize signs
22703 if (a1.negative) {
22704 a1 = a1.neg();
22705 b1 = b1.neg();
22706 }
22707 if (a2.negative) {
22708 a2 = a2.neg();
22709 b2 = b2.neg();
22710 }
22711
22712 return [
22713 { a: a1, b: b1 },
22714 { a: a2, b: b2 },
22715 ];
22716};
22717
22718ShortCurve.prototype._endoSplit = function _endoSplit(k) {
22719 var basis = this.endo.basis;
22720 var v1 = basis[0];
22721 var v2 = basis[1];
22722
22723 var c1 = v2.b.mul(k).divRound(this.n);
22724 var c2 = v1.b.neg().mul(k).divRound(this.n);
22725
22726 var p1 = c1.mul(v1.a);
22727 var p2 = c2.mul(v2.a);
22728 var q1 = c1.mul(v1.b);
22729 var q2 = c2.mul(v2.b);
22730
22731 // Calculate answer
22732 var k1 = k.sub(p1).sub(p2);
22733 var k2 = q1.add(q2).neg();
22734 return { k1: k1, k2: k2 };
22735};
22736
22737ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
22738 x = new BN(x, 16);
22739 if (!x.red)
22740 x = x.toRed(this.red);
22741
22742 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
22743 var y = y2.redSqrt();
22744 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
22745 throw new Error('invalid point');
22746
22747 // XXX Is there any way to tell if the number is odd without converting it
22748 // to non-red form?
22749 var isOdd = y.fromRed().isOdd();
22750 if (odd && !isOdd || !odd && isOdd)
22751 y = y.redNeg();
22752
22753 return this.point(x, y);
22754};
22755
22756ShortCurve.prototype.validate = function validate(point) {
22757 if (point.inf)
22758 return true;
22759
22760 var x = point.x;
22761 var y = point.y;
22762
22763 var ax = this.a.redMul(x);
22764 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
22765 return y.redSqr().redISub(rhs).cmpn(0) === 0;
22766};
22767
22768ShortCurve.prototype._endoWnafMulAdd =
22769 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
22770 var npoints = this._endoWnafT1;
22771 var ncoeffs = this._endoWnafT2;
22772 for (var i = 0; i < points.length; i++) {
22773 var split = this._endoSplit(coeffs[i]);
22774 var p = points[i];
22775 var beta = p._getBeta();
22776
22777 if (split.k1.negative) {
22778 split.k1.ineg();
22779 p = p.neg(true);
22780 }
22781 if (split.k2.negative) {
22782 split.k2.ineg();
22783 beta = beta.neg(true);
22784 }
22785
22786 npoints[i * 2] = p;
22787 npoints[i * 2 + 1] = beta;
22788 ncoeffs[i * 2] = split.k1;
22789 ncoeffs[i * 2 + 1] = split.k2;
22790 }
22791 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
22792
22793 // Clean-up references to points and coefficients
22794 for (var j = 0; j < i * 2; j++) {
22795 npoints[j] = null;
22796 ncoeffs[j] = null;
22797 }
22798 return res;
22799 };
22800
22801function Point(curve, x, y, isRed) {
22802 Base.BasePoint.call(this, curve, 'affine');
22803 if (x === null && y === null) {
22804 this.x = null;
22805 this.y = null;
22806 this.inf = true;
22807 } else {
22808 this.x = new BN(x, 16);
22809 this.y = new BN(y, 16);
22810 // Force redgomery representation when loading from JSON
22811 if (isRed) {
22812 this.x.forceRed(this.curve.red);
22813 this.y.forceRed(this.curve.red);
22814 }
22815 if (!this.x.red)
22816 this.x = this.x.toRed(this.curve.red);
22817 if (!this.y.red)
22818 this.y = this.y.toRed(this.curve.red);
22819 this.inf = false;
22820 }
22821}
22822inherits(Point, Base.BasePoint);
22823
22824ShortCurve.prototype.point = function point(x, y, isRed) {
22825 return new Point(this, x, y, isRed);
22826};
22827
22828ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
22829 return Point.fromJSON(this, obj, red);
22830};
22831
22832Point.prototype._getBeta = function _getBeta() {
22833 if (!this.curve.endo)
22834 return;
22835
22836 var pre = this.precomputed;
22837 if (pre && pre.beta)
22838 return pre.beta;
22839
22840 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
22841 if (pre) {
22842 var curve = this.curve;
22843 var endoMul = function(p) {
22844 return curve.point(p.x.redMul(curve.endo.beta), p.y);
22845 };
22846 pre.beta = beta;
22847 beta.precomputed = {
22848 beta: null,
22849 naf: pre.naf && {
22850 wnd: pre.naf.wnd,
22851 points: pre.naf.points.map(endoMul),
22852 },
22853 doubles: pre.doubles && {
22854 step: pre.doubles.step,
22855 points: pre.doubles.points.map(endoMul),
22856 },
22857 };
22858 }
22859 return beta;
22860};
22861
22862Point.prototype.toJSON = function toJSON() {
22863 if (!this.precomputed)
22864 return [ this.x, this.y ];
22865
22866 return [ this.x, this.y, this.precomputed && {
22867 doubles: this.precomputed.doubles && {
22868 step: this.precomputed.doubles.step,
22869 points: this.precomputed.doubles.points.slice(1),
22870 },
22871 naf: this.precomputed.naf && {
22872 wnd: this.precomputed.naf.wnd,
22873 points: this.precomputed.naf.points.slice(1),
22874 },
22875 } ];
22876};
22877
22878Point.fromJSON = function fromJSON(curve, obj, red) {
22879 if (typeof obj === 'string')
22880 obj = JSON.parse(obj);
22881 var res = curve.point(obj[0], obj[1], red);
22882 if (!obj[2])
22883 return res;
22884
22885 function obj2point(obj) {
22886 return curve.point(obj[0], obj[1], red);
22887 }
22888
22889 var pre = obj[2];
22890 res.precomputed = {
22891 beta: null,
22892 doubles: pre.doubles && {
22893 step: pre.doubles.step,
22894 points: [ res ].concat(pre.doubles.points.map(obj2point)),
22895 },
22896 naf: pre.naf && {
22897 wnd: pre.naf.wnd,
22898 points: [ res ].concat(pre.naf.points.map(obj2point)),
22899 },
22900 };
22901 return res;
22902};
22903
22904Point.prototype.inspect = function inspect() {
22905 if (this.isInfinity())
22906 return '<EC Point Infinity>';
22907 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
22908 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
22909};
22910
22911Point.prototype.isInfinity = function isInfinity() {
22912 return this.inf;
22913};
22914
22915Point.prototype.add = function add(p) {
22916 // O + P = P
22917 if (this.inf)
22918 return p;
22919
22920 // P + O = P
22921 if (p.inf)
22922 return this;
22923
22924 // P + P = 2P
22925 if (this.eq(p))
22926 return this.dbl();
22927
22928 // P + (-P) = O
22929 if (this.neg().eq(p))
22930 return this.curve.point(null, null);
22931
22932 // P + Q = O
22933 if (this.x.cmp(p.x) === 0)
22934 return this.curve.point(null, null);
22935
22936 var c = this.y.redSub(p.y);
22937 if (c.cmpn(0) !== 0)
22938 c = c.redMul(this.x.redSub(p.x).redInvm());
22939 var nx = c.redSqr().redISub(this.x).redISub(p.x);
22940 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
22941 return this.curve.point(nx, ny);
22942};
22943
22944Point.prototype.dbl = function dbl() {
22945 if (this.inf)
22946 return this;
22947
22948 // 2P = O
22949 var ys1 = this.y.redAdd(this.y);
22950 if (ys1.cmpn(0) === 0)
22951 return this.curve.point(null, null);
22952
22953 var a = this.curve.a;
22954
22955 var x2 = this.x.redSqr();
22956 var dyinv = ys1.redInvm();
22957 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
22958
22959 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
22960 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
22961 return this.curve.point(nx, ny);
22962};
22963
22964Point.prototype.getX = function getX() {
22965 return this.x.fromRed();
22966};
22967
22968Point.prototype.getY = function getY() {
22969 return this.y.fromRed();
22970};
22971
22972Point.prototype.mul = function mul(k) {
22973 k = new BN(k, 16);
22974 if (this.isInfinity())
22975 return this;
22976 else if (this._hasDoubles(k))
22977 return this.curve._fixedNafMul(this, k);
22978 else if (this.curve.endo)
22979 return this.curve._endoWnafMulAdd([ this ], [ k ]);
22980 else
22981 return this.curve._wnafMul(this, k);
22982};
22983
22984Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
22985 var points = [ this, p2 ];
22986 var coeffs = [ k1, k2 ];
22987 if (this.curve.endo)
22988 return this.curve._endoWnafMulAdd(points, coeffs);
22989 else
22990 return this.curve._wnafMulAdd(1, points, coeffs, 2);
22991};
22992
22993Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
22994 var points = [ this, p2 ];
22995 var coeffs = [ k1, k2 ];
22996 if (this.curve.endo)
22997 return this.curve._endoWnafMulAdd(points, coeffs, true);
22998 else
22999 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
23000};
23001
23002Point.prototype.eq = function eq(p) {
23003 return this === p ||
23004 this.inf === p.inf &&
23005 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
23006};
23007
23008Point.prototype.neg = function neg(_precompute) {
23009 if (this.inf)
23010 return this;
23011
23012 var res = this.curve.point(this.x, this.y.redNeg());
23013 if (_precompute && this.precomputed) {
23014 var pre = this.precomputed;
23015 var negate = function(p) {
23016 return p.neg();
23017 };
23018 res.precomputed = {
23019 naf: pre.naf && {
23020 wnd: pre.naf.wnd,
23021 points: pre.naf.points.map(negate),
23022 },
23023 doubles: pre.doubles && {
23024 step: pre.doubles.step,
23025 points: pre.doubles.points.map(negate),
23026 },
23027 };
23028 }
23029 return res;
23030};
23031
23032Point.prototype.toJ = function toJ() {
23033 if (this.inf)
23034 return this.curve.jpoint(null, null, null);
23035
23036 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
23037 return res;
23038};
23039
23040function JPoint(curve, x, y, z) {
23041 Base.BasePoint.call(this, curve, 'jacobian');
23042 if (x === null && y === null && z === null) {
23043 this.x = this.curve.one;
23044 this.y = this.curve.one;
23045 this.z = new BN(0);
23046 } else {
23047 this.x = new BN(x, 16);
23048 this.y = new BN(y, 16);
23049 this.z = new BN(z, 16);
23050 }
23051 if (!this.x.red)
23052 this.x = this.x.toRed(this.curve.red);
23053 if (!this.y.red)
23054 this.y = this.y.toRed(this.curve.red);
23055 if (!this.z.red)
23056 this.z = this.z.toRed(this.curve.red);
23057
23058 this.zOne = this.z === this.curve.one;
23059}
23060inherits(JPoint, Base.BasePoint);
23061
23062ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
23063 return new JPoint(this, x, y, z);
23064};
23065
23066JPoint.prototype.toP = function toP() {
23067 if (this.isInfinity())
23068 return this.curve.point(null, null);
23069
23070 var zinv = this.z.redInvm();
23071 var zinv2 = zinv.redSqr();
23072 var ax = this.x.redMul(zinv2);
23073 var ay = this.y.redMul(zinv2).redMul(zinv);
23074
23075 return this.curve.point(ax, ay);
23076};
23077
23078JPoint.prototype.neg = function neg() {
23079 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
23080};
23081
23082JPoint.prototype.add = function add(p) {
23083 // O + P = P
23084 if (this.isInfinity())
23085 return p;
23086
23087 // P + O = P
23088 if (p.isInfinity())
23089 return this;
23090
23091 // 12M + 4S + 7A
23092 var pz2 = p.z.redSqr();
23093 var z2 = this.z.redSqr();
23094 var u1 = this.x.redMul(pz2);
23095 var u2 = p.x.redMul(z2);
23096 var s1 = this.y.redMul(pz2.redMul(p.z));
23097 var s2 = p.y.redMul(z2.redMul(this.z));
23098
23099 var h = u1.redSub(u2);
23100 var r = s1.redSub(s2);
23101 if (h.cmpn(0) === 0) {
23102 if (r.cmpn(0) !== 0)
23103 return this.curve.jpoint(null, null, null);
23104 else
23105 return this.dbl();
23106 }
23107
23108 var h2 = h.redSqr();
23109 var h3 = h2.redMul(h);
23110 var v = u1.redMul(h2);
23111
23112 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
23113 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
23114 var nz = this.z.redMul(p.z).redMul(h);
23115
23116 return this.curve.jpoint(nx, ny, nz);
23117};
23118
23119JPoint.prototype.mixedAdd = function mixedAdd(p) {
23120 // O + P = P
23121 if (this.isInfinity())
23122 return p.toJ();
23123
23124 // P + O = P
23125 if (p.isInfinity())
23126 return this;
23127
23128 // 8M + 3S + 7A
23129 var z2 = this.z.redSqr();
23130 var u1 = this.x;
23131 var u2 = p.x.redMul(z2);
23132 var s1 = this.y;
23133 var s2 = p.y.redMul(z2).redMul(this.z);
23134
23135 var h = u1.redSub(u2);
23136 var r = s1.redSub(s2);
23137 if (h.cmpn(0) === 0) {
23138 if (r.cmpn(0) !== 0)
23139 return this.curve.jpoint(null, null, null);
23140 else
23141 return this.dbl();
23142 }
23143
23144 var h2 = h.redSqr();
23145 var h3 = h2.redMul(h);
23146 var v = u1.redMul(h2);
23147
23148 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
23149 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
23150 var nz = this.z.redMul(h);
23151
23152 return this.curve.jpoint(nx, ny, nz);
23153};
23154
23155JPoint.prototype.dblp = function dblp(pow) {
23156 if (pow === 0)
23157 return this;
23158 if (this.isInfinity())
23159 return this;
23160 if (!pow)
23161 return this.dbl();
23162
23163 var i;
23164 if (this.curve.zeroA || this.curve.threeA) {
23165 var r = this;
23166 for (i = 0; i < pow; i++)
23167 r = r.dbl();
23168 return r;
23169 }
23170
23171 // 1M + 2S + 1A + N * (4S + 5M + 8A)
23172 // N = 1 => 6M + 6S + 9A
23173 var a = this.curve.a;
23174 var tinv = this.curve.tinv;
23175
23176 var jx = this.x;
23177 var jy = this.y;
23178 var jz = this.z;
23179 var jz4 = jz.redSqr().redSqr();
23180
23181 // Reuse results
23182 var jyd = jy.redAdd(jy);
23183 for (i = 0; i < pow; i++) {
23184 var jx2 = jx.redSqr();
23185 var jyd2 = jyd.redSqr();
23186 var jyd4 = jyd2.redSqr();
23187 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
23188
23189 var t1 = jx.redMul(jyd2);
23190 var nx = c.redSqr().redISub(t1.redAdd(t1));
23191 var t2 = t1.redISub(nx);
23192 var dny = c.redMul(t2);
23193 dny = dny.redIAdd(dny).redISub(jyd4);
23194 var nz = jyd.redMul(jz);
23195 if (i + 1 < pow)
23196 jz4 = jz4.redMul(jyd4);
23197
23198 jx = nx;
23199 jz = nz;
23200 jyd = dny;
23201 }
23202
23203 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
23204};
23205
23206JPoint.prototype.dbl = function dbl() {
23207 if (this.isInfinity())
23208 return this;
23209
23210 if (this.curve.zeroA)
23211 return this._zeroDbl();
23212 else if (this.curve.threeA)
23213 return this._threeDbl();
23214 else
23215 return this._dbl();
23216};
23217
23218JPoint.prototype._zeroDbl = function _zeroDbl() {
23219 var nx;
23220 var ny;
23221 var nz;
23222 // Z = 1
23223 if (this.zOne) {
23224 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
23225 // #doubling-mdbl-2007-bl
23226 // 1M + 5S + 14A
23227
23228 // XX = X1^2
23229 var xx = this.x.redSqr();
23230 // YY = Y1^2
23231 var yy = this.y.redSqr();
23232 // YYYY = YY^2
23233 var yyyy = yy.redSqr();
23234 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
23235 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
23236 s = s.redIAdd(s);
23237 // M = 3 * XX + a; a = 0
23238 var m = xx.redAdd(xx).redIAdd(xx);
23239 // T = M ^ 2 - 2*S
23240 var t = m.redSqr().redISub(s).redISub(s);
23241
23242 // 8 * YYYY
23243 var yyyy8 = yyyy.redIAdd(yyyy);
23244 yyyy8 = yyyy8.redIAdd(yyyy8);
23245 yyyy8 = yyyy8.redIAdd(yyyy8);
23246
23247 // X3 = T
23248 nx = t;
23249 // Y3 = M * (S - T) - 8 * YYYY
23250 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
23251 // Z3 = 2*Y1
23252 nz = this.y.redAdd(this.y);
23253 } else {
23254 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
23255 // #doubling-dbl-2009-l
23256 // 2M + 5S + 13A
23257
23258 // A = X1^2
23259 var a = this.x.redSqr();
23260 // B = Y1^2
23261 var b = this.y.redSqr();
23262 // C = B^2
23263 var c = b.redSqr();
23264 // D = 2 * ((X1 + B)^2 - A - C)
23265 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
23266 d = d.redIAdd(d);
23267 // E = 3 * A
23268 var e = a.redAdd(a).redIAdd(a);
23269 // F = E^2
23270 var f = e.redSqr();
23271
23272 // 8 * C
23273 var c8 = c.redIAdd(c);
23274 c8 = c8.redIAdd(c8);
23275 c8 = c8.redIAdd(c8);
23276
23277 // X3 = F - 2 * D
23278 nx = f.redISub(d).redISub(d);
23279 // Y3 = E * (D - X3) - 8 * C
23280 ny = e.redMul(d.redISub(nx)).redISub(c8);
23281 // Z3 = 2 * Y1 * Z1
23282 nz = this.y.redMul(this.z);
23283 nz = nz.redIAdd(nz);
23284 }
23285
23286 return this.curve.jpoint(nx, ny, nz);
23287};
23288
23289JPoint.prototype._threeDbl = function _threeDbl() {
23290 var nx;
23291 var ny;
23292 var nz;
23293 // Z = 1
23294 if (this.zOne) {
23295 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
23296 // #doubling-mdbl-2007-bl
23297 // 1M + 5S + 15A
23298
23299 // XX = X1^2
23300 var xx = this.x.redSqr();
23301 // YY = Y1^2
23302 var yy = this.y.redSqr();
23303 // YYYY = YY^2
23304 var yyyy = yy.redSqr();
23305 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
23306 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
23307 s = s.redIAdd(s);
23308 // M = 3 * XX + a
23309 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
23310 // T = M^2 - 2 * S
23311 var t = m.redSqr().redISub(s).redISub(s);
23312 // X3 = T
23313 nx = t;
23314 // Y3 = M * (S - T) - 8 * YYYY
23315 var yyyy8 = yyyy.redIAdd(yyyy);
23316 yyyy8 = yyyy8.redIAdd(yyyy8);
23317 yyyy8 = yyyy8.redIAdd(yyyy8);
23318 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
23319 // Z3 = 2 * Y1
23320 nz = this.y.redAdd(this.y);
23321 } else {
23322 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
23323 // 3M + 5S
23324
23325 // delta = Z1^2
23326 var delta = this.z.redSqr();
23327 // gamma = Y1^2
23328 var gamma = this.y.redSqr();
23329 // beta = X1 * gamma
23330 var beta = this.x.redMul(gamma);
23331 // alpha = 3 * (X1 - delta) * (X1 + delta)
23332 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
23333 alpha = alpha.redAdd(alpha).redIAdd(alpha);
23334 // X3 = alpha^2 - 8 * beta
23335 var beta4 = beta.redIAdd(beta);
23336 beta4 = beta4.redIAdd(beta4);
23337 var beta8 = beta4.redAdd(beta4);
23338 nx = alpha.redSqr().redISub(beta8);
23339 // Z3 = (Y1 + Z1)^2 - gamma - delta
23340 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
23341 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
23342 var ggamma8 = gamma.redSqr();
23343 ggamma8 = ggamma8.redIAdd(ggamma8);
23344 ggamma8 = ggamma8.redIAdd(ggamma8);
23345 ggamma8 = ggamma8.redIAdd(ggamma8);
23346 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
23347 }
23348
23349 return this.curve.jpoint(nx, ny, nz);
23350};
23351
23352JPoint.prototype._dbl = function _dbl() {
23353 var a = this.curve.a;
23354
23355 // 4M + 6S + 10A
23356 var jx = this.x;
23357 var jy = this.y;
23358 var jz = this.z;
23359 var jz4 = jz.redSqr().redSqr();
23360
23361 var jx2 = jx.redSqr();
23362 var jy2 = jy.redSqr();
23363
23364 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
23365
23366 var jxd4 = jx.redAdd(jx);
23367 jxd4 = jxd4.redIAdd(jxd4);
23368 var t1 = jxd4.redMul(jy2);
23369 var nx = c.redSqr().redISub(t1.redAdd(t1));
23370 var t2 = t1.redISub(nx);
23371
23372 var jyd8 = jy2.redSqr();
23373 jyd8 = jyd8.redIAdd(jyd8);
23374 jyd8 = jyd8.redIAdd(jyd8);
23375 jyd8 = jyd8.redIAdd(jyd8);
23376 var ny = c.redMul(t2).redISub(jyd8);
23377 var nz = jy.redAdd(jy).redMul(jz);
23378
23379 return this.curve.jpoint(nx, ny, nz);
23380};
23381
23382JPoint.prototype.trpl = function trpl() {
23383 if (!this.curve.zeroA)
23384 return this.dbl().add(this);
23385
23386 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
23387 // 5M + 10S + ...
23388
23389 // XX = X1^2
23390 var xx = this.x.redSqr();
23391 // YY = Y1^2
23392 var yy = this.y.redSqr();
23393 // ZZ = Z1^2
23394 var zz = this.z.redSqr();
23395 // YYYY = YY^2
23396 var yyyy = yy.redSqr();
23397 // M = 3 * XX + a * ZZ2; a = 0
23398 var m = xx.redAdd(xx).redIAdd(xx);
23399 // MM = M^2
23400 var mm = m.redSqr();
23401 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
23402 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
23403 e = e.redIAdd(e);
23404 e = e.redAdd(e).redIAdd(e);
23405 e = e.redISub(mm);
23406 // EE = E^2
23407 var ee = e.redSqr();
23408 // T = 16*YYYY
23409 var t = yyyy.redIAdd(yyyy);
23410 t = t.redIAdd(t);
23411 t = t.redIAdd(t);
23412 t = t.redIAdd(t);
23413 // U = (M + E)^2 - MM - EE - T
23414 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
23415 // X3 = 4 * (X1 * EE - 4 * YY * U)
23416 var yyu4 = yy.redMul(u);
23417 yyu4 = yyu4.redIAdd(yyu4);
23418 yyu4 = yyu4.redIAdd(yyu4);
23419 var nx = this.x.redMul(ee).redISub(yyu4);
23420 nx = nx.redIAdd(nx);
23421 nx = nx.redIAdd(nx);
23422 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
23423 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
23424 ny = ny.redIAdd(ny);
23425 ny = ny.redIAdd(ny);
23426 ny = ny.redIAdd(ny);
23427 // Z3 = (Z1 + E)^2 - ZZ - EE
23428 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
23429
23430 return this.curve.jpoint(nx, ny, nz);
23431};
23432
23433JPoint.prototype.mul = function mul(k, kbase) {
23434 k = new BN(k, kbase);
23435
23436 return this.curve._wnafMul(this, k);
23437};
23438
23439JPoint.prototype.eq = function eq(p) {
23440 if (p.type === 'affine')
23441 return this.eq(p.toJ());
23442
23443 if (this === p)
23444 return true;
23445
23446 // x1 * z2^2 == x2 * z1^2
23447 var z2 = this.z.redSqr();
23448 var pz2 = p.z.redSqr();
23449 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
23450 return false;
23451
23452 // y1 * z2^3 == y2 * z1^3
23453 var z3 = z2.redMul(this.z);
23454 var pz3 = pz2.redMul(p.z);
23455 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
23456};
23457
23458JPoint.prototype.eqXToP = function eqXToP(x) {
23459 var zs = this.z.redSqr();
23460 var rx = x.toRed(this.curve.red).redMul(zs);
23461 if (this.x.cmp(rx) === 0)
23462 return true;
23463
23464 var xc = x.clone();
23465 var t = this.curve.redN.redMul(zs);
23466 for (;;) {
23467 xc.iadd(this.curve.n);
23468 if (xc.cmp(this.curve.p) >= 0)
23469 return false;
23470
23471 rx.redIAdd(t);
23472 if (this.x.cmp(rx) === 0)
23473 return true;
23474 }
23475};
23476
23477JPoint.prototype.inspect = function inspect() {
23478 if (this.isInfinity())
23479 return '<EC JPoint Infinity>';
23480 return '<EC JPoint x: ' + this.x.toString(16, 2) +
23481 ' y: ' + this.y.toString(16, 2) +
23482 ' z: ' + this.z.toString(16, 2) + '>';
23483};
23484
23485JPoint.prototype.isInfinity = function isInfinity() {
23486 // XXX This code assumes that zero is always zero in red
23487 return this.z.cmpn(0) === 0;
23488};
23489
23490},{"../utils":117,"./base":104,"bn.js":118,"inherits":152}],109:[function(require,module,exports){
23491'use strict';
23492
23493var curves = exports;
23494
23495var hash = require('hash.js');
23496var curve = require('./curve');
23497var utils = require('./utils');
23498
23499var assert = utils.assert;
23500
23501function PresetCurve(options) {
23502 if (options.type === 'short')
23503 this.curve = new curve.short(options);
23504 else if (options.type === 'edwards')
23505 this.curve = new curve.edwards(options);
23506 else
23507 this.curve = new curve.mont(options);
23508 this.g = this.curve.g;
23509 this.n = this.curve.n;
23510 this.hash = options.hash;
23511
23512 assert(this.g.validate(), 'Invalid curve');
23513 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
23514}
23515curves.PresetCurve = PresetCurve;
23516
23517function defineCurve(name, options) {
23518 Object.defineProperty(curves, name, {
23519 configurable: true,
23520 enumerable: true,
23521 get: function() {
23522 var curve = new PresetCurve(options);
23523 Object.defineProperty(curves, name, {
23524 configurable: true,
23525 enumerable: true,
23526 value: curve,
23527 });
23528 return curve;
23529 },
23530 });
23531}
23532
23533defineCurve('p192', {
23534 type: 'short',
23535 prime: 'p192',
23536 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
23537 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
23538 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
23539 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
23540 hash: hash.sha256,
23541 gRed: false,
23542 g: [
23543 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
23544 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',
23545 ],
23546});
23547
23548defineCurve('p224', {
23549 type: 'short',
23550 prime: 'p224',
23551 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
23552 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
23553 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
23554 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
23555 hash: hash.sha256,
23556 gRed: false,
23557 g: [
23558 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
23559 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',
23560 ],
23561});
23562
23563defineCurve('p256', {
23564 type: 'short',
23565 prime: null,
23566 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
23567 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
23568 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
23569 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
23570 hash: hash.sha256,
23571 gRed: false,
23572 g: [
23573 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
23574 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',
23575 ],
23576});
23577
23578defineCurve('p384', {
23579 type: 'short',
23580 prime: null,
23581 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
23582 'fffffffe ffffffff 00000000 00000000 ffffffff',
23583 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
23584 'fffffffe ffffffff 00000000 00000000 fffffffc',
23585 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
23586 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
23587 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
23588 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
23589 hash: hash.sha384,
23590 gRed: false,
23591 g: [
23592 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
23593 '5502f25d bf55296c 3a545e38 72760ab7',
23594 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
23595 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',
23596 ],
23597});
23598
23599defineCurve('p521', {
23600 type: 'short',
23601 prime: null,
23602 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
23603 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
23604 'ffffffff ffffffff ffffffff ffffffff ffffffff',
23605 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
23606 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
23607 'ffffffff ffffffff ffffffff ffffffff fffffffc',
23608 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
23609 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
23610 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
23611 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
23612 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
23613 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
23614 hash: hash.sha512,
23615 gRed: false,
23616 g: [
23617 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
23618 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
23619 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
23620 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
23621 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
23622 '3fad0761 353c7086 a272c240 88be9476 9fd16650',
23623 ],
23624});
23625
23626defineCurve('curve25519', {
23627 type: 'mont',
23628 prime: 'p25519',
23629 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
23630 a: '76d06',
23631 b: '1',
23632 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
23633 hash: hash.sha256,
23634 gRed: false,
23635 g: [
23636 '9',
23637 ],
23638});
23639
23640defineCurve('ed25519', {
23641 type: 'edwards',
23642 prime: 'p25519',
23643 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
23644 a: '-1',
23645 c: '1',
23646 // -121665 * (121666^(-1)) (mod P)
23647 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
23648 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
23649 hash: hash.sha256,
23650 gRed: false,
23651 g: [
23652 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
23653
23654 // 4/5
23655 '6666666666666666666666666666666666666666666666666666666666666658',
23656 ],
23657});
23658
23659var pre;
23660try {
23661 pre = require('./precomputed/secp256k1');
23662} catch (e) {
23663 pre = undefined;
23664}
23665
23666defineCurve('secp256k1', {
23667 type: 'short',
23668 prime: 'k256',
23669 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
23670 a: '0',
23671 b: '7',
23672 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
23673 h: '1',
23674 hash: hash.sha256,
23675
23676 // Precomputed endomorphism
23677 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
23678 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
23679 basis: [
23680 {
23681 a: '3086d221a7d46bcde86c90e49284eb15',
23682 b: '-e4437ed6010e88286f547fa90abfe4c3',
23683 },
23684 {
23685 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
23686 b: '3086d221a7d46bcde86c90e49284eb15',
23687 },
23688 ],
23689
23690 gRed: false,
23691 g: [
23692 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
23693 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
23694 pre,
23695 ],
23696});
23697
23698},{"./curve":106,"./precomputed/secp256k1":116,"./utils":117,"hash.js":138}],110:[function(require,module,exports){
23699'use strict';
23700
23701var BN = require('bn.js');
23702var HmacDRBG = require('hmac-drbg');
23703var utils = require('../utils');
23704var curves = require('../curves');
23705var rand = require('brorand');
23706var assert = utils.assert;
23707
23708var KeyPair = require('./key');
23709var Signature = require('./signature');
23710
23711function EC(options) {
23712 if (!(this instanceof EC))
23713 return new EC(options);
23714
23715 // Shortcut `elliptic.ec(curve-name)`
23716 if (typeof options === 'string') {
23717 assert(Object.prototype.hasOwnProperty.call(curves, options),
23718 'Unknown curve ' + options);
23719
23720 options = curves[options];
23721 }
23722
23723 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
23724 if (options instanceof curves.PresetCurve)
23725 options = { curve: options };
23726
23727 this.curve = options.curve.curve;
23728 this.n = this.curve.n;
23729 this.nh = this.n.ushrn(1);
23730 this.g = this.curve.g;
23731
23732 // Point on curve
23733 this.g = options.curve.g;
23734 this.g.precompute(options.curve.n.bitLength() + 1);
23735
23736 // Hash for function for DRBG
23737 this.hash = options.hash || options.curve.hash;
23738}
23739module.exports = EC;
23740
23741EC.prototype.keyPair = function keyPair(options) {
23742 return new KeyPair(this, options);
23743};
23744
23745EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
23746 return KeyPair.fromPrivate(this, priv, enc);
23747};
23748
23749EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
23750 return KeyPair.fromPublic(this, pub, enc);
23751};
23752
23753EC.prototype.genKeyPair = function genKeyPair(options) {
23754 if (!options)
23755 options = {};
23756
23757 // Instantiate Hmac_DRBG
23758 var drbg = new HmacDRBG({
23759 hash: this.hash,
23760 pers: options.pers,
23761 persEnc: options.persEnc || 'utf8',
23762 entropy: options.entropy || rand(this.hash.hmacStrength),
23763 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
23764 nonce: this.n.toArray(),
23765 });
23766
23767 var bytes = this.n.byteLength();
23768 var ns2 = this.n.sub(new BN(2));
23769 for (;;) {
23770 var priv = new BN(drbg.generate(bytes));
23771 if (priv.cmp(ns2) > 0)
23772 continue;
23773
23774 priv.iaddn(1);
23775 return this.keyFromPrivate(priv);
23776 }
23777};
23778
23779EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) {
23780 var delta = msg.byteLength() * 8 - this.n.bitLength();
23781 if (delta > 0)
23782 msg = msg.ushrn(delta);
23783 if (!truncOnly && msg.cmp(this.n) >= 0)
23784 return msg.sub(this.n);
23785 else
23786 return msg;
23787};
23788
23789EC.prototype.sign = function sign(msg, key, enc, options) {
23790 if (typeof enc === 'object') {
23791 options = enc;
23792 enc = null;
23793 }
23794 if (!options)
23795 options = {};
23796
23797 key = this.keyFromPrivate(key, enc);
23798 msg = this._truncateToN(new BN(msg, 16));
23799
23800 // Zero-extend key to provide enough entropy
23801 var bytes = this.n.byteLength();
23802 var bkey = key.getPrivate().toArray('be', bytes);
23803
23804 // Zero-extend nonce to have the same byte size as N
23805 var nonce = msg.toArray('be', bytes);
23806
23807 // Instantiate Hmac_DRBG
23808 var drbg = new HmacDRBG({
23809 hash: this.hash,
23810 entropy: bkey,
23811 nonce: nonce,
23812 pers: options.pers,
23813 persEnc: options.persEnc || 'utf8',
23814 });
23815
23816 // Number of bytes to generate
23817 var ns1 = this.n.sub(new BN(1));
23818
23819 for (var iter = 0; ; iter++) {
23820 var k = options.k ?
23821 options.k(iter) :
23822 new BN(drbg.generate(this.n.byteLength()));
23823 k = this._truncateToN(k, true);
23824 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
23825 continue;
23826
23827 var kp = this.g.mul(k);
23828 if (kp.isInfinity())
23829 continue;
23830
23831 var kpX = kp.getX();
23832 var r = kpX.umod(this.n);
23833 if (r.cmpn(0) === 0)
23834 continue;
23835
23836 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
23837 s = s.umod(this.n);
23838 if (s.cmpn(0) === 0)
23839 continue;
23840
23841 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
23842 (kpX.cmp(r) !== 0 ? 2 : 0);
23843
23844 // Use complement of `s`, if it is > `n / 2`
23845 if (options.canonical && s.cmp(this.nh) > 0) {
23846 s = this.n.sub(s);
23847 recoveryParam ^= 1;
23848 }
23849
23850 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
23851 }
23852};
23853
23854EC.prototype.verify = function verify(msg, signature, key, enc) {
23855 msg = this._truncateToN(new BN(msg, 16));
23856 key = this.keyFromPublic(key, enc);
23857 signature = new Signature(signature, 'hex');
23858
23859 // Perform primitive values validation
23860 var r = signature.r;
23861 var s = signature.s;
23862 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
23863 return false;
23864 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
23865 return false;
23866
23867 // Validate signature
23868 var sinv = s.invm(this.n);
23869 var u1 = sinv.mul(msg).umod(this.n);
23870 var u2 = sinv.mul(r).umod(this.n);
23871 var p;
23872
23873 if (!this.curve._maxwellTrick) {
23874 p = this.g.mulAdd(u1, key.getPublic(), u2);
23875 if (p.isInfinity())
23876 return false;
23877
23878 return p.getX().umod(this.n).cmp(r) === 0;
23879 }
23880
23881 // NOTE: Greg Maxwell's trick, inspired by:
23882 // https://git.io/vad3K
23883
23884 p = this.g.jmulAdd(u1, key.getPublic(), u2);
23885 if (p.isInfinity())
23886 return false;
23887
23888 // Compare `p.x` of Jacobian point with `r`,
23889 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
23890 // inverse of `p.z^2`
23891 return p.eqXToP(r);
23892};
23893
23894EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
23895 assert((3 & j) === j, 'The recovery param is more than two bits');
23896 signature = new Signature(signature, enc);
23897
23898 var n = this.n;
23899 var e = new BN(msg);
23900 var r = signature.r;
23901 var s = signature.s;
23902
23903 // A set LSB signifies that the y-coordinate is odd
23904 var isYOdd = j & 1;
23905 var isSecondKey = j >> 1;
23906 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
23907 throw new Error('Unable to find sencond key candinate');
23908
23909 // 1.1. Let x = r + jn.
23910 if (isSecondKey)
23911 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
23912 else
23913 r = this.curve.pointFromX(r, isYOdd);
23914
23915 var rInv = signature.r.invm(n);
23916 var s1 = n.sub(e).mul(rInv).umod(n);
23917 var s2 = s.mul(rInv).umod(n);
23918
23919 // 1.6.1 Compute Q = r^-1 (sR - eG)
23920 // Q = r^-1 (sR + -eG)
23921 return this.g.mulAdd(s1, r, s2);
23922};
23923
23924EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
23925 signature = new Signature(signature, enc);
23926 if (signature.recoveryParam !== null)
23927 return signature.recoveryParam;
23928
23929 for (var i = 0; i < 4; i++) {
23930 var Qprime;
23931 try {
23932 Qprime = this.recoverPubKey(e, signature, i);
23933 } catch (e) {
23934 continue;
23935 }
23936
23937 if (Qprime.eq(Q))
23938 return i;
23939 }
23940 throw new Error('Unable to find valid recovery factor');
23941};
23942
23943},{"../curves":109,"../utils":117,"./key":111,"./signature":112,"bn.js":118,"brorand":32,"hmac-drbg":150}],111:[function(require,module,exports){
23944'use strict';
23945
23946var BN = require('bn.js');
23947var utils = require('../utils');
23948var assert = utils.assert;
23949
23950function KeyPair(ec, options) {
23951 this.ec = ec;
23952 this.priv = null;
23953 this.pub = null;
23954
23955 // KeyPair(ec, { priv: ..., pub: ... })
23956 if (options.priv)
23957 this._importPrivate(options.priv, options.privEnc);
23958 if (options.pub)
23959 this._importPublic(options.pub, options.pubEnc);
23960}
23961module.exports = KeyPair;
23962
23963KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
23964 if (pub instanceof KeyPair)
23965 return pub;
23966
23967 return new KeyPair(ec, {
23968 pub: pub,
23969 pubEnc: enc,
23970 });
23971};
23972
23973KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
23974 if (priv instanceof KeyPair)
23975 return priv;
23976
23977 return new KeyPair(ec, {
23978 priv: priv,
23979 privEnc: enc,
23980 });
23981};
23982
23983KeyPair.prototype.validate = function validate() {
23984 var pub = this.getPublic();
23985
23986 if (pub.isInfinity())
23987 return { result: false, reason: 'Invalid public key' };
23988 if (!pub.validate())
23989 return { result: false, reason: 'Public key is not a point' };
23990 if (!pub.mul(this.ec.curve.n).isInfinity())
23991 return { result: false, reason: 'Public key * N != O' };
23992
23993 return { result: true, reason: null };
23994};
23995
23996KeyPair.prototype.getPublic = function getPublic(compact, enc) {
23997 // compact is optional argument
23998 if (typeof compact === 'string') {
23999 enc = compact;
24000 compact = null;
24001 }
24002
24003 if (!this.pub)
24004 this.pub = this.ec.g.mul(this.priv);
24005
24006 if (!enc)
24007 return this.pub;
24008
24009 return this.pub.encode(enc, compact);
24010};
24011
24012KeyPair.prototype.getPrivate = function getPrivate(enc) {
24013 if (enc === 'hex')
24014 return this.priv.toString(16, 2);
24015 else
24016 return this.priv;
24017};
24018
24019KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
24020 this.priv = new BN(key, enc || 16);
24021
24022 // Ensure that the priv won't be bigger than n, otherwise we may fail
24023 // in fixed multiplication method
24024 this.priv = this.priv.umod(this.ec.curve.n);
24025};
24026
24027KeyPair.prototype._importPublic = function _importPublic(key, enc) {
24028 if (key.x || key.y) {
24029 // Montgomery points only have an `x` coordinate.
24030 // Weierstrass/Edwards points on the other hand have both `x` and
24031 // `y` coordinates.
24032 if (this.ec.curve.type === 'mont') {
24033 assert(key.x, 'Need x coordinate');
24034 } else if (this.ec.curve.type === 'short' ||
24035 this.ec.curve.type === 'edwards') {
24036 assert(key.x && key.y, 'Need both x and y coordinate');
24037 }
24038 this.pub = this.ec.curve.point(key.x, key.y);
24039 return;
24040 }
24041 this.pub = this.ec.curve.decodePoint(key, enc);
24042};
24043
24044// ECDH
24045KeyPair.prototype.derive = function derive(pub) {
24046 if(!pub.validate()) {
24047 assert(pub.validate(), 'public point not validated');
24048 }
24049 return pub.mul(this.priv).getX();
24050};
24051
24052// ECDSA
24053KeyPair.prototype.sign = function sign(msg, enc, options) {
24054 return this.ec.sign(msg, this, enc, options);
24055};
24056
24057KeyPair.prototype.verify = function verify(msg, signature) {
24058 return this.ec.verify(msg, signature, this);
24059};
24060
24061KeyPair.prototype.inspect = function inspect() {
24062 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
24063 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
24064};
24065
24066},{"../utils":117,"bn.js":118}],112:[function(require,module,exports){
24067'use strict';
24068
24069var BN = require('bn.js');
24070
24071var utils = require('../utils');
24072var assert = utils.assert;
24073
24074function Signature(options, enc) {
24075 if (options instanceof Signature)
24076 return options;
24077
24078 if (this._importDER(options, enc))
24079 return;
24080
24081 assert(options.r && options.s, 'Signature without r or s');
24082 this.r = new BN(options.r, 16);
24083 this.s = new BN(options.s, 16);
24084 if (options.recoveryParam === undefined)
24085 this.recoveryParam = null;
24086 else
24087 this.recoveryParam = options.recoveryParam;
24088}
24089module.exports = Signature;
24090
24091function Position() {
24092 this.place = 0;
24093}
24094
24095function getLength(buf, p) {
24096 var initial = buf[p.place++];
24097 if (!(initial & 0x80)) {
24098 return initial;
24099 }
24100 var octetLen = initial & 0xf;
24101
24102 // Indefinite length or overflow
24103 if (octetLen === 0 || octetLen > 4) {
24104 return false;
24105 }
24106
24107 var val = 0;
24108 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
24109 val <<= 8;
24110 val |= buf[off];
24111 val >>>= 0;
24112 }
24113
24114 // Leading zeroes
24115 if (val <= 0x7f) {
24116 return false;
24117 }
24118
24119 p.place = off;
24120 return val;
24121}
24122
24123function rmPadding(buf) {
24124 var i = 0;
24125 var len = buf.length - 1;
24126 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
24127 i++;
24128 }
24129 if (i === 0) {
24130 return buf;
24131 }
24132 return buf.slice(i);
24133}
24134
24135Signature.prototype._importDER = function _importDER(data, enc) {
24136 data = utils.toArray(data, enc);
24137 var p = new Position();
24138 if (data[p.place++] !== 0x30) {
24139 return false;
24140 }
24141 var len = getLength(data, p);
24142 if (len === false) {
24143 return false;
24144 }
24145 if ((len + p.place) !== data.length) {
24146 return false;
24147 }
24148 if (data[p.place++] !== 0x02) {
24149 return false;
24150 }
24151 var rlen = getLength(data, p);
24152 if (rlen === false) {
24153 return false;
24154 }
24155 var r = data.slice(p.place, rlen + p.place);
24156 p.place += rlen;
24157 if (data[p.place++] !== 0x02) {
24158 return false;
24159 }
24160 var slen = getLength(data, p);
24161 if (slen === false) {
24162 return false;
24163 }
24164 if (data.length !== slen + p.place) {
24165 return false;
24166 }
24167 var s = data.slice(p.place, slen + p.place);
24168 if (r[0] === 0) {
24169 if (r[1] & 0x80) {
24170 r = r.slice(1);
24171 } else {
24172 // Leading zeroes
24173 return false;
24174 }
24175 }
24176 if (s[0] === 0) {
24177 if (s[1] & 0x80) {
24178 s = s.slice(1);
24179 } else {
24180 // Leading zeroes
24181 return false;
24182 }
24183 }
24184
24185 this.r = new BN(r);
24186 this.s = new BN(s);
24187 this.recoveryParam = null;
24188
24189 return true;
24190};
24191
24192function constructLength(arr, len) {
24193 if (len < 0x80) {
24194 arr.push(len);
24195 return;
24196 }
24197 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
24198 arr.push(octets | 0x80);
24199 while (--octets) {
24200 arr.push((len >>> (octets << 3)) & 0xff);
24201 }
24202 arr.push(len);
24203}
24204
24205Signature.prototype.toDER = function toDER(enc) {
24206 var r = this.r.toArray();
24207 var s = this.s.toArray();
24208
24209 // Pad values
24210 if (r[0] & 0x80)
24211 r = [ 0 ].concat(r);
24212 // Pad values
24213 if (s[0] & 0x80)
24214 s = [ 0 ].concat(s);
24215
24216 r = rmPadding(r);
24217 s = rmPadding(s);
24218
24219 while (!s[0] && !(s[1] & 0x80)) {
24220 s = s.slice(1);
24221 }
24222 var arr = [ 0x02 ];
24223 constructLength(arr, r.length);
24224 arr = arr.concat(r);
24225 arr.push(0x02);
24226 constructLength(arr, s.length);
24227 var backHalf = arr.concat(s);
24228 var res = [ 0x30 ];
24229 constructLength(res, backHalf.length);
24230 res = res.concat(backHalf);
24231 return utils.encode(res, enc);
24232};
24233
24234},{"../utils":117,"bn.js":118}],113:[function(require,module,exports){
24235'use strict';
24236
24237var hash = require('hash.js');
24238var curves = require('../curves');
24239var utils = require('../utils');
24240var assert = utils.assert;
24241var parseBytes = utils.parseBytes;
24242var KeyPair = require('./key');
24243var Signature = require('./signature');
24244
24245function EDDSA(curve) {
24246 assert(curve === 'ed25519', 'only tested with ed25519 so far');
24247
24248 if (!(this instanceof EDDSA))
24249 return new EDDSA(curve);
24250
24251 curve = curves[curve].curve;
24252 this.curve = curve;
24253 this.g = curve.g;
24254 this.g.precompute(curve.n.bitLength() + 1);
24255
24256 this.pointClass = curve.point().constructor;
24257 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
24258 this.hash = hash.sha512;
24259}
24260
24261module.exports = EDDSA;
24262
24263/**
24264* @param {Array|String} message - message bytes
24265* @param {Array|String|KeyPair} secret - secret bytes or a keypair
24266* @returns {Signature} - signature
24267*/
24268EDDSA.prototype.sign = function sign(message, secret) {
24269 message = parseBytes(message);
24270 var key = this.keyFromSecret(secret);
24271 var r = this.hashInt(key.messagePrefix(), message);
24272 var R = this.g.mul(r);
24273 var Rencoded = this.encodePoint(R);
24274 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
24275 .mul(key.priv());
24276 var S = r.add(s_).umod(this.curve.n);
24277 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
24278};
24279
24280/**
24281* @param {Array} message - message bytes
24282* @param {Array|String|Signature} sig - sig bytes
24283* @param {Array|String|Point|KeyPair} pub - public key
24284* @returns {Boolean} - true if public key matches sig of message
24285*/
24286EDDSA.prototype.verify = function verify(message, sig, pub) {
24287 message = parseBytes(message);
24288 sig = this.makeSignature(sig);
24289 var key = this.keyFromPublic(pub);
24290 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
24291 var SG = this.g.mul(sig.S());
24292 var RplusAh = sig.R().add(key.pub().mul(h));
24293 return RplusAh.eq(SG);
24294};
24295
24296EDDSA.prototype.hashInt = function hashInt() {
24297 var hash = this.hash();
24298 for (var i = 0; i < arguments.length; i++)
24299 hash.update(arguments[i]);
24300 return utils.intFromLE(hash.digest()).umod(this.curve.n);
24301};
24302
24303EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
24304 return KeyPair.fromPublic(this, pub);
24305};
24306
24307EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
24308 return KeyPair.fromSecret(this, secret);
24309};
24310
24311EDDSA.prototype.makeSignature = function makeSignature(sig) {
24312 if (sig instanceof Signature)
24313 return sig;
24314 return new Signature(this, sig);
24315};
24316
24317/**
24318* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
24319*
24320* EDDSA defines methods for encoding and decoding points and integers. These are
24321* helper convenience methods, that pass along to utility functions implied
24322* parameters.
24323*
24324*/
24325EDDSA.prototype.encodePoint = function encodePoint(point) {
24326 var enc = point.getY().toArray('le', this.encodingLength);
24327 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
24328 return enc;
24329};
24330
24331EDDSA.prototype.decodePoint = function decodePoint(bytes) {
24332 bytes = utils.parseBytes(bytes);
24333
24334 var lastIx = bytes.length - 1;
24335 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
24336 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
24337
24338 var y = utils.intFromLE(normed);
24339 return this.curve.pointFromY(y, xIsOdd);
24340};
24341
24342EDDSA.prototype.encodeInt = function encodeInt(num) {
24343 return num.toArray('le', this.encodingLength);
24344};
24345
24346EDDSA.prototype.decodeInt = function decodeInt(bytes) {
24347 return utils.intFromLE(bytes);
24348};
24349
24350EDDSA.prototype.isPoint = function isPoint(val) {
24351 return val instanceof this.pointClass;
24352};
24353
24354},{"../curves":109,"../utils":117,"./key":114,"./signature":115,"hash.js":138}],114:[function(require,module,exports){
24355'use strict';
24356
24357var utils = require('../utils');
24358var assert = utils.assert;
24359var parseBytes = utils.parseBytes;
24360var cachedProperty = utils.cachedProperty;
24361
24362/**
24363* @param {EDDSA} eddsa - instance
24364* @param {Object} params - public/private key parameters
24365*
24366* @param {Array<Byte>} [params.secret] - secret seed bytes
24367* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
24368* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
24369*
24370*/
24371function KeyPair(eddsa, params) {
24372 this.eddsa = eddsa;
24373 this._secret = parseBytes(params.secret);
24374 if (eddsa.isPoint(params.pub))
24375 this._pub = params.pub;
24376 else
24377 this._pubBytes = parseBytes(params.pub);
24378}
24379
24380KeyPair.fromPublic = function fromPublic(eddsa, pub) {
24381 if (pub instanceof KeyPair)
24382 return pub;
24383 return new KeyPair(eddsa, { pub: pub });
24384};
24385
24386KeyPair.fromSecret = function fromSecret(eddsa, secret) {
24387 if (secret instanceof KeyPair)
24388 return secret;
24389 return new KeyPair(eddsa, { secret: secret });
24390};
24391
24392KeyPair.prototype.secret = function secret() {
24393 return this._secret;
24394};
24395
24396cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
24397 return this.eddsa.encodePoint(this.pub());
24398});
24399
24400cachedProperty(KeyPair, 'pub', function pub() {
24401 if (this._pubBytes)
24402 return this.eddsa.decodePoint(this._pubBytes);
24403 return this.eddsa.g.mul(this.priv());
24404});
24405
24406cachedProperty(KeyPair, 'privBytes', function privBytes() {
24407 var eddsa = this.eddsa;
24408 var hash = this.hash();
24409 var lastIx = eddsa.encodingLength - 1;
24410
24411 var a = hash.slice(0, eddsa.encodingLength);
24412 a[0] &= 248;
24413 a[lastIx] &= 127;
24414 a[lastIx] |= 64;
24415
24416 return a;
24417});
24418
24419cachedProperty(KeyPair, 'priv', function priv() {
24420 return this.eddsa.decodeInt(this.privBytes());
24421});
24422
24423cachedProperty(KeyPair, 'hash', function hash() {
24424 return this.eddsa.hash().update(this.secret()).digest();
24425});
24426
24427cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
24428 return this.hash().slice(this.eddsa.encodingLength);
24429});
24430
24431KeyPair.prototype.sign = function sign(message) {
24432 assert(this._secret, 'KeyPair can only verify');
24433 return this.eddsa.sign(message, this);
24434};
24435
24436KeyPair.prototype.verify = function verify(message, sig) {
24437 return this.eddsa.verify(message, sig, this);
24438};
24439
24440KeyPair.prototype.getSecret = function getSecret(enc) {
24441 assert(this._secret, 'KeyPair is public only');
24442 return utils.encode(this.secret(), enc);
24443};
24444
24445KeyPair.prototype.getPublic = function getPublic(enc) {
24446 return utils.encode(this.pubBytes(), enc);
24447};
24448
24449module.exports = KeyPair;
24450
24451},{"../utils":117}],115:[function(require,module,exports){
24452'use strict';
24453
24454var BN = require('bn.js');
24455var utils = require('../utils');
24456var assert = utils.assert;
24457var cachedProperty = utils.cachedProperty;
24458var parseBytes = utils.parseBytes;
24459
24460/**
24461* @param {EDDSA} eddsa - eddsa instance
24462* @param {Array<Bytes>|Object} sig -
24463* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
24464* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
24465* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
24466* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
24467*/
24468function Signature(eddsa, sig) {
24469 this.eddsa = eddsa;
24470
24471 if (typeof sig !== 'object')
24472 sig = parseBytes(sig);
24473
24474 if (Array.isArray(sig)) {
24475 sig = {
24476 R: sig.slice(0, eddsa.encodingLength),
24477 S: sig.slice(eddsa.encodingLength),
24478 };
24479 }
24480
24481 assert(sig.R && sig.S, 'Signature without R or S');
24482
24483 if (eddsa.isPoint(sig.R))
24484 this._R = sig.R;
24485 if (sig.S instanceof BN)
24486 this._S = sig.S;
24487
24488 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
24489 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
24490}
24491
24492cachedProperty(Signature, 'S', function S() {
24493 return this.eddsa.decodeInt(this.Sencoded());
24494});
24495
24496cachedProperty(Signature, 'R', function R() {
24497 return this.eddsa.decodePoint(this.Rencoded());
24498});
24499
24500cachedProperty(Signature, 'Rencoded', function Rencoded() {
24501 return this.eddsa.encodePoint(this.R());
24502});
24503
24504cachedProperty(Signature, 'Sencoded', function Sencoded() {
24505 return this.eddsa.encodeInt(this.S());
24506});
24507
24508Signature.prototype.toBytes = function toBytes() {
24509 return this.Rencoded().concat(this.Sencoded());
24510};
24511
24512Signature.prototype.toHex = function toHex() {
24513 return utils.encode(this.toBytes(), 'hex').toUpperCase();
24514};
24515
24516module.exports = Signature;
24517
24518},{"../utils":117,"bn.js":118}],116:[function(require,module,exports){
24519module.exports = {
24520 doubles: {
24521 step: 4,
24522 points: [
24523 [
24524 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
24525 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821',
24526 ],
24527 [
24528 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
24529 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf',
24530 ],
24531 [
24532 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
24533 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695',
24534 ],
24535 [
24536 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
24537 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9',
24538 ],
24539 [
24540 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
24541 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36',
24542 ],
24543 [
24544 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
24545 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f',
24546 ],
24547 [
24548 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
24549 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999',
24550 ],
24551 [
24552 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
24553 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09',
24554 ],
24555 [
24556 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
24557 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d',
24558 ],
24559 [
24560 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
24561 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088',
24562 ],
24563 [
24564 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
24565 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d',
24566 ],
24567 [
24568 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
24569 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8',
24570 ],
24571 [
24572 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
24573 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a',
24574 ],
24575 [
24576 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
24577 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453',
24578 ],
24579 [
24580 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
24581 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160',
24582 ],
24583 [
24584 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
24585 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0',
24586 ],
24587 [
24588 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
24589 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6',
24590 ],
24591 [
24592 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
24593 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589',
24594 ],
24595 [
24596 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
24597 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17',
24598 ],
24599 [
24600 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
24601 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda',
24602 ],
24603 [
24604 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
24605 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd',
24606 ],
24607 [
24608 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
24609 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2',
24610 ],
24611 [
24612 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
24613 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6',
24614 ],
24615 [
24616 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
24617 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f',
24618 ],
24619 [
24620 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
24621 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01',
24622 ],
24623 [
24624 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
24625 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3',
24626 ],
24627 [
24628 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
24629 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f',
24630 ],
24631 [
24632 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
24633 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7',
24634 ],
24635 [
24636 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
24637 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78',
24638 ],
24639 [
24640 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
24641 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1',
24642 ],
24643 [
24644 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
24645 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150',
24646 ],
24647 [
24648 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
24649 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82',
24650 ],
24651 [
24652 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
24653 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc',
24654 ],
24655 [
24656 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
24657 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b',
24658 ],
24659 [
24660 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
24661 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51',
24662 ],
24663 [
24664 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
24665 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45',
24666 ],
24667 [
24668 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
24669 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120',
24670 ],
24671 [
24672 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
24673 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84',
24674 ],
24675 [
24676 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
24677 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d',
24678 ],
24679 [
24680 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
24681 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d',
24682 ],
24683 [
24684 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
24685 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8',
24686 ],
24687 [
24688 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
24689 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8',
24690 ],
24691 [
24692 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
24693 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac',
24694 ],
24695 [
24696 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
24697 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f',
24698 ],
24699 [
24700 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
24701 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962',
24702 ],
24703 [
24704 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
24705 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907',
24706 ],
24707 [
24708 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
24709 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec',
24710 ],
24711 [
24712 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
24713 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d',
24714 ],
24715 [
24716 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
24717 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414',
24718 ],
24719 [
24720 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
24721 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd',
24722 ],
24723 [
24724 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
24725 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0',
24726 ],
24727 [
24728 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
24729 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811',
24730 ],
24731 [
24732 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
24733 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1',
24734 ],
24735 [
24736 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
24737 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c',
24738 ],
24739 [
24740 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
24741 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73',
24742 ],
24743 [
24744 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
24745 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd',
24746 ],
24747 [
24748 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
24749 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405',
24750 ],
24751 [
24752 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
24753 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589',
24754 ],
24755 [
24756 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
24757 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e',
24758 ],
24759 [
24760 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
24761 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27',
24762 ],
24763 [
24764 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
24765 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1',
24766 ],
24767 [
24768 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
24769 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482',
24770 ],
24771 [
24772 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
24773 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945',
24774 ],
24775 [
24776 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
24777 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573',
24778 ],
24779 [
24780 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
24781 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82',
24782 ],
24783 ],
24784 },
24785 naf: {
24786 wnd: 7,
24787 points: [
24788 [
24789 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
24790 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672',
24791 ],
24792 [
24793 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
24794 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6',
24795 ],
24796 [
24797 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
24798 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da',
24799 ],
24800 [
24801 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
24802 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37',
24803 ],
24804 [
24805 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
24806 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b',
24807 ],
24808 [
24809 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
24810 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81',
24811 ],
24812 [
24813 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
24814 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58',
24815 ],
24816 [
24817 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
24818 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77',
24819 ],
24820 [
24821 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
24822 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a',
24823 ],
24824 [
24825 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
24826 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c',
24827 ],
24828 [
24829 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
24830 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67',
24831 ],
24832 [
24833 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
24834 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402',
24835 ],
24836 [
24837 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
24838 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55',
24839 ],
24840 [
24841 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
24842 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482',
24843 ],
24844 [
24845 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
24846 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82',
24847 ],
24848 [
24849 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
24850 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396',
24851 ],
24852 [
24853 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
24854 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49',
24855 ],
24856 [
24857 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
24858 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf',
24859 ],
24860 [
24861 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
24862 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a',
24863 ],
24864 [
24865 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
24866 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7',
24867 ],
24868 [
24869 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
24870 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933',
24871 ],
24872 [
24873 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
24874 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a',
24875 ],
24876 [
24877 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
24878 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6',
24879 ],
24880 [
24881 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
24882 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37',
24883 ],
24884 [
24885 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
24886 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e',
24887 ],
24888 [
24889 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
24890 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6',
24891 ],
24892 [
24893 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
24894 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476',
24895 ],
24896 [
24897 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
24898 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40',
24899 ],
24900 [
24901 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
24902 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61',
24903 ],
24904 [
24905 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
24906 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683',
24907 ],
24908 [
24909 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
24910 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5',
24911 ],
24912 [
24913 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
24914 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b',
24915 ],
24916 [
24917 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
24918 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417',
24919 ],
24920 [
24921 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
24922 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868',
24923 ],
24924 [
24925 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
24926 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a',
24927 ],
24928 [
24929 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
24930 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6',
24931 ],
24932 [
24933 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
24934 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996',
24935 ],
24936 [
24937 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
24938 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e',
24939 ],
24940 [
24941 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
24942 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d',
24943 ],
24944 [
24945 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
24946 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2',
24947 ],
24948 [
24949 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
24950 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e',
24951 ],
24952 [
24953 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
24954 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437',
24955 ],
24956 [
24957 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
24958 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311',
24959 ],
24960 [
24961 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
24962 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4',
24963 ],
24964 [
24965 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
24966 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575',
24967 ],
24968 [
24969 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
24970 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d',
24971 ],
24972 [
24973 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
24974 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d',
24975 ],
24976 [
24977 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
24978 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629',
24979 ],
24980 [
24981 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
24982 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06',
24983 ],
24984 [
24985 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
24986 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374',
24987 ],
24988 [
24989 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
24990 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee',
24991 ],
24992 [
24993 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
24994 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1',
24995 ],
24996 [
24997 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
24998 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b',
24999 ],
25000 [
25001 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
25002 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661',
25003 ],
25004 [
25005 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
25006 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6',
25007 ],
25008 [
25009 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
25010 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e',
25011 ],
25012 [
25013 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
25014 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d',
25015 ],
25016 [
25017 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
25018 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc',
25019 ],
25020 [
25021 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
25022 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4',
25023 ],
25024 [
25025 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
25026 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c',
25027 ],
25028 [
25029 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
25030 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b',
25031 ],
25032 [
25033 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
25034 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913',
25035 ],
25036 [
25037 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
25038 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154',
25039 ],
25040 [
25041 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
25042 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865',
25043 ],
25044 [
25045 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
25046 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc',
25047 ],
25048 [
25049 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
25050 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224',
25051 ],
25052 [
25053 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
25054 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e',
25055 ],
25056 [
25057 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
25058 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6',
25059 ],
25060 [
25061 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
25062 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511',
25063 ],
25064 [
25065 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
25066 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b',
25067 ],
25068 [
25069 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
25070 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2',
25071 ],
25072 [
25073 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
25074 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c',
25075 ],
25076 [
25077 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
25078 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3',
25079 ],
25080 [
25081 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
25082 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d',
25083 ],
25084 [
25085 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
25086 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700',
25087 ],
25088 [
25089 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
25090 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4',
25091 ],
25092 [
25093 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
25094 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196',
25095 ],
25096 [
25097 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
25098 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4',
25099 ],
25100 [
25101 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
25102 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257',
25103 ],
25104 [
25105 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
25106 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13',
25107 ],
25108 [
25109 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
25110 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096',
25111 ],
25112 [
25113 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
25114 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38',
25115 ],
25116 [
25117 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
25118 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f',
25119 ],
25120 [
25121 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
25122 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448',
25123 ],
25124 [
25125 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
25126 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a',
25127 ],
25128 [
25129 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
25130 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4',
25131 ],
25132 [
25133 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
25134 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437',
25135 ],
25136 [
25137 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
25138 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7',
25139 ],
25140 [
25141 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
25142 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d',
25143 ],
25144 [
25145 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
25146 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a',
25147 ],
25148 [
25149 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
25150 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54',
25151 ],
25152 [
25153 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
25154 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77',
25155 ],
25156 [
25157 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
25158 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517',
25159 ],
25160 [
25161 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
25162 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10',
25163 ],
25164 [
25165 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
25166 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125',
25167 ],
25168 [
25169 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
25170 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e',
25171 ],
25172 [
25173 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
25174 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1',
25175 ],
25176 [
25177 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
25178 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2',
25179 ],
25180 [
25181 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
25182 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423',
25183 ],
25184 [
25185 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
25186 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8',
25187 ],
25188 [
25189 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
25190 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758',
25191 ],
25192 [
25193 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
25194 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375',
25195 ],
25196 [
25197 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
25198 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d',
25199 ],
25200 [
25201 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
25202 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec',
25203 ],
25204 [
25205 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
25206 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0',
25207 ],
25208 [
25209 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
25210 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c',
25211 ],
25212 [
25213 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
25214 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4',
25215 ],
25216 [
25217 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
25218 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f',
25219 ],
25220 [
25221 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
25222 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649',
25223 ],
25224 [
25225 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
25226 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826',
25227 ],
25228 [
25229 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
25230 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5',
25231 ],
25232 [
25233 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
25234 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87',
25235 ],
25236 [
25237 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
25238 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b',
25239 ],
25240 [
25241 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
25242 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc',
25243 ],
25244 [
25245 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
25246 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c',
25247 ],
25248 [
25249 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
25250 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f',
25251 ],
25252 [
25253 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
25254 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a',
25255 ],
25256 [
25257 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
25258 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46',
25259 ],
25260 [
25261 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
25262 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f',
25263 ],
25264 [
25265 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
25266 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03',
25267 ],
25268 [
25269 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
25270 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08',
25271 ],
25272 [
25273 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
25274 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8',
25275 ],
25276 [
25277 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
25278 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373',
25279 ],
25280 [
25281 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
25282 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3',
25283 ],
25284 [
25285 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
25286 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8',
25287 ],
25288 [
25289 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
25290 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1',
25291 ],
25292 [
25293 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
25294 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9',
25295 ],
25296 ],
25297 },
25298};
25299
25300},{}],117:[function(require,module,exports){
25301'use strict';
25302
25303var utils = exports;
25304var BN = require('bn.js');
25305var minAssert = require('minimalistic-assert');
25306var minUtils = require('minimalistic-crypto-utils');
25307
25308utils.assert = minAssert;
25309utils.toArray = minUtils.toArray;
25310utils.zero2 = minUtils.zero2;
25311utils.toHex = minUtils.toHex;
25312utils.encode = minUtils.encode;
25313
25314// Represent num in a w-NAF form
25315function getNAF(num, w, bits) {
25316 var naf = new Array(Math.max(num.bitLength(), bits) + 1);
25317 naf.fill(0);
25318
25319 var ws = 1 << (w + 1);
25320 var k = num.clone();
25321
25322 for (var i = 0; i < naf.length; i++) {
25323 var z;
25324 var mod = k.andln(ws - 1);
25325 if (k.isOdd()) {
25326 if (mod > (ws >> 1) - 1)
25327 z = (ws >> 1) - mod;
25328 else
25329 z = mod;
25330 k.isubn(z);
25331 } else {
25332 z = 0;
25333 }
25334
25335 naf[i] = z;
25336 k.iushrn(1);
25337 }
25338
25339 return naf;
25340}
25341utils.getNAF = getNAF;
25342
25343// Represent k1, k2 in a Joint Sparse Form
25344function getJSF(k1, k2) {
25345 var jsf = [
25346 [],
25347 [],
25348 ];
25349
25350 k1 = k1.clone();
25351 k2 = k2.clone();
25352 var d1 = 0;
25353 var d2 = 0;
25354 var m8;
25355 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
25356 // First phase
25357 var m14 = (k1.andln(3) + d1) & 3;
25358 var m24 = (k2.andln(3) + d2) & 3;
25359 if (m14 === 3)
25360 m14 = -1;
25361 if (m24 === 3)
25362 m24 = -1;
25363 var u1;
25364 if ((m14 & 1) === 0) {
25365 u1 = 0;
25366 } else {
25367 m8 = (k1.andln(7) + d1) & 7;
25368 if ((m8 === 3 || m8 === 5) && m24 === 2)
25369 u1 = -m14;
25370 else
25371 u1 = m14;
25372 }
25373 jsf[0].push(u1);
25374
25375 var u2;
25376 if ((m24 & 1) === 0) {
25377 u2 = 0;
25378 } else {
25379 m8 = (k2.andln(7) + d2) & 7;
25380 if ((m8 === 3 || m8 === 5) && m14 === 2)
25381 u2 = -m24;
25382 else
25383 u2 = m24;
25384 }
25385 jsf[1].push(u2);
25386
25387 // Second phase
25388 if (2 * d1 === u1 + 1)
25389 d1 = 1 - d1;
25390 if (2 * d2 === u2 + 1)
25391 d2 = 1 - d2;
25392 k1.iushrn(1);
25393 k2.iushrn(1);
25394 }
25395
25396 return jsf;
25397}
25398utils.getJSF = getJSF;
25399
25400function cachedProperty(obj, name, computer) {
25401 var key = '_' + name;
25402 obj.prototype[name] = function cachedProperty() {
25403 return this[key] !== undefined ? this[key] :
25404 this[key] = computer.call(this);
25405 };
25406}
25407utils.cachedProperty = cachedProperty;
25408
25409function parseBytes(bytes) {
25410 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
25411 bytes;
25412}
25413utils.parseBytes = parseBytes;
25414
25415function intFromLE(bytes) {
25416 return new BN(bytes, 'hex', 'le');
25417}
25418utils.intFromLE = intFromLE;
25419
25420
25421},{"bn.js":118,"minimalistic-assert":159,"minimalistic-crypto-utils":160}],118:[function(require,module,exports){
25422arguments[4][21][0].apply(exports,arguments)
25423},{"buffer":33,"dup":21}],119:[function(require,module,exports){
25424module.exports={
25425 "_from": "elliptic@^6.5.3",
25426 "_id": "elliptic@6.5.4",
25427 "_inBundle": false,
25428 "_integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==",
25429 "_location": "/elliptic",
25430 "_phantomChildren": {},
25431 "_requested": {
25432 "type": "range",
25433 "registry": true,
25434 "raw": "elliptic@^6.5.3",
25435 "name": "elliptic",
25436 "escapedName": "elliptic",
25437 "rawSpec": "^6.5.3",
25438 "saveSpec": null,
25439 "fetchSpec": "^6.5.3"
25440 },
25441 "_requiredBy": [
25442 "/browserify-sign",
25443 "/create-ecdh"
25444 ],
25445 "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz",
25446 "_shasum": "da37cebd31e79a1367e941b592ed1fbebd58abbb",
25447 "_spec": "elliptic@^6.5.3",
25448 "_where": "/home/user/git/blindsecp256k1-js/node_modules/browserify-sign",
25449 "author": {
25450 "name": "Fedor Indutny",
25451 "email": "fedor@indutny.com"
25452 },
25453 "bugs": {
25454 "url": "https://github.com/indutny/elliptic/issues"
25455 },
25456 "bundleDependencies": false,
25457 "dependencies": {
25458 "bn.js": "^4.11.9",
25459 "brorand": "^1.1.0",
25460 "hash.js": "^1.0.0",
25461 "hmac-drbg": "^1.0.1",
25462 "inherits": "^2.0.4",
25463 "minimalistic-assert": "^1.0.1",
25464 "minimalistic-crypto-utils": "^1.0.1"
25465 },
25466 "deprecated": false,
25467 "description": "EC cryptography",
25468 "devDependencies": {
25469 "brfs": "^2.0.2",
25470 "coveralls": "^3.1.0",
25471 "eslint": "^7.6.0",
25472 "grunt": "^1.2.1",
25473 "grunt-browserify": "^5.3.0",
25474 "grunt-cli": "^1.3.2",
25475 "grunt-contrib-connect": "^3.0.0",
25476 "grunt-contrib-copy": "^1.0.0",
25477 "grunt-contrib-uglify": "^5.0.0",
25478 "grunt-mocha-istanbul": "^5.0.2",
25479 "grunt-saucelabs": "^9.0.1",
25480 "istanbul": "^0.4.5",
25481 "mocha": "^8.0.1"
25482 },
25483 "files": [
25484 "lib"
25485 ],
25486 "homepage": "https://github.com/indutny/elliptic",
25487 "keywords": [
25488 "EC",
25489 "Elliptic",
25490 "curve",
25491 "Cryptography"
25492 ],
25493 "license": "MIT",
25494 "main": "lib/elliptic.js",
25495 "name": "elliptic",
25496 "repository": {
25497 "type": "git",
25498 "url": "git+ssh://git@github.com/indutny/elliptic.git"
25499 },
25500 "scripts": {
25501 "lint": "eslint lib test",
25502 "lint:fix": "npm run lint -- --fix",
25503 "test": "npm run lint && npm run unit",
25504 "unit": "istanbul test _mocha --reporter=spec test/index.js",
25505 "version": "grunt dist && git add dist/"
25506 },
25507 "version": "6.5.4"
25508}
25509
25510},{}],120:[function(require,module,exports){
25511// Copyright Joyent, Inc. and other Node contributors.
25512//
25513// Permission is hereby granted, free of charge, to any person obtaining a
25514// copy of this software and associated documentation files (the
25515// "Software"), to deal in the Software without restriction, including
25516// without limitation the rights to use, copy, modify, merge, publish,
25517// distribute, sublicense, and/or sell copies of the Software, and to permit
25518// persons to whom the Software is furnished to do so, subject to the
25519// following conditions:
25520//
25521// The above copyright notice and this permission notice shall be included
25522// in all copies or substantial portions of the Software.
25523//
25524// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
25525// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25526// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
25527// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
25528// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
25529// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25530// USE OR OTHER DEALINGS IN THE SOFTWARE.
25531
25532var objectCreate = Object.create || objectCreatePolyfill
25533var objectKeys = Object.keys || objectKeysPolyfill
25534var bind = Function.prototype.bind || functionBindPolyfill
25535
25536function EventEmitter() {
25537 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
25538 this._events = objectCreate(null);
25539 this._eventsCount = 0;
25540 }
25541
25542 this._maxListeners = this._maxListeners || undefined;
25543}
25544module.exports = EventEmitter;
25545
25546// Backwards-compat with node 0.10.x
25547EventEmitter.EventEmitter = EventEmitter;
25548
25549EventEmitter.prototype._events = undefined;
25550EventEmitter.prototype._maxListeners = undefined;
25551
25552// By default EventEmitters will print a warning if more than 10 listeners are
25553// added to it. This is a useful default which helps finding memory leaks.
25554var defaultMaxListeners = 10;
25555
25556var hasDefineProperty;
25557try {
25558 var o = {};
25559 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
25560 hasDefineProperty = o.x === 0;
25561} catch (err) { hasDefineProperty = false }
25562if (hasDefineProperty) {
25563 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
25564 enumerable: true,
25565 get: function() {
25566 return defaultMaxListeners;
25567 },
25568 set: function(arg) {
25569 // check whether the input is a positive number (whose value is zero or
25570 // greater and not a NaN).
25571 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
25572 throw new TypeError('"defaultMaxListeners" must be a positive number');
25573 defaultMaxListeners = arg;
25574 }
25575 });
25576} else {
25577 EventEmitter.defaultMaxListeners = defaultMaxListeners;
25578}
25579
25580// Obviously not all Emitters should be limited to 10. This function allows
25581// that to be increased. Set to zero for unlimited.
25582EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
25583 if (typeof n !== 'number' || n < 0 || isNaN(n))
25584 throw new TypeError('"n" argument must be a positive number');
25585 this._maxListeners = n;
25586 return this;
25587};
25588
25589function $getMaxListeners(that) {
25590 if (that._maxListeners === undefined)
25591 return EventEmitter.defaultMaxListeners;
25592 return that._maxListeners;
25593}
25594
25595EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
25596 return $getMaxListeners(this);
25597};
25598
25599// These standalone emit* functions are used to optimize calling of event
25600// handlers for fast cases because emit() itself often has a variable number of
25601// arguments and can be deoptimized because of that. These functions always have
25602// the same number of arguments and thus do not get deoptimized, so the code
25603// inside them can execute faster.
25604function emitNone(handler, isFn, self) {
25605 if (isFn)
25606 handler.call(self);
25607 else {
25608 var len = handler.length;
25609 var listeners = arrayClone(handler, len);
25610 for (var i = 0; i < len; ++i)
25611 listeners[i].call(self);
25612 }
25613}
25614function emitOne(handler, isFn, self, arg1) {
25615 if (isFn)
25616 handler.call(self, arg1);
25617 else {
25618 var len = handler.length;
25619 var listeners = arrayClone(handler, len);
25620 for (var i = 0; i < len; ++i)
25621 listeners[i].call(self, arg1);
25622 }
25623}
25624function emitTwo(handler, isFn, self, arg1, arg2) {
25625 if (isFn)
25626 handler.call(self, arg1, arg2);
25627 else {
25628 var len = handler.length;
25629 var listeners = arrayClone(handler, len);
25630 for (var i = 0; i < len; ++i)
25631 listeners[i].call(self, arg1, arg2);
25632 }
25633}
25634function emitThree(handler, isFn, self, arg1, arg2, arg3) {
25635 if (isFn)
25636 handler.call(self, arg1, arg2, arg3);
25637 else {
25638 var len = handler.length;
25639 var listeners = arrayClone(handler, len);
25640 for (var i = 0; i < len; ++i)
25641 listeners[i].call(self, arg1, arg2, arg3);
25642 }
25643}
25644
25645function emitMany(handler, isFn, self, args) {
25646 if (isFn)
25647 handler.apply(self, args);
25648 else {
25649 var len = handler.length;
25650 var listeners = arrayClone(handler, len);
25651 for (var i = 0; i < len; ++i)
25652 listeners[i].apply(self, args);
25653 }
25654}
25655
25656EventEmitter.prototype.emit = function emit(type) {
25657 var er, handler, len, args, i, events;
25658 var doError = (type === 'error');
25659
25660 events = this._events;
25661 if (events)
25662 doError = (doError && events.error == null);
25663 else if (!doError)
25664 return false;
25665
25666 // If there is no 'error' event listener then throw.
25667 if (doError) {
25668 if (arguments.length > 1)
25669 er = arguments[1];
25670 if (er instanceof Error) {
25671 throw er; // Unhandled 'error' event
25672 } else {
25673 // At least give some kind of context to the user
25674 var err = new Error('Unhandled "error" event. (' + er + ')');
25675 err.context = er;
25676 throw err;
25677 }
25678 return false;
25679 }
25680
25681 handler = events[type];
25682
25683 if (!handler)
25684 return false;
25685
25686 var isFn = typeof handler === 'function';
25687 len = arguments.length;
25688 switch (len) {
25689 // fast cases
25690 case 1:
25691 emitNone(handler, isFn, this);
25692 break;
25693 case 2:
25694 emitOne(handler, isFn, this, arguments[1]);
25695 break;
25696 case 3:
25697 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
25698 break;
25699 case 4:
25700 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
25701 break;
25702 // slower
25703 default:
25704 args = new Array(len - 1);
25705 for (i = 1; i < len; i++)
25706 args[i - 1] = arguments[i];
25707 emitMany(handler, isFn, this, args);
25708 }
25709
25710 return true;
25711};
25712
25713function _addListener(target, type, listener, prepend) {
25714 var m;
25715 var events;
25716 var existing;
25717
25718 if (typeof listener !== 'function')
25719 throw new TypeError('"listener" argument must be a function');
25720
25721 events = target._events;
25722 if (!events) {
25723 events = target._events = objectCreate(null);
25724 target._eventsCount = 0;
25725 } else {
25726 // To avoid recursion in the case that type === "newListener"! Before
25727 // adding it to the listeners, first emit "newListener".
25728 if (events.newListener) {
25729 target.emit('newListener', type,
25730 listener.listener ? listener.listener : listener);
25731
25732 // Re-assign `events` because a newListener handler could have caused the
25733 // this._events to be assigned to a new object
25734 events = target._events;
25735 }
25736 existing = events[type];
25737 }
25738
25739 if (!existing) {
25740 // Optimize the case of one listener. Don't need the extra array object.
25741 existing = events[type] = listener;
25742 ++target._eventsCount;
25743 } else {
25744 if (typeof existing === 'function') {
25745 // Adding the second element, need to change to array.
25746 existing = events[type] =
25747 prepend ? [listener, existing] : [existing, listener];
25748 } else {
25749 // If we've already got an array, just append.
25750 if (prepend) {
25751 existing.unshift(listener);
25752 } else {
25753 existing.push(listener);
25754 }
25755 }
25756
25757 // Check for listener leak
25758 if (!existing.warned) {
25759 m = $getMaxListeners(target);
25760 if (m && m > 0 && existing.length > m) {
25761 existing.warned = true;
25762 var w = new Error('Possible EventEmitter memory leak detected. ' +
25763 existing.length + ' "' + String(type) + '" listeners ' +
25764 'added. Use emitter.setMaxListeners() to ' +
25765 'increase limit.');
25766 w.name = 'MaxListenersExceededWarning';
25767 w.emitter = target;
25768 w.type = type;
25769 w.count = existing.length;
25770 if (typeof console === 'object' && console.warn) {
25771 console.warn('%s: %s', w.name, w.message);
25772 }
25773 }
25774 }
25775 }
25776
25777 return target;
25778}
25779
25780EventEmitter.prototype.addListener = function addListener(type, listener) {
25781 return _addListener(this, type, listener, false);
25782};
25783
25784EventEmitter.prototype.on = EventEmitter.prototype.addListener;
25785
25786EventEmitter.prototype.prependListener =
25787 function prependListener(type, listener) {
25788 return _addListener(this, type, listener, true);
25789 };
25790
25791function onceWrapper() {
25792 if (!this.fired) {
25793 this.target.removeListener(this.type, this.wrapFn);
25794 this.fired = true;
25795 switch (arguments.length) {
25796 case 0:
25797 return this.listener.call(this.target);
25798 case 1:
25799 return this.listener.call(this.target, arguments[0]);
25800 case 2:
25801 return this.listener.call(this.target, arguments[0], arguments[1]);
25802 case 3:
25803 return this.listener.call(this.target, arguments[0], arguments[1],
25804 arguments[2]);
25805 default:
25806 var args = new Array(arguments.length);
25807 for (var i = 0; i < args.length; ++i)
25808 args[i] = arguments[i];
25809 this.listener.apply(this.target, args);
25810 }
25811 }
25812}
25813
25814function _onceWrap(target, type, listener) {
25815 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
25816 var wrapped = bind.call(onceWrapper, state);
25817 wrapped.listener = listener;
25818 state.wrapFn = wrapped;
25819 return wrapped;
25820}
25821
25822EventEmitter.prototype.once = function once(type, listener) {
25823 if (typeof listener !== 'function')
25824 throw new TypeError('"listener" argument must be a function');
25825 this.on(type, _onceWrap(this, type, listener));
25826 return this;
25827};
25828
25829EventEmitter.prototype.prependOnceListener =
25830 function prependOnceListener(type, listener) {
25831 if (typeof listener !== 'function')
25832 throw new TypeError('"listener" argument must be a function');
25833 this.prependListener(type, _onceWrap(this, type, listener));
25834 return this;
25835 };
25836
25837// Emits a 'removeListener' event if and only if the listener was removed.
25838EventEmitter.prototype.removeListener =
25839 function removeListener(type, listener) {
25840 var list, events, position, i, originalListener;
25841
25842 if (typeof listener !== 'function')
25843 throw new TypeError('"listener" argument must be a function');
25844
25845 events = this._events;
25846 if (!events)
25847 return this;
25848
25849 list = events[type];
25850 if (!list)
25851 return this;
25852
25853 if (list === listener || list.listener === listener) {
25854 if (--this._eventsCount === 0)
25855 this._events = objectCreate(null);
25856 else {
25857 delete events[type];
25858 if (events.removeListener)
25859 this.emit('removeListener', type, list.listener || listener);
25860 }
25861 } else if (typeof list !== 'function') {
25862 position = -1;
25863
25864 for (i = list.length - 1; i >= 0; i--) {
25865 if (list[i] === listener || list[i].listener === listener) {
25866 originalListener = list[i].listener;
25867 position = i;
25868 break;
25869 }
25870 }
25871
25872 if (position < 0)
25873 return this;
25874
25875 if (position === 0)
25876 list.shift();
25877 else
25878 spliceOne(list, position);
25879
25880 if (list.length === 1)
25881 events[type] = list[0];
25882
25883 if (events.removeListener)
25884 this.emit('removeListener', type, originalListener || listener);
25885 }
25886
25887 return this;
25888 };
25889
25890EventEmitter.prototype.removeAllListeners =
25891 function removeAllListeners(type) {
25892 var listeners, events, i;
25893
25894 events = this._events;
25895 if (!events)
25896 return this;
25897
25898 // not listening for removeListener, no need to emit
25899 if (!events.removeListener) {
25900 if (arguments.length === 0) {
25901 this._events = objectCreate(null);
25902 this._eventsCount = 0;
25903 } else if (events[type]) {
25904 if (--this._eventsCount === 0)
25905 this._events = objectCreate(null);
25906 else
25907 delete events[type];
25908 }
25909 return this;
25910 }
25911
25912 // emit removeListener for all listeners on all events
25913 if (arguments.length === 0) {
25914 var keys = objectKeys(events);
25915 var key;
25916 for (i = 0; i < keys.length; ++i) {
25917 key = keys[i];
25918 if (key === 'removeListener') continue;
25919 this.removeAllListeners(key);
25920 }
25921 this.removeAllListeners('removeListener');
25922 this._events = objectCreate(null);
25923 this._eventsCount = 0;
25924 return this;
25925 }
25926
25927 listeners = events[type];
25928
25929 if (typeof listeners === 'function') {
25930 this.removeListener(type, listeners);
25931 } else if (listeners) {
25932 // LIFO order
25933 for (i = listeners.length - 1; i >= 0; i--) {
25934 this.removeListener(type, listeners[i]);
25935 }
25936 }
25937
25938 return this;
25939 };
25940
25941function _listeners(target, type, unwrap) {
25942 var events = target._events;
25943
25944 if (!events)
25945 return [];
25946
25947 var evlistener = events[type];
25948 if (!evlistener)
25949 return [];
25950
25951 if (typeof evlistener === 'function')
25952 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
25953
25954 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
25955}
25956
25957EventEmitter.prototype.listeners = function listeners(type) {
25958 return _listeners(this, type, true);
25959};
25960
25961EventEmitter.prototype.rawListeners = function rawListeners(type) {
25962 return _listeners(this, type, false);
25963};
25964
25965EventEmitter.listenerCount = function(emitter, type) {
25966 if (typeof emitter.listenerCount === 'function') {
25967 return emitter.listenerCount(type);
25968 } else {
25969 return listenerCount.call(emitter, type);
25970 }
25971};
25972
25973EventEmitter.prototype.listenerCount = listenerCount;
25974function listenerCount(type) {
25975 var events = this._events;
25976
25977 if (events) {
25978 var evlistener = events[type];
25979
25980 if (typeof evlistener === 'function') {
25981 return 1;
25982 } else if (evlistener) {
25983 return evlistener.length;
25984 }
25985 }
25986
25987 return 0;
25988}
25989
25990EventEmitter.prototype.eventNames = function eventNames() {
25991 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
25992};
25993
25994// About 1.5x faster than the two-arg version of Array#splice().
25995function spliceOne(list, index) {
25996 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
25997 list[i] = list[k];
25998 list.pop();
25999}
26000
26001function arrayClone(arr, n) {
26002 var copy = new Array(n);
26003 for (var i = 0; i < n; ++i)
26004 copy[i] = arr[i];
26005 return copy;
26006}
26007
26008function unwrapListeners(arr) {
26009 var ret = new Array(arr.length);
26010 for (var i = 0; i < ret.length; ++i) {
26011 ret[i] = arr[i].listener || arr[i];
26012 }
26013 return ret;
26014}
26015
26016function objectCreatePolyfill(proto) {
26017 var F = function() {};
26018 F.prototype = proto;
26019 return new F;
26020}
26021function objectKeysPolyfill(obj) {
26022 var keys = [];
26023 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
26024 keys.push(k);
26025 }
26026 return k;
26027}
26028function functionBindPolyfill(context) {
26029 var fn = this;
26030 return function () {
26031 return fn.apply(context, arguments);
26032 };
26033}
26034
26035},{}],121:[function(require,module,exports){
26036var Buffer = require('safe-buffer').Buffer
26037var MD5 = require('md5.js')
26038
26039/* eslint-disable camelcase */
26040function EVP_BytesToKey (password, salt, keyBits, ivLen) {
26041 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
26042 if (salt) {
26043 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
26044 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
26045 }
26046
26047 var keyLen = keyBits / 8
26048 var key = Buffer.alloc(keyLen)
26049 var iv = Buffer.alloc(ivLen || 0)
26050 var tmp = Buffer.alloc(0)
26051
26052 while (keyLen > 0 || ivLen > 0) {
26053 var hash = new MD5()
26054 hash.update(tmp)
26055 hash.update(password)
26056 if (salt) hash.update(salt)
26057 tmp = hash.digest()
26058
26059 var used = 0
26060
26061 if (keyLen > 0) {
26062 var keyStart = key.length - keyLen
26063 used = Math.min(keyLen, tmp.length)
26064 tmp.copy(key, keyStart, 0, used)
26065 keyLen -= used
26066 }
26067
26068 if (used < tmp.length && ivLen > 0) {
26069 var ivStart = iv.length - ivLen
26070 var length = Math.min(ivLen, tmp.length - used)
26071 tmp.copy(iv, ivStart, used, used + length)
26072 ivLen -= length
26073 }
26074 }
26075
26076 tmp.fill(0)
26077 return { key: key, iv: iv }
26078}
26079
26080module.exports = EVP_BytesToKey
26081
26082},{"md5.js":156,"safe-buffer":200}],122:[function(require,module,exports){
26083'use strict'
26084var Buffer = require('safe-buffer').Buffer
26085var Transform = require('readable-stream').Transform
26086var inherits = require('inherits')
26087
26088function throwIfNotStringOrBuffer (val, prefix) {
26089 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
26090 throw new TypeError(prefix + ' must be a string or a buffer')
26091 }
26092}
26093
26094function HashBase (blockSize) {
26095 Transform.call(this)
26096
26097 this._block = Buffer.allocUnsafe(blockSize)
26098 this._blockSize = blockSize
26099 this._blockOffset = 0
26100 this._length = [0, 0, 0, 0]
26101
26102 this._finalized = false
26103}
26104
26105inherits(HashBase, Transform)
26106
26107HashBase.prototype._transform = function (chunk, encoding, callback) {
26108 var error = null
26109 try {
26110 this.update(chunk, encoding)
26111 } catch (err) {
26112 error = err
26113 }
26114
26115 callback(error)
26116}
26117
26118HashBase.prototype._flush = function (callback) {
26119 var error = null
26120 try {
26121 this.push(this.digest())
26122 } catch (err) {
26123 error = err
26124 }
26125
26126 callback(error)
26127}
26128
26129HashBase.prototype.update = function (data, encoding) {
26130 throwIfNotStringOrBuffer(data, 'Data')
26131 if (this._finalized) throw new Error('Digest already called')
26132 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
26133
26134 // consume data
26135 var block = this._block
26136 var offset = 0
26137 while (this._blockOffset + data.length - offset >= this._blockSize) {
26138 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
26139 this._update()
26140 this._blockOffset = 0
26141 }
26142 while (offset < data.length) block[this._blockOffset++] = data[offset++]
26143
26144 // update length
26145 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
26146 this._length[j] += carry
26147 carry = (this._length[j] / 0x0100000000) | 0
26148 if (carry > 0) this._length[j] -= 0x0100000000 * carry
26149 }
26150
26151 return this
26152}
26153
26154HashBase.prototype._update = function () {
26155 throw new Error('_update is not implemented')
26156}
26157
26158HashBase.prototype.digest = function (encoding) {
26159 if (this._finalized) throw new Error('Digest already called')
26160 this._finalized = true
26161
26162 var digest = this._digest()
26163 if (encoding !== undefined) digest = digest.toString(encoding)
26164
26165 // reset state
26166 this._block.fill(0)
26167 this._blockOffset = 0
26168 for (var i = 0; i < 4; ++i) this._length[i] = 0
26169
26170 return digest
26171}
26172
26173HashBase.prototype._digest = function () {
26174 throw new Error('_digest is not implemented')
26175}
26176
26177module.exports = HashBase
26178
26179},{"inherits":152,"readable-stream":137,"safe-buffer":200}],123:[function(require,module,exports){
26180arguments[4][61][0].apply(exports,arguments)
26181},{"dup":61}],124:[function(require,module,exports){
26182arguments[4][62][0].apply(exports,arguments)
26183},{"./_stream_readable":126,"./_stream_writable":128,"_process":174,"dup":62,"inherits":152}],125:[function(require,module,exports){
26184arguments[4][63][0].apply(exports,arguments)
26185},{"./_stream_transform":127,"dup":63,"inherits":152}],126:[function(require,module,exports){
26186arguments[4][64][0].apply(exports,arguments)
26187},{"../errors":123,"./_stream_duplex":124,"./internal/streams/async_iterator":129,"./internal/streams/buffer_list":130,"./internal/streams/destroy":131,"./internal/streams/from":133,"./internal/streams/state":135,"./internal/streams/stream":136,"_process":174,"buffer":77,"dup":64,"events":120,"inherits":152,"string_decoder/":211,"util":33}],127:[function(require,module,exports){
26188arguments[4][65][0].apply(exports,arguments)
26189},{"../errors":123,"./_stream_duplex":124,"dup":65,"inherits":152}],128:[function(require,module,exports){
26190arguments[4][66][0].apply(exports,arguments)
26191},{"../errors":123,"./_stream_duplex":124,"./internal/streams/destroy":131,"./internal/streams/state":135,"./internal/streams/stream":136,"_process":174,"buffer":77,"dup":66,"inherits":152,"util-deprecate":213}],129:[function(require,module,exports){
26192arguments[4][67][0].apply(exports,arguments)
26193},{"./end-of-stream":132,"_process":174,"dup":67}],130:[function(require,module,exports){
26194arguments[4][68][0].apply(exports,arguments)
26195},{"buffer":77,"dup":68,"util":33}],131:[function(require,module,exports){
26196arguments[4][69][0].apply(exports,arguments)
26197},{"_process":174,"dup":69}],132:[function(require,module,exports){
26198arguments[4][70][0].apply(exports,arguments)
26199},{"../../../errors":123,"dup":70}],133:[function(require,module,exports){
26200arguments[4][71][0].apply(exports,arguments)
26201},{"dup":71}],134:[function(require,module,exports){
26202arguments[4][72][0].apply(exports,arguments)
26203},{"../../../errors":123,"./end-of-stream":132,"dup":72}],135:[function(require,module,exports){
26204arguments[4][73][0].apply(exports,arguments)
26205},{"../../../errors":123,"dup":73}],136:[function(require,module,exports){
26206arguments[4][74][0].apply(exports,arguments)
26207},{"dup":74,"events":120}],137:[function(require,module,exports){
26208arguments[4][75][0].apply(exports,arguments)
26209},{"./lib/_stream_duplex.js":124,"./lib/_stream_passthrough.js":125,"./lib/_stream_readable.js":126,"./lib/_stream_transform.js":127,"./lib/_stream_writable.js":128,"./lib/internal/streams/end-of-stream.js":132,"./lib/internal/streams/pipeline.js":134,"dup":75}],138:[function(require,module,exports){
26210var hash = exports;
26211
26212hash.utils = require('./hash/utils');
26213hash.common = require('./hash/common');
26214hash.sha = require('./hash/sha');
26215hash.ripemd = require('./hash/ripemd');
26216hash.hmac = require('./hash/hmac');
26217
26218// Proxy hash functions to the main object
26219hash.sha1 = hash.sha.sha1;
26220hash.sha256 = hash.sha.sha256;
26221hash.sha224 = hash.sha.sha224;
26222hash.sha384 = hash.sha.sha384;
26223hash.sha512 = hash.sha.sha512;
26224hash.ripemd160 = hash.ripemd.ripemd160;
26225
26226},{"./hash/common":139,"./hash/hmac":140,"./hash/ripemd":141,"./hash/sha":142,"./hash/utils":149}],139:[function(require,module,exports){
26227'use strict';
26228
26229var utils = require('./utils');
26230var assert = require('minimalistic-assert');
26231
26232function BlockHash() {
26233 this.pending = null;
26234 this.pendingTotal = 0;
26235 this.blockSize = this.constructor.blockSize;
26236 this.outSize = this.constructor.outSize;
26237 this.hmacStrength = this.constructor.hmacStrength;
26238 this.padLength = this.constructor.padLength / 8;
26239 this.endian = 'big';
26240
26241 this._delta8 = this.blockSize / 8;
26242 this._delta32 = this.blockSize / 32;
26243}
26244exports.BlockHash = BlockHash;
26245
26246BlockHash.prototype.update = function update(msg, enc) {
26247 // Convert message to array, pad it, and join into 32bit blocks
26248 msg = utils.toArray(msg, enc);
26249 if (!this.pending)
26250 this.pending = msg;
26251 else
26252 this.pending = this.pending.concat(msg);
26253 this.pendingTotal += msg.length;
26254
26255 // Enough data, try updating
26256 if (this.pending.length >= this._delta8) {
26257 msg = this.pending;
26258
26259 // Process pending data in blocks
26260 var r = msg.length % this._delta8;
26261 this.pending = msg.slice(msg.length - r, msg.length);
26262 if (this.pending.length === 0)
26263 this.pending = null;
26264
26265 msg = utils.join32(msg, 0, msg.length - r, this.endian);
26266 for (var i = 0; i < msg.length; i += this._delta32)
26267 this._update(msg, i, i + this._delta32);
26268 }
26269
26270 return this;
26271};
26272
26273BlockHash.prototype.digest = function digest(enc) {
26274 this.update(this._pad());
26275 assert(this.pending === null);
26276
26277 return this._digest(enc);
26278};
26279
26280BlockHash.prototype._pad = function pad() {
26281 var len = this.pendingTotal;
26282 var bytes = this._delta8;
26283 var k = bytes - ((len + this.padLength) % bytes);
26284 var res = new Array(k + this.padLength);
26285 res[0] = 0x80;
26286 for (var i = 1; i < k; i++)
26287 res[i] = 0;
26288
26289 // Append length
26290 len <<= 3;
26291 if (this.endian === 'big') {
26292 for (var t = 8; t < this.padLength; t++)
26293 res[i++] = 0;
26294
26295 res[i++] = 0;
26296 res[i++] = 0;
26297 res[i++] = 0;
26298 res[i++] = 0;
26299 res[i++] = (len >>> 24) & 0xff;
26300 res[i++] = (len >>> 16) & 0xff;
26301 res[i++] = (len >>> 8) & 0xff;
26302 res[i++] = len & 0xff;
26303 } else {
26304 res[i++] = len & 0xff;
26305 res[i++] = (len >>> 8) & 0xff;
26306 res[i++] = (len >>> 16) & 0xff;
26307 res[i++] = (len >>> 24) & 0xff;
26308 res[i++] = 0;
26309 res[i++] = 0;
26310 res[i++] = 0;
26311 res[i++] = 0;
26312
26313 for (t = 8; t < this.padLength; t++)
26314 res[i++] = 0;
26315 }
26316
26317 return res;
26318};
26319
26320},{"./utils":149,"minimalistic-assert":159}],140:[function(require,module,exports){
26321'use strict';
26322
26323var utils = require('./utils');
26324var assert = require('minimalistic-assert');
26325
26326function Hmac(hash, key, enc) {
26327 if (!(this instanceof Hmac))
26328 return new Hmac(hash, key, enc);
26329 this.Hash = hash;
26330 this.blockSize = hash.blockSize / 8;
26331 this.outSize = hash.outSize / 8;
26332 this.inner = null;
26333 this.outer = null;
26334
26335 this._init(utils.toArray(key, enc));
26336}
26337module.exports = Hmac;
26338
26339Hmac.prototype._init = function init(key) {
26340 // Shorten key, if needed
26341 if (key.length > this.blockSize)
26342 key = new this.Hash().update(key).digest();
26343 assert(key.length <= this.blockSize);
26344
26345 // Add padding to key
26346 for (var i = key.length; i < this.blockSize; i++)
26347 key.push(0);
26348
26349 for (i = 0; i < key.length; i++)
26350 key[i] ^= 0x36;
26351 this.inner = new this.Hash().update(key);
26352
26353 // 0x36 ^ 0x5c = 0x6a
26354 for (i = 0; i < key.length; i++)
26355 key[i] ^= 0x6a;
26356 this.outer = new this.Hash().update(key);
26357};
26358
26359Hmac.prototype.update = function update(msg, enc) {
26360 this.inner.update(msg, enc);
26361 return this;
26362};
26363
26364Hmac.prototype.digest = function digest(enc) {
26365 this.outer.update(this.inner.digest());
26366 return this.outer.digest(enc);
26367};
26368
26369},{"./utils":149,"minimalistic-assert":159}],141:[function(require,module,exports){
26370'use strict';
26371
26372var utils = require('./utils');
26373var common = require('./common');
26374
26375var rotl32 = utils.rotl32;
26376var sum32 = utils.sum32;
26377var sum32_3 = utils.sum32_3;
26378var sum32_4 = utils.sum32_4;
26379var BlockHash = common.BlockHash;
26380
26381function RIPEMD160() {
26382 if (!(this instanceof RIPEMD160))
26383 return new RIPEMD160();
26384
26385 BlockHash.call(this);
26386
26387 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
26388 this.endian = 'little';
26389}
26390utils.inherits(RIPEMD160, BlockHash);
26391exports.ripemd160 = RIPEMD160;
26392
26393RIPEMD160.blockSize = 512;
26394RIPEMD160.outSize = 160;
26395RIPEMD160.hmacStrength = 192;
26396RIPEMD160.padLength = 64;
26397
26398RIPEMD160.prototype._update = function update(msg, start) {
26399 var A = this.h[0];
26400 var B = this.h[1];
26401 var C = this.h[2];
26402 var D = this.h[3];
26403 var E = this.h[4];
26404 var Ah = A;
26405 var Bh = B;
26406 var Ch = C;
26407 var Dh = D;
26408 var Eh = E;
26409 for (var j = 0; j < 80; j++) {
26410 var T = sum32(
26411 rotl32(
26412 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
26413 s[j]),
26414 E);
26415 A = E;
26416 E = D;
26417 D = rotl32(C, 10);
26418 C = B;
26419 B = T;
26420 T = sum32(
26421 rotl32(
26422 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
26423 sh[j]),
26424 Eh);
26425 Ah = Eh;
26426 Eh = Dh;
26427 Dh = rotl32(Ch, 10);
26428 Ch = Bh;
26429 Bh = T;
26430 }
26431 T = sum32_3(this.h[1], C, Dh);
26432 this.h[1] = sum32_3(this.h[2], D, Eh);
26433 this.h[2] = sum32_3(this.h[3], E, Ah);
26434 this.h[3] = sum32_3(this.h[4], A, Bh);
26435 this.h[4] = sum32_3(this.h[0], B, Ch);
26436 this.h[0] = T;
26437};
26438
26439RIPEMD160.prototype._digest = function digest(enc) {
26440 if (enc === 'hex')
26441 return utils.toHex32(this.h, 'little');
26442 else
26443 return utils.split32(this.h, 'little');
26444};
26445
26446function f(j, x, y, z) {
26447 if (j <= 15)
26448 return x ^ y ^ z;
26449 else if (j <= 31)
26450 return (x & y) | ((~x) & z);
26451 else if (j <= 47)
26452 return (x | (~y)) ^ z;
26453 else if (j <= 63)
26454 return (x & z) | (y & (~z));
26455 else
26456 return x ^ (y | (~z));
26457}
26458
26459function K(j) {
26460 if (j <= 15)
26461 return 0x00000000;
26462 else if (j <= 31)
26463 return 0x5a827999;
26464 else if (j <= 47)
26465 return 0x6ed9eba1;
26466 else if (j <= 63)
26467 return 0x8f1bbcdc;
26468 else
26469 return 0xa953fd4e;
26470}
26471
26472function Kh(j) {
26473 if (j <= 15)
26474 return 0x50a28be6;
26475 else if (j <= 31)
26476 return 0x5c4dd124;
26477 else if (j <= 47)
26478 return 0x6d703ef3;
26479 else if (j <= 63)
26480 return 0x7a6d76e9;
26481 else
26482 return 0x00000000;
26483}
26484
26485var r = [
26486 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
26487 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
26488 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
26489 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
26490 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
26491];
26492
26493var rh = [
26494 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
26495 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
26496 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
26497 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
26498 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
26499];
26500
26501var s = [
26502 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
26503 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
26504 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
26505 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
26506 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
26507];
26508
26509var sh = [
26510 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
26511 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
26512 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
26513 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
26514 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
26515];
26516
26517},{"./common":139,"./utils":149}],142:[function(require,module,exports){
26518'use strict';
26519
26520exports.sha1 = require('./sha/1');
26521exports.sha224 = require('./sha/224');
26522exports.sha256 = require('./sha/256');
26523exports.sha384 = require('./sha/384');
26524exports.sha512 = require('./sha/512');
26525
26526},{"./sha/1":143,"./sha/224":144,"./sha/256":145,"./sha/384":146,"./sha/512":147}],143:[function(require,module,exports){
26527'use strict';
26528
26529var utils = require('../utils');
26530var common = require('../common');
26531var shaCommon = require('./common');
26532
26533var rotl32 = utils.rotl32;
26534var sum32 = utils.sum32;
26535var sum32_5 = utils.sum32_5;
26536var ft_1 = shaCommon.ft_1;
26537var BlockHash = common.BlockHash;
26538
26539var sha1_K = [
26540 0x5A827999, 0x6ED9EBA1,
26541 0x8F1BBCDC, 0xCA62C1D6
26542];
26543
26544function SHA1() {
26545 if (!(this instanceof SHA1))
26546 return new SHA1();
26547
26548 BlockHash.call(this);
26549 this.h = [
26550 0x67452301, 0xefcdab89, 0x98badcfe,
26551 0x10325476, 0xc3d2e1f0 ];
26552 this.W = new Array(80);
26553}
26554
26555utils.inherits(SHA1, BlockHash);
26556module.exports = SHA1;
26557
26558SHA1.blockSize = 512;
26559SHA1.outSize = 160;
26560SHA1.hmacStrength = 80;
26561SHA1.padLength = 64;
26562
26563SHA1.prototype._update = function _update(msg, start) {
26564 var W = this.W;
26565
26566 for (var i = 0; i < 16; i++)
26567 W[i] = msg[start + i];
26568
26569 for(; i < W.length; i++)
26570 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
26571
26572 var a = this.h[0];
26573 var b = this.h[1];
26574 var c = this.h[2];
26575 var d = this.h[3];
26576 var e = this.h[4];
26577
26578 for (i = 0; i < W.length; i++) {
26579 var s = ~~(i / 20);
26580 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
26581 e = d;
26582 d = c;
26583 c = rotl32(b, 30);
26584 b = a;
26585 a = t;
26586 }
26587
26588 this.h[0] = sum32(this.h[0], a);
26589 this.h[1] = sum32(this.h[1], b);
26590 this.h[2] = sum32(this.h[2], c);
26591 this.h[3] = sum32(this.h[3], d);
26592 this.h[4] = sum32(this.h[4], e);
26593};
26594
26595SHA1.prototype._digest = function digest(enc) {
26596 if (enc === 'hex')
26597 return utils.toHex32(this.h, 'big');
26598 else
26599 return utils.split32(this.h, 'big');
26600};
26601
26602},{"../common":139,"../utils":149,"./common":148}],144:[function(require,module,exports){
26603'use strict';
26604
26605var utils = require('../utils');
26606var SHA256 = require('./256');
26607
26608function SHA224() {
26609 if (!(this instanceof SHA224))
26610 return new SHA224();
26611
26612 SHA256.call(this);
26613 this.h = [
26614 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
26615 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
26616}
26617utils.inherits(SHA224, SHA256);
26618module.exports = SHA224;
26619
26620SHA224.blockSize = 512;
26621SHA224.outSize = 224;
26622SHA224.hmacStrength = 192;
26623SHA224.padLength = 64;
26624
26625SHA224.prototype._digest = function digest(enc) {
26626 // Just truncate output
26627 if (enc === 'hex')
26628 return utils.toHex32(this.h.slice(0, 7), 'big');
26629 else
26630 return utils.split32(this.h.slice(0, 7), 'big');
26631};
26632
26633
26634},{"../utils":149,"./256":145}],145:[function(require,module,exports){
26635'use strict';
26636
26637var utils = require('../utils');
26638var common = require('../common');
26639var shaCommon = require('./common');
26640var assert = require('minimalistic-assert');
26641
26642var sum32 = utils.sum32;
26643var sum32_4 = utils.sum32_4;
26644var sum32_5 = utils.sum32_5;
26645var ch32 = shaCommon.ch32;
26646var maj32 = shaCommon.maj32;
26647var s0_256 = shaCommon.s0_256;
26648var s1_256 = shaCommon.s1_256;
26649var g0_256 = shaCommon.g0_256;
26650var g1_256 = shaCommon.g1_256;
26651
26652var BlockHash = common.BlockHash;
26653
26654var sha256_K = [
26655 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
26656 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
26657 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
26658 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
26659 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
26660 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
26661 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
26662 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
26663 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
26664 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
26665 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
26666 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
26667 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
26668 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
26669 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
26670 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
26671];
26672
26673function SHA256() {
26674 if (!(this instanceof SHA256))
26675 return new SHA256();
26676
26677 BlockHash.call(this);
26678 this.h = [
26679 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
26680 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
26681 ];
26682 this.k = sha256_K;
26683 this.W = new Array(64);
26684}
26685utils.inherits(SHA256, BlockHash);
26686module.exports = SHA256;
26687
26688SHA256.blockSize = 512;
26689SHA256.outSize = 256;
26690SHA256.hmacStrength = 192;
26691SHA256.padLength = 64;
26692
26693SHA256.prototype._update = function _update(msg, start) {
26694 var W = this.W;
26695
26696 for (var i = 0; i < 16; i++)
26697 W[i] = msg[start + i];
26698 for (; i < W.length; i++)
26699 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
26700
26701 var a = this.h[0];
26702 var b = this.h[1];
26703 var c = this.h[2];
26704 var d = this.h[3];
26705 var e = this.h[4];
26706 var f = this.h[5];
26707 var g = this.h[6];
26708 var h = this.h[7];
26709
26710 assert(this.k.length === W.length);
26711 for (i = 0; i < W.length; i++) {
26712 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
26713 var T2 = sum32(s0_256(a), maj32(a, b, c));
26714 h = g;
26715 g = f;
26716 f = e;
26717 e = sum32(d, T1);
26718 d = c;
26719 c = b;
26720 b = a;
26721 a = sum32(T1, T2);
26722 }
26723
26724 this.h[0] = sum32(this.h[0], a);
26725 this.h[1] = sum32(this.h[1], b);
26726 this.h[2] = sum32(this.h[2], c);
26727 this.h[3] = sum32(this.h[3], d);
26728 this.h[4] = sum32(this.h[4], e);
26729 this.h[5] = sum32(this.h[5], f);
26730 this.h[6] = sum32(this.h[6], g);
26731 this.h[7] = sum32(this.h[7], h);
26732};
26733
26734SHA256.prototype._digest = function digest(enc) {
26735 if (enc === 'hex')
26736 return utils.toHex32(this.h, 'big');
26737 else
26738 return utils.split32(this.h, 'big');
26739};
26740
26741},{"../common":139,"../utils":149,"./common":148,"minimalistic-assert":159}],146:[function(require,module,exports){
26742'use strict';
26743
26744var utils = require('../utils');
26745
26746var SHA512 = require('./512');
26747
26748function SHA384() {
26749 if (!(this instanceof SHA384))
26750 return new SHA384();
26751
26752 SHA512.call(this);
26753 this.h = [
26754 0xcbbb9d5d, 0xc1059ed8,
26755 0x629a292a, 0x367cd507,
26756 0x9159015a, 0x3070dd17,
26757 0x152fecd8, 0xf70e5939,
26758 0x67332667, 0xffc00b31,
26759 0x8eb44a87, 0x68581511,
26760 0xdb0c2e0d, 0x64f98fa7,
26761 0x47b5481d, 0xbefa4fa4 ];
26762}
26763utils.inherits(SHA384, SHA512);
26764module.exports = SHA384;
26765
26766SHA384.blockSize = 1024;
26767SHA384.outSize = 384;
26768SHA384.hmacStrength = 192;
26769SHA384.padLength = 128;
26770
26771SHA384.prototype._digest = function digest(enc) {
26772 if (enc === 'hex')
26773 return utils.toHex32(this.h.slice(0, 12), 'big');
26774 else
26775 return utils.split32(this.h.slice(0, 12), 'big');
26776};
26777
26778},{"../utils":149,"./512":147}],147:[function(require,module,exports){
26779'use strict';
26780
26781var utils = require('../utils');
26782var common = require('../common');
26783var assert = require('minimalistic-assert');
26784
26785var rotr64_hi = utils.rotr64_hi;
26786var rotr64_lo = utils.rotr64_lo;
26787var shr64_hi = utils.shr64_hi;
26788var shr64_lo = utils.shr64_lo;
26789var sum64 = utils.sum64;
26790var sum64_hi = utils.sum64_hi;
26791var sum64_lo = utils.sum64_lo;
26792var sum64_4_hi = utils.sum64_4_hi;
26793var sum64_4_lo = utils.sum64_4_lo;
26794var sum64_5_hi = utils.sum64_5_hi;
26795var sum64_5_lo = utils.sum64_5_lo;
26796
26797var BlockHash = common.BlockHash;
26798
26799var sha512_K = [
26800 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
26801 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
26802 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
26803 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
26804 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
26805 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
26806 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
26807 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
26808 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
26809 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
26810 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
26811 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
26812 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
26813 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
26814 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
26815 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
26816 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
26817 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
26818 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
26819 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
26820 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
26821 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
26822 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
26823 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
26824 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
26825 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
26826 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
26827 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
26828 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
26829 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
26830 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
26831 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
26832 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
26833 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
26834 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
26835 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
26836 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
26837 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
26838 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
26839 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
26840];
26841
26842function SHA512() {
26843 if (!(this instanceof SHA512))
26844 return new SHA512();
26845
26846 BlockHash.call(this);
26847 this.h = [
26848 0x6a09e667, 0xf3bcc908,
26849 0xbb67ae85, 0x84caa73b,
26850 0x3c6ef372, 0xfe94f82b,
26851 0xa54ff53a, 0x5f1d36f1,
26852 0x510e527f, 0xade682d1,
26853 0x9b05688c, 0x2b3e6c1f,
26854 0x1f83d9ab, 0xfb41bd6b,
26855 0x5be0cd19, 0x137e2179 ];
26856 this.k = sha512_K;
26857 this.W = new Array(160);
26858}
26859utils.inherits(SHA512, BlockHash);
26860module.exports = SHA512;
26861
26862SHA512.blockSize = 1024;
26863SHA512.outSize = 512;
26864SHA512.hmacStrength = 192;
26865SHA512.padLength = 128;
26866
26867SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
26868 var W = this.W;
26869
26870 // 32 x 32bit words
26871 for (var i = 0; i < 32; i++)
26872 W[i] = msg[start + i];
26873 for (; i < W.length; i += 2) {
26874 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
26875 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
26876 var c1_hi = W[i - 14]; // i - 7
26877 var c1_lo = W[i - 13];
26878 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
26879 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
26880 var c3_hi = W[i - 32]; // i - 16
26881 var c3_lo = W[i - 31];
26882
26883 W[i] = sum64_4_hi(
26884 c0_hi, c0_lo,
26885 c1_hi, c1_lo,
26886 c2_hi, c2_lo,
26887 c3_hi, c3_lo);
26888 W[i + 1] = sum64_4_lo(
26889 c0_hi, c0_lo,
26890 c1_hi, c1_lo,
26891 c2_hi, c2_lo,
26892 c3_hi, c3_lo);
26893 }
26894};
26895
26896SHA512.prototype._update = function _update(msg, start) {
26897 this._prepareBlock(msg, start);
26898
26899 var W = this.W;
26900
26901 var ah = this.h[0];
26902 var al = this.h[1];
26903 var bh = this.h[2];
26904 var bl = this.h[3];
26905 var ch = this.h[4];
26906 var cl = this.h[5];
26907 var dh = this.h[6];
26908 var dl = this.h[7];
26909 var eh = this.h[8];
26910 var el = this.h[9];
26911 var fh = this.h[10];
26912 var fl = this.h[11];
26913 var gh = this.h[12];
26914 var gl = this.h[13];
26915 var hh = this.h[14];
26916 var hl = this.h[15];
26917
26918 assert(this.k.length === W.length);
26919 for (var i = 0; i < W.length; i += 2) {
26920 var c0_hi = hh;
26921 var c0_lo = hl;
26922 var c1_hi = s1_512_hi(eh, el);
26923 var c1_lo = s1_512_lo(eh, el);
26924 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
26925 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
26926 var c3_hi = this.k[i];
26927 var c3_lo = this.k[i + 1];
26928 var c4_hi = W[i];
26929 var c4_lo = W[i + 1];
26930
26931 var T1_hi = sum64_5_hi(
26932 c0_hi, c0_lo,
26933 c1_hi, c1_lo,
26934 c2_hi, c2_lo,
26935 c3_hi, c3_lo,
26936 c4_hi, c4_lo);
26937 var T1_lo = sum64_5_lo(
26938 c0_hi, c0_lo,
26939 c1_hi, c1_lo,
26940 c2_hi, c2_lo,
26941 c3_hi, c3_lo,
26942 c4_hi, c4_lo);
26943
26944 c0_hi = s0_512_hi(ah, al);
26945 c0_lo = s0_512_lo(ah, al);
26946 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
26947 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
26948
26949 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
26950 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
26951
26952 hh = gh;
26953 hl = gl;
26954
26955 gh = fh;
26956 gl = fl;
26957
26958 fh = eh;
26959 fl = el;
26960
26961 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
26962 el = sum64_lo(dl, dl, T1_hi, T1_lo);
26963
26964 dh = ch;
26965 dl = cl;
26966
26967 ch = bh;
26968 cl = bl;
26969
26970 bh = ah;
26971 bl = al;
26972
26973 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
26974 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
26975 }
26976
26977 sum64(this.h, 0, ah, al);
26978 sum64(this.h, 2, bh, bl);
26979 sum64(this.h, 4, ch, cl);
26980 sum64(this.h, 6, dh, dl);
26981 sum64(this.h, 8, eh, el);
26982 sum64(this.h, 10, fh, fl);
26983 sum64(this.h, 12, gh, gl);
26984 sum64(this.h, 14, hh, hl);
26985};
26986
26987SHA512.prototype._digest = function digest(enc) {
26988 if (enc === 'hex')
26989 return utils.toHex32(this.h, 'big');
26990 else
26991 return utils.split32(this.h, 'big');
26992};
26993
26994function ch64_hi(xh, xl, yh, yl, zh) {
26995 var r = (xh & yh) ^ ((~xh) & zh);
26996 if (r < 0)
26997 r += 0x100000000;
26998 return r;
26999}
27000
27001function ch64_lo(xh, xl, yh, yl, zh, zl) {
27002 var r = (xl & yl) ^ ((~xl) & zl);
27003 if (r < 0)
27004 r += 0x100000000;
27005 return r;
27006}
27007
27008function maj64_hi(xh, xl, yh, yl, zh) {
27009 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
27010 if (r < 0)
27011 r += 0x100000000;
27012 return r;
27013}
27014
27015function maj64_lo(xh, xl, yh, yl, zh, zl) {
27016 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
27017 if (r < 0)
27018 r += 0x100000000;
27019 return r;
27020}
27021
27022function s0_512_hi(xh, xl) {
27023 var c0_hi = rotr64_hi(xh, xl, 28);
27024 var c1_hi = rotr64_hi(xl, xh, 2); // 34
27025 var c2_hi = rotr64_hi(xl, xh, 7); // 39
27026
27027 var r = c0_hi ^ c1_hi ^ c2_hi;
27028 if (r < 0)
27029 r += 0x100000000;
27030 return r;
27031}
27032
27033function s0_512_lo(xh, xl) {
27034 var c0_lo = rotr64_lo(xh, xl, 28);
27035 var c1_lo = rotr64_lo(xl, xh, 2); // 34
27036 var c2_lo = rotr64_lo(xl, xh, 7); // 39
27037
27038 var r = c0_lo ^ c1_lo ^ c2_lo;
27039 if (r < 0)
27040 r += 0x100000000;
27041 return r;
27042}
27043
27044function s1_512_hi(xh, xl) {
27045 var c0_hi = rotr64_hi(xh, xl, 14);
27046 var c1_hi = rotr64_hi(xh, xl, 18);
27047 var c2_hi = rotr64_hi(xl, xh, 9); // 41
27048
27049 var r = c0_hi ^ c1_hi ^ c2_hi;
27050 if (r < 0)
27051 r += 0x100000000;
27052 return r;
27053}
27054
27055function s1_512_lo(xh, xl) {
27056 var c0_lo = rotr64_lo(xh, xl, 14);
27057 var c1_lo = rotr64_lo(xh, xl, 18);
27058 var c2_lo = rotr64_lo(xl, xh, 9); // 41
27059
27060 var r = c0_lo ^ c1_lo ^ c2_lo;
27061 if (r < 0)
27062 r += 0x100000000;
27063 return r;
27064}
27065
27066function g0_512_hi(xh, xl) {
27067 var c0_hi = rotr64_hi(xh, xl, 1);
27068 var c1_hi = rotr64_hi(xh, xl, 8);
27069 var c2_hi = shr64_hi(xh, xl, 7);
27070
27071 var r = c0_hi ^ c1_hi ^ c2_hi;
27072 if (r < 0)
27073 r += 0x100000000;
27074 return r;
27075}
27076
27077function g0_512_lo(xh, xl) {
27078 var c0_lo = rotr64_lo(xh, xl, 1);
27079 var c1_lo = rotr64_lo(xh, xl, 8);
27080 var c2_lo = shr64_lo(xh, xl, 7);
27081
27082 var r = c0_lo ^ c1_lo ^ c2_lo;
27083 if (r < 0)
27084 r += 0x100000000;
27085 return r;
27086}
27087
27088function g1_512_hi(xh, xl) {
27089 var c0_hi = rotr64_hi(xh, xl, 19);
27090 var c1_hi = rotr64_hi(xl, xh, 29); // 61
27091 var c2_hi = shr64_hi(xh, xl, 6);
27092
27093 var r = c0_hi ^ c1_hi ^ c2_hi;
27094 if (r < 0)
27095 r += 0x100000000;
27096 return r;
27097}
27098
27099function g1_512_lo(xh, xl) {
27100 var c0_lo = rotr64_lo(xh, xl, 19);
27101 var c1_lo = rotr64_lo(xl, xh, 29); // 61
27102 var c2_lo = shr64_lo(xh, xl, 6);
27103
27104 var r = c0_lo ^ c1_lo ^ c2_lo;
27105 if (r < 0)
27106 r += 0x100000000;
27107 return r;
27108}
27109
27110},{"../common":139,"../utils":149,"minimalistic-assert":159}],148:[function(require,module,exports){
27111'use strict';
27112
27113var utils = require('../utils');
27114var rotr32 = utils.rotr32;
27115
27116function ft_1(s, x, y, z) {
27117 if (s === 0)
27118 return ch32(x, y, z);
27119 if (s === 1 || s === 3)
27120 return p32(x, y, z);
27121 if (s === 2)
27122 return maj32(x, y, z);
27123}
27124exports.ft_1 = ft_1;
27125
27126function ch32(x, y, z) {
27127 return (x & y) ^ ((~x) & z);
27128}
27129exports.ch32 = ch32;
27130
27131function maj32(x, y, z) {
27132 return (x & y) ^ (x & z) ^ (y & z);
27133}
27134exports.maj32 = maj32;
27135
27136function p32(x, y, z) {
27137 return x ^ y ^ z;
27138}
27139exports.p32 = p32;
27140
27141function s0_256(x) {
27142 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
27143}
27144exports.s0_256 = s0_256;
27145
27146function s1_256(x) {
27147 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
27148}
27149exports.s1_256 = s1_256;
27150
27151function g0_256(x) {
27152 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
27153}
27154exports.g0_256 = g0_256;
27155
27156function g1_256(x) {
27157 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
27158}
27159exports.g1_256 = g1_256;
27160
27161},{"../utils":149}],149:[function(require,module,exports){
27162'use strict';
27163
27164var assert = require('minimalistic-assert');
27165var inherits = require('inherits');
27166
27167exports.inherits = inherits;
27168
27169function isSurrogatePair(msg, i) {
27170 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
27171 return false;
27172 }
27173 if (i < 0 || i + 1 >= msg.length) {
27174 return false;
27175 }
27176 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
27177}
27178
27179function toArray(msg, enc) {
27180 if (Array.isArray(msg))
27181 return msg.slice();
27182 if (!msg)
27183 return [];
27184 var res = [];
27185 if (typeof msg === 'string') {
27186 if (!enc) {
27187 // Inspired by stringToUtf8ByteArray() in closure-library by Google
27188 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
27189 // Apache License 2.0
27190 // https://github.com/google/closure-library/blob/master/LICENSE
27191 var p = 0;
27192 for (var i = 0; i < msg.length; i++) {
27193 var c = msg.charCodeAt(i);
27194 if (c < 128) {
27195 res[p++] = c;
27196 } else if (c < 2048) {
27197 res[p++] = (c >> 6) | 192;
27198 res[p++] = (c & 63) | 128;
27199 } else if (isSurrogatePair(msg, i)) {
27200 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
27201 res[p++] = (c >> 18) | 240;
27202 res[p++] = ((c >> 12) & 63) | 128;
27203 res[p++] = ((c >> 6) & 63) | 128;
27204 res[p++] = (c & 63) | 128;
27205 } else {
27206 res[p++] = (c >> 12) | 224;
27207 res[p++] = ((c >> 6) & 63) | 128;
27208 res[p++] = (c & 63) | 128;
27209 }
27210 }
27211 } else if (enc === 'hex') {
27212 msg = msg.replace(/[^a-z0-9]+/ig, '');
27213 if (msg.length % 2 !== 0)
27214 msg = '0' + msg;
27215 for (i = 0; i < msg.length; i += 2)
27216 res.push(parseInt(msg[i] + msg[i + 1], 16));
27217 }
27218 } else {
27219 for (i = 0; i < msg.length; i++)
27220 res[i] = msg[i] | 0;
27221 }
27222 return res;
27223}
27224exports.toArray = toArray;
27225
27226function toHex(msg) {
27227 var res = '';
27228 for (var i = 0; i < msg.length; i++)
27229 res += zero2(msg[i].toString(16));
27230 return res;
27231}
27232exports.toHex = toHex;
27233
27234function htonl(w) {
27235 var res = (w >>> 24) |
27236 ((w >>> 8) & 0xff00) |
27237 ((w << 8) & 0xff0000) |
27238 ((w & 0xff) << 24);
27239 return res >>> 0;
27240}
27241exports.htonl = htonl;
27242
27243function toHex32(msg, endian) {
27244 var res = '';
27245 for (var i = 0; i < msg.length; i++) {
27246 var w = msg[i];
27247 if (endian === 'little')
27248 w = htonl(w);
27249 res += zero8(w.toString(16));
27250 }
27251 return res;
27252}
27253exports.toHex32 = toHex32;
27254
27255function zero2(word) {
27256 if (word.length === 1)
27257 return '0' + word;
27258 else
27259 return word;
27260}
27261exports.zero2 = zero2;
27262
27263function zero8(word) {
27264 if (word.length === 7)
27265 return '0' + word;
27266 else if (word.length === 6)
27267 return '00' + word;
27268 else if (word.length === 5)
27269 return '000' + word;
27270 else if (word.length === 4)
27271 return '0000' + word;
27272 else if (word.length === 3)
27273 return '00000' + word;
27274 else if (word.length === 2)
27275 return '000000' + word;
27276 else if (word.length === 1)
27277 return '0000000' + word;
27278 else
27279 return word;
27280}
27281exports.zero8 = zero8;
27282
27283function join32(msg, start, end, endian) {
27284 var len = end - start;
27285 assert(len % 4 === 0);
27286 var res = new Array(len / 4);
27287 for (var i = 0, k = start; i < res.length; i++, k += 4) {
27288 var w;
27289 if (endian === 'big')
27290 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
27291 else
27292 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
27293 res[i] = w >>> 0;
27294 }
27295 return res;
27296}
27297exports.join32 = join32;
27298
27299function split32(msg, endian) {
27300 var res = new Array(msg.length * 4);
27301 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
27302 var m = msg[i];
27303 if (endian === 'big') {
27304 res[k] = m >>> 24;
27305 res[k + 1] = (m >>> 16) & 0xff;
27306 res[k + 2] = (m >>> 8) & 0xff;
27307 res[k + 3] = m & 0xff;
27308 } else {
27309 res[k + 3] = m >>> 24;
27310 res[k + 2] = (m >>> 16) & 0xff;
27311 res[k + 1] = (m >>> 8) & 0xff;
27312 res[k] = m & 0xff;
27313 }
27314 }
27315 return res;
27316}
27317exports.split32 = split32;
27318
27319function rotr32(w, b) {
27320 return (w >>> b) | (w << (32 - b));
27321}
27322exports.rotr32 = rotr32;
27323
27324function rotl32(w, b) {
27325 return (w << b) | (w >>> (32 - b));
27326}
27327exports.rotl32 = rotl32;
27328
27329function sum32(a, b) {
27330 return (a + b) >>> 0;
27331}
27332exports.sum32 = sum32;
27333
27334function sum32_3(a, b, c) {
27335 return (a + b + c) >>> 0;
27336}
27337exports.sum32_3 = sum32_3;
27338
27339function sum32_4(a, b, c, d) {
27340 return (a + b + c + d) >>> 0;
27341}
27342exports.sum32_4 = sum32_4;
27343
27344function sum32_5(a, b, c, d, e) {
27345 return (a + b + c + d + e) >>> 0;
27346}
27347exports.sum32_5 = sum32_5;
27348
27349function sum64(buf, pos, ah, al) {
27350 var bh = buf[pos];
27351 var bl = buf[pos + 1];
27352
27353 var lo = (al + bl) >>> 0;
27354 var hi = (lo < al ? 1 : 0) + ah + bh;
27355 buf[pos] = hi >>> 0;
27356 buf[pos + 1] = lo;
27357}
27358exports.sum64 = sum64;
27359
27360function sum64_hi(ah, al, bh, bl) {
27361 var lo = (al + bl) >>> 0;
27362 var hi = (lo < al ? 1 : 0) + ah + bh;
27363 return hi >>> 0;
27364}
27365exports.sum64_hi = sum64_hi;
27366
27367function sum64_lo(ah, al, bh, bl) {
27368 var lo = al + bl;
27369 return lo >>> 0;
27370}
27371exports.sum64_lo = sum64_lo;
27372
27373function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
27374 var carry = 0;
27375 var lo = al;
27376 lo = (lo + bl) >>> 0;
27377 carry += lo < al ? 1 : 0;
27378 lo = (lo + cl) >>> 0;
27379 carry += lo < cl ? 1 : 0;
27380 lo = (lo + dl) >>> 0;
27381 carry += lo < dl ? 1 : 0;
27382
27383 var hi = ah + bh + ch + dh + carry;
27384 return hi >>> 0;
27385}
27386exports.sum64_4_hi = sum64_4_hi;
27387
27388function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
27389 var lo = al + bl + cl + dl;
27390 return lo >>> 0;
27391}
27392exports.sum64_4_lo = sum64_4_lo;
27393
27394function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
27395 var carry = 0;
27396 var lo = al;
27397 lo = (lo + bl) >>> 0;
27398 carry += lo < al ? 1 : 0;
27399 lo = (lo + cl) >>> 0;
27400 carry += lo < cl ? 1 : 0;
27401 lo = (lo + dl) >>> 0;
27402 carry += lo < dl ? 1 : 0;
27403 lo = (lo + el) >>> 0;
27404 carry += lo < el ? 1 : 0;
27405
27406 var hi = ah + bh + ch + dh + eh + carry;
27407 return hi >>> 0;
27408}
27409exports.sum64_5_hi = sum64_5_hi;
27410
27411function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
27412 var lo = al + bl + cl + dl + el;
27413
27414 return lo >>> 0;
27415}
27416exports.sum64_5_lo = sum64_5_lo;
27417
27418function rotr64_hi(ah, al, num) {
27419 var r = (al << (32 - num)) | (ah >>> num);
27420 return r >>> 0;
27421}
27422exports.rotr64_hi = rotr64_hi;
27423
27424function rotr64_lo(ah, al, num) {
27425 var r = (ah << (32 - num)) | (al >>> num);
27426 return r >>> 0;
27427}
27428exports.rotr64_lo = rotr64_lo;
27429
27430function shr64_hi(ah, al, num) {
27431 return ah >>> num;
27432}
27433exports.shr64_hi = shr64_hi;
27434
27435function shr64_lo(ah, al, num) {
27436 var r = (ah << (32 - num)) | (al >>> num);
27437 return r >>> 0;
27438}
27439exports.shr64_lo = shr64_lo;
27440
27441},{"inherits":152,"minimalistic-assert":159}],150:[function(require,module,exports){
27442'use strict';
27443
27444var hash = require('hash.js');
27445var utils = require('minimalistic-crypto-utils');
27446var assert = require('minimalistic-assert');
27447
27448function HmacDRBG(options) {
27449 if (!(this instanceof HmacDRBG))
27450 return new HmacDRBG(options);
27451 this.hash = options.hash;
27452 this.predResist = !!options.predResist;
27453
27454 this.outLen = this.hash.outSize;
27455 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
27456
27457 this._reseed = null;
27458 this.reseedInterval = null;
27459 this.K = null;
27460 this.V = null;
27461
27462 var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
27463 var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
27464 var pers = utils.toArray(options.pers, options.persEnc || 'hex');
27465 assert(entropy.length >= (this.minEntropy / 8),
27466 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
27467 this._init(entropy, nonce, pers);
27468}
27469module.exports = HmacDRBG;
27470
27471HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
27472 var seed = entropy.concat(nonce).concat(pers);
27473
27474 this.K = new Array(this.outLen / 8);
27475 this.V = new Array(this.outLen / 8);
27476 for (var i = 0; i < this.V.length; i++) {
27477 this.K[i] = 0x00;
27478 this.V[i] = 0x01;
27479 }
27480
27481 this._update(seed);
27482 this._reseed = 1;
27483 this.reseedInterval = 0x1000000000000; // 2^48
27484};
27485
27486HmacDRBG.prototype._hmac = function hmac() {
27487 return new hash.hmac(this.hash, this.K);
27488};
27489
27490HmacDRBG.prototype._update = function update(seed) {
27491 var kmac = this._hmac()
27492 .update(this.V)
27493 .update([ 0x00 ]);
27494 if (seed)
27495 kmac = kmac.update(seed);
27496 this.K = kmac.digest();
27497 this.V = this._hmac().update(this.V).digest();
27498 if (!seed)
27499 return;
27500
27501 this.K = this._hmac()
27502 .update(this.V)
27503 .update([ 0x01 ])
27504 .update(seed)
27505 .digest();
27506 this.V = this._hmac().update(this.V).digest();
27507};
27508
27509HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
27510 // Optional entropy enc
27511 if (typeof entropyEnc !== 'string') {
27512 addEnc = add;
27513 add = entropyEnc;
27514 entropyEnc = null;
27515 }
27516
27517 entropy = utils.toArray(entropy, entropyEnc);
27518 add = utils.toArray(add, addEnc);
27519
27520 assert(entropy.length >= (this.minEntropy / 8),
27521 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
27522
27523 this._update(entropy.concat(add || []));
27524 this._reseed = 1;
27525};
27526
27527HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
27528 if (this._reseed > this.reseedInterval)
27529 throw new Error('Reseed is required');
27530
27531 // Optional encoding
27532 if (typeof enc !== 'string') {
27533 addEnc = add;
27534 add = enc;
27535 enc = null;
27536 }
27537
27538 // Optional additional data
27539 if (add) {
27540 add = utils.toArray(add, addEnc || 'hex');
27541 this._update(add);
27542 }
27543
27544 var temp = [];
27545 while (temp.length < len) {
27546 this.V = this._hmac().update(this.V).digest();
27547 temp = temp.concat(this.V);
27548 }
27549
27550 var res = temp.slice(0, len);
27551 this._update(add);
27552 this._reseed++;
27553 return utils.encode(res, enc);
27554};
27555
27556},{"hash.js":138,"minimalistic-assert":159,"minimalistic-crypto-utils":160}],151:[function(require,module,exports){
27557/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
27558exports.read = function (buffer, offset, isLE, mLen, nBytes) {
27559 var e, m
27560 var eLen = (nBytes * 8) - mLen - 1
27561 var eMax = (1 << eLen) - 1
27562 var eBias = eMax >> 1
27563 var nBits = -7
27564 var i = isLE ? (nBytes - 1) : 0
27565 var d = isLE ? -1 : 1
27566 var s = buffer[offset + i]
27567
27568 i += d
27569
27570 e = s & ((1 << (-nBits)) - 1)
27571 s >>= (-nBits)
27572 nBits += eLen
27573 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
27574
27575 m = e & ((1 << (-nBits)) - 1)
27576 e >>= (-nBits)
27577 nBits += mLen
27578 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
27579
27580 if (e === 0) {
27581 e = 1 - eBias
27582 } else if (e === eMax) {
27583 return m ? NaN : ((s ? -1 : 1) * Infinity)
27584 } else {
27585 m = m + Math.pow(2, mLen)
27586 e = e - eBias
27587 }
27588 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
27589}
27590
27591exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
27592 var e, m, c
27593 var eLen = (nBytes * 8) - mLen - 1
27594 var eMax = (1 << eLen) - 1
27595 var eBias = eMax >> 1
27596 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
27597 var i = isLE ? 0 : (nBytes - 1)
27598 var d = isLE ? 1 : -1
27599 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
27600
27601 value = Math.abs(value)
27602
27603 if (isNaN(value) || value === Infinity) {
27604 m = isNaN(value) ? 1 : 0
27605 e = eMax
27606 } else {
27607 e = Math.floor(Math.log(value) / Math.LN2)
27608 if (value * (c = Math.pow(2, -e)) < 1) {
27609 e--
27610 c *= 2
27611 }
27612 if (e + eBias >= 1) {
27613 value += rt / c
27614 } else {
27615 value += rt * Math.pow(2, 1 - eBias)
27616 }
27617 if (value * c >= 2) {
27618 e++
27619 c /= 2
27620 }
27621
27622 if (e + eBias >= eMax) {
27623 m = 0
27624 e = eMax
27625 } else if (e + eBias >= 1) {
27626 m = ((value * c) - 1) * Math.pow(2, mLen)
27627 e = e + eBias
27628 } else {
27629 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
27630 e = 0
27631 }
27632 }
27633
27634 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
27635
27636 e = (e << mLen) | m
27637 eLen += mLen
27638 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
27639
27640 buffer[offset + i - d] |= s * 128
27641}
27642
27643},{}],152:[function(require,module,exports){
27644if (typeof Object.create === 'function') {
27645 // implementation from standard node.js 'util' module
27646 module.exports = function inherits(ctor, superCtor) {
27647 if (superCtor) {
27648 ctor.super_ = superCtor
27649 ctor.prototype = Object.create(superCtor.prototype, {
27650 constructor: {
27651 value: ctor,
27652 enumerable: false,
27653 writable: true,
27654 configurable: true
27655 }
27656 })
27657 }
27658 };
27659} else {
27660 // old school shim for old browsers
27661 module.exports = function inherits(ctor, superCtor) {
27662 if (superCtor) {
27663 ctor.super_ = superCtor
27664 var TempCtor = function () {}
27665 TempCtor.prototype = superCtor.prototype
27666 ctor.prototype = new TempCtor()
27667 ctor.prototype.constructor = ctor
27668 }
27669 }
27670}
27671
27672},{}],153:[function(require,module,exports){
27673/*!
27674 * Determine if an object is a Buffer
27675 *
27676 * @author Feross Aboukhadijeh <https://feross.org>
27677 * @license MIT
27678 */
27679
27680// The _isBuffer check is for Safari 5-7 support, because it's missing
27681// Object.prototype.constructor. Remove this eventually
27682module.exports = function (obj) {
27683 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
27684}
27685
27686function isBuffer (obj) {
27687 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
27688}
27689
27690// For Node v0.10 support. Remove this eventually.
27691function isSlowBuffer (obj) {
27692 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
27693}
27694
27695},{}],154:[function(require,module,exports){
27696var toString = {}.toString;
27697
27698module.exports = Array.isArray || function (arr) {
27699 return toString.call(arr) == '[object Array]';
27700};
27701
27702},{}],155:[function(require,module,exports){
27703(function (process,global){(function (){
27704/**
27705 * [js-sha3]{@link https://github.com/emn178/js-sha3}
27706 *
27707 * @version 0.5.7
27708 * @author Chen, Yi-Cyuan [emn178@gmail.com]
27709 * @copyright Chen, Yi-Cyuan 2015-2016
27710 * @license MIT
27711 */
27712/*jslint bitwise: true */
27713(function () {
27714 'use strict';
27715
27716 var root = typeof window === 'object' ? window : {};
27717 var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
27718 if (NODE_JS) {
27719 root = global;
27720 }
27721 var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;
27722 var HEX_CHARS = '0123456789abcdef'.split('');
27723 var SHAKE_PADDING = [31, 7936, 2031616, 520093696];
27724 var KECCAK_PADDING = [1, 256, 65536, 16777216];
27725 var PADDING = [6, 1536, 393216, 100663296];
27726 var SHIFT = [0, 8, 16, 24];
27727 var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
27728 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,
27729 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,
27730 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
27731 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
27732 var BITS = [224, 256, 384, 512];
27733 var SHAKE_BITS = [128, 256];
27734 var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array'];
27735
27736 var createOutputMethod = function (bits, padding, outputType) {
27737 return function (message) {
27738 return new Keccak(bits, padding, bits).update(message)[outputType]();
27739 };
27740 };
27741
27742 var createShakeOutputMethod = function (bits, padding, outputType) {
27743 return function (message, outputBits) {
27744 return new Keccak(bits, padding, outputBits).update(message)[outputType]();
27745 };
27746 };
27747
27748 var createMethod = function (bits, padding) {
27749 var method = createOutputMethod(bits, padding, 'hex');
27750 method.create = function () {
27751 return new Keccak(bits, padding, bits);
27752 };
27753 method.update = function (message) {
27754 return method.create().update(message);
27755 };
27756 for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
27757 var type = OUTPUT_TYPES[i];
27758 method[type] = createOutputMethod(bits, padding, type);
27759 }
27760 return method;
27761 };
27762
27763 var createShakeMethod = function (bits, padding) {
27764 var method = createShakeOutputMethod(bits, padding, 'hex');
27765 method.create = function (outputBits) {
27766 return new Keccak(bits, padding, outputBits);
27767 };
27768 method.update = function (message, outputBits) {
27769 return method.create(outputBits).update(message);
27770 };
27771 for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
27772 var type = OUTPUT_TYPES[i];
27773 method[type] = createShakeOutputMethod(bits, padding, type);
27774 }
27775 return method;
27776 };
27777
27778 var algorithms = [
27779 {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod},
27780 {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod},
27781 {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod}
27782 ];
27783
27784 var methods = {}, methodNames = [];
27785
27786 for (var i = 0; i < algorithms.length; ++i) {
27787 var algorithm = algorithms[i];
27788 var bits = algorithm.bits;
27789 for (var j = 0; j < bits.length; ++j) {
27790 var methodName = algorithm.name +'_' + bits[j];
27791 methodNames.push(methodName);
27792 methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);
27793 }
27794 }
27795
27796 function Keccak(bits, padding, outputBits) {
27797 this.blocks = [];
27798 this.s = [];
27799 this.padding = padding;
27800 this.outputBits = outputBits;
27801 this.reset = true;
27802 this.block = 0;
27803 this.start = 0;
27804 this.blockCount = (1600 - (bits << 1)) >> 5;
27805 this.byteCount = this.blockCount << 2;
27806 this.outputBlocks = outputBits >> 5;
27807 this.extraBytes = (outputBits & 31) >> 3;
27808
27809 for (var i = 0; i < 50; ++i) {
27810 this.s[i] = 0;
27811 }
27812 }
27813
27814 Keccak.prototype.update = function (message) {
27815 var notString = typeof message !== 'string';
27816 if (notString && message.constructor === ArrayBuffer) {
27817 message = new Uint8Array(message);
27818 }
27819 var length = message.length, blocks = this.blocks, byteCount = this.byteCount,
27820 blockCount = this.blockCount, index = 0, s = this.s, i, code;
27821
27822 while (index < length) {
27823 if (this.reset) {
27824 this.reset = false;
27825 blocks[0] = this.block;
27826 for (i = 1; i < blockCount + 1; ++i) {
27827 blocks[i] = 0;
27828 }
27829 }
27830 if (notString) {
27831 for (i = this.start; index < length && i < byteCount; ++index) {
27832 blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
27833 }
27834 } else {
27835 for (i = this.start; index < length && i < byteCount; ++index) {
27836 code = message.charCodeAt(index);
27837 if (code < 0x80) {
27838 blocks[i >> 2] |= code << SHIFT[i++ & 3];
27839 } else if (code < 0x800) {
27840 blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
27841 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
27842 } else if (code < 0xd800 || code >= 0xe000) {
27843 blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
27844 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
27845 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
27846 } else {
27847 code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
27848 blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
27849 blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
27850 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
27851 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
27852 }
27853 }
27854 }
27855 this.lastByteIndex = i;
27856 if (i >= byteCount) {
27857 this.start = i - byteCount;
27858 this.block = blocks[blockCount];
27859 for (i = 0; i < blockCount; ++i) {
27860 s[i] ^= blocks[i];
27861 }
27862 f(s);
27863 this.reset = true;
27864 } else {
27865 this.start = i;
27866 }
27867 }
27868 return this;
27869 };
27870
27871 Keccak.prototype.finalize = function () {
27872 var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
27873 blocks[i >> 2] |= this.padding[i & 3];
27874 if (this.lastByteIndex === this.byteCount) {
27875 blocks[0] = blocks[blockCount];
27876 for (i = 1; i < blockCount + 1; ++i) {
27877 blocks[i] = 0;
27878 }
27879 }
27880 blocks[blockCount - 1] |= 0x80000000;
27881 for (i = 0; i < blockCount; ++i) {
27882 s[i] ^= blocks[i];
27883 }
27884 f(s);
27885 };
27886
27887 Keccak.prototype.toString = Keccak.prototype.hex = function () {
27888 this.finalize();
27889
27890 var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
27891 extraBytes = this.extraBytes, i = 0, j = 0;
27892 var hex = '', block;
27893 while (j < outputBlocks) {
27894 for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
27895 block = s[i];
27896 hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +
27897 HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +
27898 HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +
27899 HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
27900 }
27901 if (j % blockCount === 0) {
27902 f(s);
27903 i = 0;
27904 }
27905 }
27906 if (extraBytes) {
27907 block = s[i];
27908 if (extraBytes > 0) {
27909 hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
27910 }
27911 if (extraBytes > 1) {
27912 hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
27913 }
27914 if (extraBytes > 2) {
27915 hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
27916 }
27917 }
27918 return hex;
27919 };
27920
27921 Keccak.prototype.arrayBuffer = function () {
27922 this.finalize();
27923
27924 var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
27925 extraBytes = this.extraBytes, i = 0, j = 0;
27926 var bytes = this.outputBits >> 3;
27927 var buffer;
27928 if (extraBytes) {
27929 buffer = new ArrayBuffer((outputBlocks + 1) << 2);
27930 } else {
27931 buffer = new ArrayBuffer(bytes);
27932 }
27933 var array = new Uint32Array(buffer);
27934 while (j < outputBlocks) {
27935 for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
27936 array[j] = s[i];
27937 }
27938 if (j % blockCount === 0) {
27939 f(s);
27940 }
27941 }
27942 if (extraBytes) {
27943 array[i] = s[i];
27944 buffer = buffer.slice(0, bytes);
27945 }
27946 return buffer;
27947 };
27948
27949 Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
27950
27951 Keccak.prototype.digest = Keccak.prototype.array = function () {
27952 this.finalize();
27953
27954 var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
27955 extraBytes = this.extraBytes, i = 0, j = 0;
27956 var array = [], offset, block;
27957 while (j < outputBlocks) {
27958 for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
27959 offset = j << 2;
27960 block = s[i];
27961 array[offset] = block & 0xFF;
27962 array[offset + 1] = (block >> 8) & 0xFF;
27963 array[offset + 2] = (block >> 16) & 0xFF;
27964 array[offset + 3] = (block >> 24) & 0xFF;
27965 }
27966 if (j % blockCount === 0) {
27967 f(s);
27968 }
27969 }
27970 if (extraBytes) {
27971 offset = j << 2;
27972 block = s[i];
27973 if (extraBytes > 0) {
27974 array[offset] = block & 0xFF;
27975 }
27976 if (extraBytes > 1) {
27977 array[offset + 1] = (block >> 8) & 0xFF;
27978 }
27979 if (extraBytes > 2) {
27980 array[offset + 2] = (block >> 16) & 0xFF;
27981 }
27982 }
27983 return array;
27984 };
27985
27986 var f = function (s) {
27987 var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,
27988 b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,
27989 b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,
27990 b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
27991 for (n = 0; n < 48; n += 2) {
27992 c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
27993 c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
27994 c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
27995 c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
27996 c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
27997 c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
27998 c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
27999 c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
28000 c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
28001 c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
28002
28003 h = c8 ^ ((c2 << 1) | (c3 >>> 31));
28004 l = c9 ^ ((c3 << 1) | (c2 >>> 31));
28005 s[0] ^= h;
28006 s[1] ^= l;
28007 s[10] ^= h;
28008 s[11] ^= l;
28009 s[20] ^= h;
28010 s[21] ^= l;
28011 s[30] ^= h;
28012 s[31] ^= l;
28013 s[40] ^= h;
28014 s[41] ^= l;
28015 h = c0 ^ ((c4 << 1) | (c5 >>> 31));
28016 l = c1 ^ ((c5 << 1) | (c4 >>> 31));
28017 s[2] ^= h;
28018 s[3] ^= l;
28019 s[12] ^= h;
28020 s[13] ^= l;
28021 s[22] ^= h;
28022 s[23] ^= l;
28023 s[32] ^= h;
28024 s[33] ^= l;
28025 s[42] ^= h;
28026 s[43] ^= l;
28027 h = c2 ^ ((c6 << 1) | (c7 >>> 31));
28028 l = c3 ^ ((c7 << 1) | (c6 >>> 31));
28029 s[4] ^= h;
28030 s[5] ^= l;
28031 s[14] ^= h;
28032 s[15] ^= l;
28033 s[24] ^= h;
28034 s[25] ^= l;
28035 s[34] ^= h;
28036 s[35] ^= l;
28037 s[44] ^= h;
28038 s[45] ^= l;
28039 h = c4 ^ ((c8 << 1) | (c9 >>> 31));
28040 l = c5 ^ ((c9 << 1) | (c8 >>> 31));
28041 s[6] ^= h;
28042 s[7] ^= l;
28043 s[16] ^= h;
28044 s[17] ^= l;
28045 s[26] ^= h;
28046 s[27] ^= l;
28047 s[36] ^= h;
28048 s[37] ^= l;
28049 s[46] ^= h;
28050 s[47] ^= l;
28051 h = c6 ^ ((c0 << 1) | (c1 >>> 31));
28052 l = c7 ^ ((c1 << 1) | (c0 >>> 31));
28053 s[8] ^= h;
28054 s[9] ^= l;
28055 s[18] ^= h;
28056 s[19] ^= l;
28057 s[28] ^= h;
28058 s[29] ^= l;
28059 s[38] ^= h;
28060 s[39] ^= l;
28061 s[48] ^= h;
28062 s[49] ^= l;
28063
28064 b0 = s[0];
28065 b1 = s[1];
28066 b32 = (s[11] << 4) | (s[10] >>> 28);
28067 b33 = (s[10] << 4) | (s[11] >>> 28);
28068 b14 = (s[20] << 3) | (s[21] >>> 29);
28069 b15 = (s[21] << 3) | (s[20] >>> 29);
28070 b46 = (s[31] << 9) | (s[30] >>> 23);
28071 b47 = (s[30] << 9) | (s[31] >>> 23);
28072 b28 = (s[40] << 18) | (s[41] >>> 14);
28073 b29 = (s[41] << 18) | (s[40] >>> 14);
28074 b20 = (s[2] << 1) | (s[3] >>> 31);
28075 b21 = (s[3] << 1) | (s[2] >>> 31);
28076 b2 = (s[13] << 12) | (s[12] >>> 20);
28077 b3 = (s[12] << 12) | (s[13] >>> 20);
28078 b34 = (s[22] << 10) | (s[23] >>> 22);
28079 b35 = (s[23] << 10) | (s[22] >>> 22);
28080 b16 = (s[33] << 13) | (s[32] >>> 19);
28081 b17 = (s[32] << 13) | (s[33] >>> 19);
28082 b48 = (s[42] << 2) | (s[43] >>> 30);
28083 b49 = (s[43] << 2) | (s[42] >>> 30);
28084 b40 = (s[5] << 30) | (s[4] >>> 2);
28085 b41 = (s[4] << 30) | (s[5] >>> 2);
28086 b22 = (s[14] << 6) | (s[15] >>> 26);
28087 b23 = (s[15] << 6) | (s[14] >>> 26);
28088 b4 = (s[25] << 11) | (s[24] >>> 21);
28089 b5 = (s[24] << 11) | (s[25] >>> 21);
28090 b36 = (s[34] << 15) | (s[35] >>> 17);
28091 b37 = (s[35] << 15) | (s[34] >>> 17);
28092 b18 = (s[45] << 29) | (s[44] >>> 3);
28093 b19 = (s[44] << 29) | (s[45] >>> 3);
28094 b10 = (s[6] << 28) | (s[7] >>> 4);
28095 b11 = (s[7] << 28) | (s[6] >>> 4);
28096 b42 = (s[17] << 23) | (s[16] >>> 9);
28097 b43 = (s[16] << 23) | (s[17] >>> 9);
28098 b24 = (s[26] << 25) | (s[27] >>> 7);
28099 b25 = (s[27] << 25) | (s[26] >>> 7);
28100 b6 = (s[36] << 21) | (s[37] >>> 11);
28101 b7 = (s[37] << 21) | (s[36] >>> 11);
28102 b38 = (s[47] << 24) | (s[46] >>> 8);
28103 b39 = (s[46] << 24) | (s[47] >>> 8);
28104 b30 = (s[8] << 27) | (s[9] >>> 5);
28105 b31 = (s[9] << 27) | (s[8] >>> 5);
28106 b12 = (s[18] << 20) | (s[19] >>> 12);
28107 b13 = (s[19] << 20) | (s[18] >>> 12);
28108 b44 = (s[29] << 7) | (s[28] >>> 25);
28109 b45 = (s[28] << 7) | (s[29] >>> 25);
28110 b26 = (s[38] << 8) | (s[39] >>> 24);
28111 b27 = (s[39] << 8) | (s[38] >>> 24);
28112 b8 = (s[48] << 14) | (s[49] >>> 18);
28113 b9 = (s[49] << 14) | (s[48] >>> 18);
28114
28115 s[0] = b0 ^ (~b2 & b4);
28116 s[1] = b1 ^ (~b3 & b5);
28117 s[10] = b10 ^ (~b12 & b14);
28118 s[11] = b11 ^ (~b13 & b15);
28119 s[20] = b20 ^ (~b22 & b24);
28120 s[21] = b21 ^ (~b23 & b25);
28121 s[30] = b30 ^ (~b32 & b34);
28122 s[31] = b31 ^ (~b33 & b35);
28123 s[40] = b40 ^ (~b42 & b44);
28124 s[41] = b41 ^ (~b43 & b45);
28125 s[2] = b2 ^ (~b4 & b6);
28126 s[3] = b3 ^ (~b5 & b7);
28127 s[12] = b12 ^ (~b14 & b16);
28128 s[13] = b13 ^ (~b15 & b17);
28129 s[22] = b22 ^ (~b24 & b26);
28130 s[23] = b23 ^ (~b25 & b27);
28131 s[32] = b32 ^ (~b34 & b36);
28132 s[33] = b33 ^ (~b35 & b37);
28133 s[42] = b42 ^ (~b44 & b46);
28134 s[43] = b43 ^ (~b45 & b47);
28135 s[4] = b4 ^ (~b6 & b8);
28136 s[5] = b5 ^ (~b7 & b9);
28137 s[14] = b14 ^ (~b16 & b18);
28138 s[15] = b15 ^ (~b17 & b19);
28139 s[24] = b24 ^ (~b26 & b28);
28140 s[25] = b25 ^ (~b27 & b29);
28141 s[34] = b34 ^ (~b36 & b38);
28142 s[35] = b35 ^ (~b37 & b39);
28143 s[44] = b44 ^ (~b46 & b48);
28144 s[45] = b45 ^ (~b47 & b49);
28145 s[6] = b6 ^ (~b8 & b0);
28146 s[7] = b7 ^ (~b9 & b1);
28147 s[16] = b16 ^ (~b18 & b10);
28148 s[17] = b17 ^ (~b19 & b11);
28149 s[26] = b26 ^ (~b28 & b20);
28150 s[27] = b27 ^ (~b29 & b21);
28151 s[36] = b36 ^ (~b38 & b30);
28152 s[37] = b37 ^ (~b39 & b31);
28153 s[46] = b46 ^ (~b48 & b40);
28154 s[47] = b47 ^ (~b49 & b41);
28155 s[8] = b8 ^ (~b0 & b2);
28156 s[9] = b9 ^ (~b1 & b3);
28157 s[18] = b18 ^ (~b10 & b12);
28158 s[19] = b19 ^ (~b11 & b13);
28159 s[28] = b28 ^ (~b20 & b22);
28160 s[29] = b29 ^ (~b21 & b23);
28161 s[38] = b38 ^ (~b30 & b32);
28162 s[39] = b39 ^ (~b31 & b33);
28163 s[48] = b48 ^ (~b40 & b42);
28164 s[49] = b49 ^ (~b41 & b43);
28165
28166 s[0] ^= RC[n];
28167 s[1] ^= RC[n + 1];
28168 }
28169 };
28170
28171 if (COMMON_JS) {
28172 module.exports = methods;
28173 } else {
28174 for (var i = 0; i < methodNames.length; ++i) {
28175 root[methodNames[i]] = methods[methodNames[i]];
28176 }
28177 }
28178})();
28179
28180}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
28181},{"_process":174}],156:[function(require,module,exports){
28182'use strict'
28183var inherits = require('inherits')
28184var HashBase = require('hash-base')
28185var Buffer = require('safe-buffer').Buffer
28186
28187var ARRAY16 = new Array(16)
28188
28189function MD5 () {
28190 HashBase.call(this, 64)
28191
28192 // state
28193 this._a = 0x67452301
28194 this._b = 0xefcdab89
28195 this._c = 0x98badcfe
28196 this._d = 0x10325476
28197}
28198
28199inherits(MD5, HashBase)
28200
28201MD5.prototype._update = function () {
28202 var M = ARRAY16
28203 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
28204
28205 var a = this._a
28206 var b = this._b
28207 var c = this._c
28208 var d = this._d
28209
28210 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
28211 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
28212 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
28213 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
28214 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
28215 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
28216 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
28217 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
28218 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
28219 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
28220 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
28221 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
28222 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
28223 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
28224 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
28225 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
28226
28227 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
28228 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
28229 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
28230 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
28231 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
28232 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
28233 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
28234 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
28235 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
28236 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
28237 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
28238 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
28239 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
28240 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
28241 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
28242 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
28243
28244 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
28245 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
28246 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
28247 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
28248 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
28249 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
28250 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
28251 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
28252 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
28253 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
28254 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
28255 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
28256 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
28257 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
28258 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
28259 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
28260
28261 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
28262 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
28263 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
28264 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
28265 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
28266 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
28267 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
28268 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
28269 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
28270 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
28271 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
28272 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
28273 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
28274 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
28275 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
28276 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
28277
28278 this._a = (this._a + a) | 0
28279 this._b = (this._b + b) | 0
28280 this._c = (this._c + c) | 0
28281 this._d = (this._d + d) | 0
28282}
28283
28284MD5.prototype._digest = function () {
28285 // create padding and handle blocks
28286 this._block[this._blockOffset++] = 0x80
28287 if (this._blockOffset > 56) {
28288 this._block.fill(0, this._blockOffset, 64)
28289 this._update()
28290 this._blockOffset = 0
28291 }
28292
28293 this._block.fill(0, this._blockOffset, 56)
28294 this._block.writeUInt32LE(this._length[0], 56)
28295 this._block.writeUInt32LE(this._length[1], 60)
28296 this._update()
28297
28298 // produce result
28299 var buffer = Buffer.allocUnsafe(16)
28300 buffer.writeInt32LE(this._a, 0)
28301 buffer.writeInt32LE(this._b, 4)
28302 buffer.writeInt32LE(this._c, 8)
28303 buffer.writeInt32LE(this._d, 12)
28304 return buffer
28305}
28306
28307function rotl (x, n) {
28308 return (x << n) | (x >>> (32 - n))
28309}
28310
28311function fnF (a, b, c, d, m, k, s) {
28312 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
28313}
28314
28315function fnG (a, b, c, d, m, k, s) {
28316 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
28317}
28318
28319function fnH (a, b, c, d, m, k, s) {
28320 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
28321}
28322
28323function fnI (a, b, c, d, m, k, s) {
28324 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
28325}
28326
28327module.exports = MD5
28328
28329},{"hash-base":122,"inherits":152,"safe-buffer":200}],157:[function(require,module,exports){
28330var bn = require('bn.js');
28331var brorand = require('brorand');
28332
28333function MillerRabin(rand) {
28334 this.rand = rand || new brorand.Rand();
28335}
28336module.exports = MillerRabin;
28337
28338MillerRabin.create = function create(rand) {
28339 return new MillerRabin(rand);
28340};
28341
28342MillerRabin.prototype._randbelow = function _randbelow(n) {
28343 var len = n.bitLength();
28344 var min_bytes = Math.ceil(len / 8);
28345
28346 // Generage random bytes until a number less than n is found.
28347 // This ensures that 0..n-1 have an equal probability of being selected.
28348 do
28349 var a = new bn(this.rand.generate(min_bytes));
28350 while (a.cmp(n) >= 0);
28351
28352 return a;
28353};
28354
28355MillerRabin.prototype._randrange = function _randrange(start, stop) {
28356 // Generate a random number greater than or equal to start and less than stop.
28357 var size = stop.sub(start);
28358 return start.add(this._randbelow(size));
28359};
28360
28361MillerRabin.prototype.test = function test(n, k, cb) {
28362 var len = n.bitLength();
28363 var red = bn.mont(n);
28364 var rone = new bn(1).toRed(red);
28365
28366 if (!k)
28367 k = Math.max(1, (len / 48) | 0);
28368
28369 // Find d and s, (n - 1) = (2 ^ s) * d;
28370 var n1 = n.subn(1);
28371 for (var s = 0; !n1.testn(s); s++) {}
28372 var d = n.shrn(s);
28373
28374 var rn1 = n1.toRed(red);
28375
28376 var prime = true;
28377 for (; k > 0; k--) {
28378 var a = this._randrange(new bn(2), n1);
28379 if (cb)
28380 cb(a);
28381
28382 var x = a.toRed(red).redPow(d);
28383 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
28384 continue;
28385
28386 for (var i = 1; i < s; i++) {
28387 x = x.redSqr();
28388
28389 if (x.cmp(rone) === 0)
28390 return false;
28391 if (x.cmp(rn1) === 0)
28392 break;
28393 }
28394
28395 if (i === s)
28396 return false;
28397 }
28398
28399 return prime;
28400};
28401
28402MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
28403 var len = n.bitLength();
28404 var red = bn.mont(n);
28405 var rone = new bn(1).toRed(red);
28406
28407 if (!k)
28408 k = Math.max(1, (len / 48) | 0);
28409
28410 // Find d and s, (n - 1) = (2 ^ s) * d;
28411 var n1 = n.subn(1);
28412 for (var s = 0; !n1.testn(s); s++) {}
28413 var d = n.shrn(s);
28414
28415 var rn1 = n1.toRed(red);
28416
28417 for (; k > 0; k--) {
28418 var a = this._randrange(new bn(2), n1);
28419
28420 var g = n.gcd(a);
28421 if (g.cmpn(1) !== 0)
28422 return g;
28423
28424 var x = a.toRed(red).redPow(d);
28425 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
28426 continue;
28427
28428 for (var i = 1; i < s; i++) {
28429 x = x.redSqr();
28430
28431 if (x.cmp(rone) === 0)
28432 return x.fromRed().subn(1).gcd(n);
28433 if (x.cmp(rn1) === 0)
28434 break;
28435 }
28436
28437 if (i === s) {
28438 x = x.redSqr();
28439 return x.fromRed().subn(1).gcd(n);
28440 }
28441 }
28442
28443 return false;
28444};
28445
28446},{"bn.js":158,"brorand":32}],158:[function(require,module,exports){
28447arguments[4][21][0].apply(exports,arguments)
28448},{"buffer":33,"dup":21}],159:[function(require,module,exports){
28449module.exports = assert;
28450
28451function assert(val, msg) {
28452 if (!val)
28453 throw new Error(msg || 'Assertion failed');
28454}
28455
28456assert.equal = function assertEqual(l, r, msg) {
28457 if (l != r)
28458 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
28459};
28460
28461},{}],160:[function(require,module,exports){
28462'use strict';
28463
28464var utils = exports;
28465
28466function toArray(msg, enc) {
28467 if (Array.isArray(msg))
28468 return msg.slice();
28469 if (!msg)
28470 return [];
28471 var res = [];
28472 if (typeof msg !== 'string') {
28473 for (var i = 0; i < msg.length; i++)
28474 res[i] = msg[i] | 0;
28475 return res;
28476 }
28477 if (enc === 'hex') {
28478 msg = msg.replace(/[^a-z0-9]+/ig, '');
28479 if (msg.length % 2 !== 0)
28480 msg = '0' + msg;
28481 for (var i = 0; i < msg.length; i += 2)
28482 res.push(parseInt(msg[i] + msg[i + 1], 16));
28483 } else {
28484 for (var i = 0; i < msg.length; i++) {
28485 var c = msg.charCodeAt(i);
28486 var hi = c >> 8;
28487 var lo = c & 0xff;
28488 if (hi)
28489 res.push(hi, lo);
28490 else
28491 res.push(lo);
28492 }
28493 }
28494 return res;
28495}
28496utils.toArray = toArray;
28497
28498function zero2(word) {
28499 if (word.length === 1)
28500 return '0' + word;
28501 else
28502 return word;
28503}
28504utils.zero2 = zero2;
28505
28506function toHex(msg) {
28507 var res = '';
28508 for (var i = 0; i < msg.length; i++)
28509 res += zero2(msg[i].toString(16));
28510 return res;
28511}
28512utils.toHex = toHex;
28513
28514utils.encode = function encode(arr, enc) {
28515 if (enc === 'hex')
28516 return toHex(arr);
28517 else
28518 return arr;
28519};
28520
28521},{}],161:[function(require,module,exports){
28522/*
28523object-assign
28524(c) Sindre Sorhus
28525@license MIT
28526*/
28527
28528'use strict';
28529/* eslint-disable no-unused-vars */
28530var getOwnPropertySymbols = Object.getOwnPropertySymbols;
28531var hasOwnProperty = Object.prototype.hasOwnProperty;
28532var propIsEnumerable = Object.prototype.propertyIsEnumerable;
28533
28534function toObject(val) {
28535 if (val === null || val === undefined) {
28536 throw new TypeError('Object.assign cannot be called with null or undefined');
28537 }
28538
28539 return Object(val);
28540}
28541
28542function shouldUseNative() {
28543 try {
28544 if (!Object.assign) {
28545 return false;
28546 }
28547
28548 // Detect buggy property enumeration order in older V8 versions.
28549
28550 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
28551 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
28552 test1[5] = 'de';
28553 if (Object.getOwnPropertyNames(test1)[0] === '5') {
28554 return false;
28555 }
28556
28557 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
28558 var test2 = {};
28559 for (var i = 0; i < 10; i++) {
28560 test2['_' + String.fromCharCode(i)] = i;
28561 }
28562 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
28563 return test2[n];
28564 });
28565 if (order2.join('') !== '0123456789') {
28566 return false;
28567 }
28568
28569 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
28570 var test3 = {};
28571 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
28572 test3[letter] = letter;
28573 });
28574 if (Object.keys(Object.assign({}, test3)).join('') !==
28575 'abcdefghijklmnopqrst') {
28576 return false;
28577 }
28578
28579 return true;
28580 } catch (err) {
28581 // We don't expect any of the above to throw, but better to be safe.
28582 return false;
28583 }
28584}
28585
28586module.exports = shouldUseNative() ? Object.assign : function (target, source) {
28587 var from;
28588 var to = toObject(target);
28589 var symbols;
28590
28591 for (var s = 1; s < arguments.length; s++) {
28592 from = Object(arguments[s]);
28593
28594 for (var key in from) {
28595 if (hasOwnProperty.call(from, key)) {
28596 to[key] = from[key];
28597 }
28598 }
28599
28600 if (getOwnPropertySymbols) {
28601 symbols = getOwnPropertySymbols(from);
28602 for (var i = 0; i < symbols.length; i++) {
28603 if (propIsEnumerable.call(from, symbols[i])) {
28604 to[symbols[i]] = from[symbols[i]];
28605 }
28606 }
28607 }
28608 }
28609
28610 return to;
28611};
28612
28613},{}],162:[function(require,module,exports){
28614module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
28615"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
28616"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
28617"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
28618"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
28619"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
28620"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
28621"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
28622"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
28623"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
28624"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
28625"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
28626}
28627},{}],163:[function(require,module,exports){
28628// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
28629// Fedor, you are amazing.
28630'use strict'
28631
28632var asn1 = require('asn1.js')
28633
28634exports.certificate = require('./certificate')
28635
28636var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
28637 this.seq().obj(
28638 this.key('version').int(),
28639 this.key('modulus').int(),
28640 this.key('publicExponent').int(),
28641 this.key('privateExponent').int(),
28642 this.key('prime1').int(),
28643 this.key('prime2').int(),
28644 this.key('exponent1').int(),
28645 this.key('exponent2').int(),
28646 this.key('coefficient').int()
28647 )
28648})
28649exports.RSAPrivateKey = RSAPrivateKey
28650
28651var RSAPublicKey = asn1.define('RSAPublicKey', function () {
28652 this.seq().obj(
28653 this.key('modulus').int(),
28654 this.key('publicExponent').int()
28655 )
28656})
28657exports.RSAPublicKey = RSAPublicKey
28658
28659var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
28660 this.seq().obj(
28661 this.key('algorithm').use(AlgorithmIdentifier),
28662 this.key('subjectPublicKey').bitstr()
28663 )
28664})
28665exports.PublicKey = PublicKey
28666
28667var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
28668 this.seq().obj(
28669 this.key('algorithm').objid(),
28670 this.key('none').null_().optional(),
28671 this.key('curve').objid().optional(),
28672 this.key('params').seq().obj(
28673 this.key('p').int(),
28674 this.key('q').int(),
28675 this.key('g').int()
28676 ).optional()
28677 )
28678})
28679
28680var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
28681 this.seq().obj(
28682 this.key('version').int(),
28683 this.key('algorithm').use(AlgorithmIdentifier),
28684 this.key('subjectPrivateKey').octstr()
28685 )
28686})
28687exports.PrivateKey = PrivateKeyInfo
28688var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
28689 this.seq().obj(
28690 this.key('algorithm').seq().obj(
28691 this.key('id').objid(),
28692 this.key('decrypt').seq().obj(
28693 this.key('kde').seq().obj(
28694 this.key('id').objid(),
28695 this.key('kdeparams').seq().obj(
28696 this.key('salt').octstr(),
28697 this.key('iters').int()
28698 )
28699 ),
28700 this.key('cipher').seq().obj(
28701 this.key('algo').objid(),
28702 this.key('iv').octstr()
28703 )
28704 )
28705 ),
28706 this.key('subjectPrivateKey').octstr()
28707 )
28708})
28709
28710exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
28711
28712var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
28713 this.seq().obj(
28714 this.key('version').int(),
28715 this.key('p').int(),
28716 this.key('q').int(),
28717 this.key('g').int(),
28718 this.key('pub_key').int(),
28719 this.key('priv_key').int()
28720 )
28721})
28722exports.DSAPrivateKey = DSAPrivateKey
28723
28724exports.DSAparam = asn1.define('DSAparam', function () {
28725 this.int()
28726})
28727
28728var ECPrivateKey = asn1.define('ECPrivateKey', function () {
28729 this.seq().obj(
28730 this.key('version').int(),
28731 this.key('privateKey').octstr(),
28732 this.key('parameters').optional().explicit(0).use(ECParameters),
28733 this.key('publicKey').optional().explicit(1).bitstr()
28734 )
28735})
28736exports.ECPrivateKey = ECPrivateKey
28737
28738var ECParameters = asn1.define('ECParameters', function () {
28739 this.choice({
28740 namedCurve: this.objid()
28741 })
28742})
28743
28744exports.signature = asn1.define('signature', function () {
28745 this.seq().obj(
28746 this.key('r').int(),
28747 this.key('s').int()
28748 )
28749})
28750
28751},{"./certificate":164,"asn1.js":7}],164:[function(require,module,exports){
28752// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
28753// thanks to @Rantanen
28754
28755'use strict'
28756
28757var asn = require('asn1.js')
28758
28759var Time = asn.define('Time', function () {
28760 this.choice({
28761 utcTime: this.utctime(),
28762 generalTime: this.gentime()
28763 })
28764})
28765
28766var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
28767 this.seq().obj(
28768 this.key('type').objid(),
28769 this.key('value').any()
28770 )
28771})
28772
28773var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
28774 this.seq().obj(
28775 this.key('algorithm').objid(),
28776 this.key('parameters').optional(),
28777 this.key('curve').objid().optional()
28778 )
28779})
28780
28781var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
28782 this.seq().obj(
28783 this.key('algorithm').use(AlgorithmIdentifier),
28784 this.key('subjectPublicKey').bitstr()
28785 )
28786})
28787
28788var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
28789 this.setof(AttributeTypeValue)
28790})
28791
28792var RDNSequence = asn.define('RDNSequence', function () {
28793 this.seqof(RelativeDistinguishedName)
28794})
28795
28796var Name = asn.define('Name', function () {
28797 this.choice({
28798 rdnSequence: this.use(RDNSequence)
28799 })
28800})
28801
28802var Validity = asn.define('Validity', function () {
28803 this.seq().obj(
28804 this.key('notBefore').use(Time),
28805 this.key('notAfter').use(Time)
28806 )
28807})
28808
28809var Extension = asn.define('Extension', function () {
28810 this.seq().obj(
28811 this.key('extnID').objid(),
28812 this.key('critical').bool().def(false),
28813 this.key('extnValue').octstr()
28814 )
28815})
28816
28817var TBSCertificate = asn.define('TBSCertificate', function () {
28818 this.seq().obj(
28819 this.key('version').explicit(0).int().optional(),
28820 this.key('serialNumber').int(),
28821 this.key('signature').use(AlgorithmIdentifier),
28822 this.key('issuer').use(Name),
28823 this.key('validity').use(Validity),
28824 this.key('subject').use(Name),
28825 this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
28826 this.key('issuerUniqueID').implicit(1).bitstr().optional(),
28827 this.key('subjectUniqueID').implicit(2).bitstr().optional(),
28828 this.key('extensions').explicit(3).seqof(Extension).optional()
28829 )
28830})
28831
28832var X509Certificate = asn.define('X509Certificate', function () {
28833 this.seq().obj(
28834 this.key('tbsCertificate').use(TBSCertificate),
28835 this.key('signatureAlgorithm').use(AlgorithmIdentifier),
28836 this.key('signatureValue').bitstr()
28837 )
28838})
28839
28840module.exports = X509Certificate
28841
28842},{"asn1.js":7}],165:[function(require,module,exports){
28843// adapted from https://github.com/apatil/pemstrip
28844var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m
28845var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m
28846var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m
28847var evp = require('evp_bytestokey')
28848var ciphers = require('browserify-aes')
28849var Buffer = require('safe-buffer').Buffer
28850module.exports = function (okey, password) {
28851 var key = okey.toString()
28852 var match = key.match(findProc)
28853 var decrypted
28854 if (!match) {
28855 var match2 = key.match(fullRegex)
28856 decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64')
28857 } else {
28858 var suite = 'aes' + match[1]
28859 var iv = Buffer.from(match[2], 'hex')
28860 var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64')
28861 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
28862 var out = []
28863 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
28864 out.push(cipher.update(cipherText))
28865 out.push(cipher.final())
28866 decrypted = Buffer.concat(out)
28867 }
28868 var tag = key.match(startRegex)[1]
28869 return {
28870 tag: tag,
28871 data: decrypted
28872 }
28873}
28874
28875},{"browserify-aes":36,"evp_bytestokey":121,"safe-buffer":200}],166:[function(require,module,exports){
28876var asn1 = require('./asn1')
28877var aesid = require('./aesid.json')
28878var fixProc = require('./fixProc')
28879var ciphers = require('browserify-aes')
28880var compat = require('pbkdf2')
28881var Buffer = require('safe-buffer').Buffer
28882module.exports = parseKeys
28883
28884function parseKeys (buffer) {
28885 var password
28886 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
28887 password = buffer.passphrase
28888 buffer = buffer.key
28889 }
28890 if (typeof buffer === 'string') {
28891 buffer = Buffer.from(buffer)
28892 }
28893
28894 var stripped = fixProc(buffer, password)
28895
28896 var type = stripped.tag
28897 var data = stripped.data
28898 var subtype, ndata
28899 switch (type) {
28900 case 'CERTIFICATE':
28901 ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
28902 // falls through
28903 case 'PUBLIC KEY':
28904 if (!ndata) {
28905 ndata = asn1.PublicKey.decode(data, 'der')
28906 }
28907 subtype = ndata.algorithm.algorithm.join('.')
28908 switch (subtype) {
28909 case '1.2.840.113549.1.1.1':
28910 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
28911 case '1.2.840.10045.2.1':
28912 ndata.subjectPrivateKey = ndata.subjectPublicKey
28913 return {
28914 type: 'ec',
28915 data: ndata
28916 }
28917 case '1.2.840.10040.4.1':
28918 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
28919 return {
28920 type: 'dsa',
28921 data: ndata.algorithm.params
28922 }
28923 default: throw new Error('unknown key id ' + subtype)
28924 }
28925 // throw new Error('unknown key type ' + type)
28926 case 'ENCRYPTED PRIVATE KEY':
28927 data = asn1.EncryptedPrivateKey.decode(data, 'der')
28928 data = decrypt(data, password)
28929 // falls through
28930 case 'PRIVATE KEY':
28931 ndata = asn1.PrivateKey.decode(data, 'der')
28932 subtype = ndata.algorithm.algorithm.join('.')
28933 switch (subtype) {
28934 case '1.2.840.113549.1.1.1':
28935 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
28936 case '1.2.840.10045.2.1':
28937 return {
28938 curve: ndata.algorithm.curve,
28939 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
28940 }
28941 case '1.2.840.10040.4.1':
28942 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
28943 return {
28944 type: 'dsa',
28945 params: ndata.algorithm.params
28946 }
28947 default: throw new Error('unknown key id ' + subtype)
28948 }
28949 // throw new Error('unknown key type ' + type)
28950 case 'RSA PUBLIC KEY':
28951 return asn1.RSAPublicKey.decode(data, 'der')
28952 case 'RSA PRIVATE KEY':
28953 return asn1.RSAPrivateKey.decode(data, 'der')
28954 case 'DSA PRIVATE KEY':
28955 return {
28956 type: 'dsa',
28957 params: asn1.DSAPrivateKey.decode(data, 'der')
28958 }
28959 case 'EC PRIVATE KEY':
28960 data = asn1.ECPrivateKey.decode(data, 'der')
28961 return {
28962 curve: data.parameters.value,
28963 privateKey: data.privateKey
28964 }
28965 default: throw new Error('unknown key type ' + type)
28966 }
28967}
28968parseKeys.signature = asn1.signature
28969function decrypt (data, password) {
28970 var salt = data.algorithm.decrypt.kde.kdeparams.salt
28971 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
28972 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
28973 var iv = data.algorithm.decrypt.cipher.iv
28974 var cipherText = data.subjectPrivateKey
28975 var keylen = parseInt(algo.split('-')[1], 10) / 8
28976 var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1')
28977 var cipher = ciphers.createDecipheriv(algo, key, iv)
28978 var out = []
28979 out.push(cipher.update(cipherText))
28980 out.push(cipher.final())
28981 return Buffer.concat(out)
28982}
28983
28984},{"./aesid.json":162,"./asn1":163,"./fixProc":165,"browserify-aes":36,"pbkdf2":167,"safe-buffer":200}],167:[function(require,module,exports){
28985exports.pbkdf2 = require('./lib/async')
28986exports.pbkdf2Sync = require('./lib/sync')
28987
28988},{"./lib/async":168,"./lib/sync":171}],168:[function(require,module,exports){
28989(function (process,global){(function (){
28990var Buffer = require('safe-buffer').Buffer
28991
28992var checkParameters = require('./precondition')
28993var defaultEncoding = require('./default-encoding')
28994var sync = require('./sync')
28995var toBuffer = require('./to-buffer')
28996
28997var ZERO_BUF
28998var subtle = global.crypto && global.crypto.subtle
28999var toBrowser = {
29000 sha: 'SHA-1',
29001 'sha-1': 'SHA-1',
29002 sha1: 'SHA-1',
29003 sha256: 'SHA-256',
29004 'sha-256': 'SHA-256',
29005 sha384: 'SHA-384',
29006 'sha-384': 'SHA-384',
29007 'sha-512': 'SHA-512',
29008 sha512: 'SHA-512'
29009}
29010var checks = []
29011function checkNative (algo) {
29012 if (global.process && !global.process.browser) {
29013 return Promise.resolve(false)
29014 }
29015 if (!subtle || !subtle.importKey || !subtle.deriveBits) {
29016 return Promise.resolve(false)
29017 }
29018 if (checks[algo] !== undefined) {
29019 return checks[algo]
29020 }
29021 ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
29022 var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
29023 .then(function () {
29024 return true
29025 }).catch(function () {
29026 return false
29027 })
29028 checks[algo] = prom
29029 return prom
29030}
29031
29032function browserPbkdf2 (password, salt, iterations, length, algo) {
29033 return subtle.importKey(
29034 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits']
29035 ).then(function (key) {
29036 return subtle.deriveBits({
29037 name: 'PBKDF2',
29038 salt: salt,
29039 iterations: iterations,
29040 hash: {
29041 name: algo
29042 }
29043 }, key, length << 3)
29044 }).then(function (res) {
29045 return Buffer.from(res)
29046 })
29047}
29048
29049function resolvePromise (promise, callback) {
29050 promise.then(function (out) {
29051 process.nextTick(function () {
29052 callback(null, out)
29053 })
29054 }, function (e) {
29055 process.nextTick(function () {
29056 callback(e)
29057 })
29058 })
29059}
29060module.exports = function (password, salt, iterations, keylen, digest, callback) {
29061 if (typeof digest === 'function') {
29062 callback = digest
29063 digest = undefined
29064 }
29065
29066 digest = digest || 'sha1'
29067 var algo = toBrowser[digest.toLowerCase()]
29068
29069 if (!algo || typeof global.Promise !== 'function') {
29070 return process.nextTick(function () {
29071 var out
29072 try {
29073 out = sync(password, salt, iterations, keylen, digest)
29074 } catch (e) {
29075 return callback(e)
29076 }
29077 callback(null, out)
29078 })
29079 }
29080
29081 checkParameters(iterations, keylen)
29082 password = toBuffer(password, defaultEncoding, 'Password')
29083 salt = toBuffer(salt, defaultEncoding, 'Salt')
29084 if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
29085
29086 resolvePromise(checkNative(algo).then(function (resp) {
29087 if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)
29088
29089 return sync(password, salt, iterations, keylen, digest)
29090 }), callback)
29091}
29092
29093}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
29094},{"./default-encoding":169,"./precondition":170,"./sync":171,"./to-buffer":172,"_process":174,"safe-buffer":200}],169:[function(require,module,exports){
29095(function (process){(function (){
29096var defaultEncoding
29097/* istanbul ignore next */
29098if (process.browser) {
29099 defaultEncoding = 'utf-8'
29100} else if (process.version) {
29101 var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
29102
29103 defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
29104} else {
29105 defaultEncoding = 'utf-8'
29106}
29107module.exports = defaultEncoding
29108
29109}).call(this)}).call(this,require('_process'))
29110},{"_process":174}],170:[function(require,module,exports){
29111var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
29112
29113module.exports = function (iterations, keylen) {
29114 if (typeof iterations !== 'number') {
29115 throw new TypeError('Iterations not a number')
29116 }
29117
29118 if (iterations < 0) {
29119 throw new TypeError('Bad iterations')
29120 }
29121
29122 if (typeof keylen !== 'number') {
29123 throw new TypeError('Key length not a number')
29124 }
29125
29126 if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
29127 throw new TypeError('Bad key length')
29128 }
29129}
29130
29131},{}],171:[function(require,module,exports){
29132var md5 = require('create-hash/md5')
29133var RIPEMD160 = require('ripemd160')
29134var sha = require('sha.js')
29135var Buffer = require('safe-buffer').Buffer
29136
29137var checkParameters = require('./precondition')
29138var defaultEncoding = require('./default-encoding')
29139var toBuffer = require('./to-buffer')
29140
29141var ZEROS = Buffer.alloc(128)
29142var sizes = {
29143 md5: 16,
29144 sha1: 20,
29145 sha224: 28,
29146 sha256: 32,
29147 sha384: 48,
29148 sha512: 64,
29149 rmd160: 20,
29150 ripemd160: 20
29151}
29152
29153function Hmac (alg, key, saltLen) {
29154 var hash = getDigest(alg)
29155 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
29156
29157 if (key.length > blocksize) {
29158 key = hash(key)
29159 } else if (key.length < blocksize) {
29160 key = Buffer.concat([key, ZEROS], blocksize)
29161 }
29162
29163 var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
29164 var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
29165 for (var i = 0; i < blocksize; i++) {
29166 ipad[i] = key[i] ^ 0x36
29167 opad[i] = key[i] ^ 0x5C
29168 }
29169
29170 var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
29171 ipad.copy(ipad1, 0, 0, blocksize)
29172 this.ipad1 = ipad1
29173 this.ipad2 = ipad
29174 this.opad = opad
29175 this.alg = alg
29176 this.blocksize = blocksize
29177 this.hash = hash
29178 this.size = sizes[alg]
29179}
29180
29181Hmac.prototype.run = function (data, ipad) {
29182 data.copy(ipad, this.blocksize)
29183 var h = this.hash(ipad)
29184 h.copy(this.opad, this.blocksize)
29185 return this.hash(this.opad)
29186}
29187
29188function getDigest (alg) {
29189 function shaFunc (data) {
29190 return sha(alg).update(data).digest()
29191 }
29192 function rmd160Func (data) {
29193 return new RIPEMD160().update(data).digest()
29194 }
29195
29196 if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
29197 if (alg === 'md5') return md5
29198 return shaFunc
29199}
29200
29201function pbkdf2 (password, salt, iterations, keylen, digest) {
29202 checkParameters(iterations, keylen)
29203 password = toBuffer(password, defaultEncoding, 'Password')
29204 salt = toBuffer(salt, defaultEncoding, 'Salt')
29205
29206 digest = digest || 'sha1'
29207
29208 var hmac = new Hmac(digest, password, salt.length)
29209
29210 var DK = Buffer.allocUnsafe(keylen)
29211 var block1 = Buffer.allocUnsafe(salt.length + 4)
29212 salt.copy(block1, 0, 0, salt.length)
29213
29214 var destPos = 0
29215 var hLen = sizes[digest]
29216 var l = Math.ceil(keylen / hLen)
29217
29218 for (var i = 1; i <= l; i++) {
29219 block1.writeUInt32BE(i, salt.length)
29220
29221 var T = hmac.run(block1, hmac.ipad1)
29222 var U = T
29223
29224 for (var j = 1; j < iterations; j++) {
29225 U = hmac.run(U, hmac.ipad2)
29226 for (var k = 0; k < hLen; k++) T[k] ^= U[k]
29227 }
29228
29229 T.copy(DK, destPos)
29230 destPos += hLen
29231 }
29232
29233 return DK
29234}
29235
29236module.exports = pbkdf2
29237
29238},{"./default-encoding":169,"./precondition":170,"./to-buffer":172,"create-hash/md5":83,"ripemd160":199,"safe-buffer":200,"sha.js":203}],172:[function(require,module,exports){
29239var Buffer = require('safe-buffer').Buffer
29240
29241module.exports = function (thing, encoding, name) {
29242 if (Buffer.isBuffer(thing)) {
29243 return thing
29244 } else if (typeof thing === 'string') {
29245 return Buffer.from(thing, encoding)
29246 } else if (ArrayBuffer.isView(thing)) {
29247 return Buffer.from(thing.buffer)
29248 } else {
29249 throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
29250 }
29251}
29252
29253},{"safe-buffer":200}],173:[function(require,module,exports){
29254(function (process){(function (){
29255'use strict';
29256
29257if (typeof process === 'undefined' ||
29258 !process.version ||
29259 process.version.indexOf('v0.') === 0 ||
29260 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
29261 module.exports = { nextTick: nextTick };
29262} else {
29263 module.exports = process
29264}
29265
29266function nextTick(fn, arg1, arg2, arg3) {
29267 if (typeof fn !== 'function') {
29268 throw new TypeError('"callback" argument must be a function');
29269 }
29270 var len = arguments.length;
29271 var args, i;
29272 switch (len) {
29273 case 0:
29274 case 1:
29275 return process.nextTick(fn);
29276 case 2:
29277 return process.nextTick(function afterTickOne() {
29278 fn.call(null, arg1);
29279 });
29280 case 3:
29281 return process.nextTick(function afterTickTwo() {
29282 fn.call(null, arg1, arg2);
29283 });
29284 case 4:
29285 return process.nextTick(function afterTickThree() {
29286 fn.call(null, arg1, arg2, arg3);
29287 });
29288 default:
29289 args = new Array(len - 1);
29290 i = 0;
29291 while (i < args.length) {
29292 args[i++] = arguments[i];
29293 }
29294 return process.nextTick(function afterTick() {
29295 fn.apply(null, args);
29296 });
29297 }
29298}
29299
29300
29301}).call(this)}).call(this,require('_process'))
29302},{"_process":174}],174:[function(require,module,exports){
29303// shim for using process in browser
29304var process = module.exports = {};
29305
29306// cached from whatever global is present so that test runners that stub it
29307// don't break things. But we need to wrap it in a try catch in case it is
29308// wrapped in strict mode code which doesn't define any globals. It's inside a
29309// function because try/catches deoptimize in certain engines.
29310
29311var cachedSetTimeout;
29312var cachedClearTimeout;
29313
29314function defaultSetTimout() {
29315 throw new Error('setTimeout has not been defined');
29316}
29317function defaultClearTimeout () {
29318 throw new Error('clearTimeout has not been defined');
29319}
29320(function () {
29321 try {
29322 if (typeof setTimeout === 'function') {
29323 cachedSetTimeout = setTimeout;
29324 } else {
29325 cachedSetTimeout = defaultSetTimout;
29326 }
29327 } catch (e) {
29328 cachedSetTimeout = defaultSetTimout;
29329 }
29330 try {
29331 if (typeof clearTimeout === 'function') {
29332 cachedClearTimeout = clearTimeout;
29333 } else {
29334 cachedClearTimeout = defaultClearTimeout;
29335 }
29336 } catch (e) {
29337 cachedClearTimeout = defaultClearTimeout;
29338 }
29339} ())
29340function runTimeout(fun) {
29341 if (cachedSetTimeout === setTimeout) {
29342 //normal enviroments in sane situations
29343 return setTimeout(fun, 0);
29344 }
29345 // if setTimeout wasn't available but was latter defined
29346 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
29347 cachedSetTimeout = setTimeout;
29348 return setTimeout(fun, 0);
29349 }
29350 try {
29351 // when when somebody has screwed with setTimeout but no I.E. maddness
29352 return cachedSetTimeout(fun, 0);
29353 } catch(e){
29354 try {
29355 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
29356 return cachedSetTimeout.call(null, fun, 0);
29357 } catch(e){
29358 // 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
29359 return cachedSetTimeout.call(this, fun, 0);
29360 }
29361 }
29362
29363
29364}
29365function runClearTimeout(marker) {
29366 if (cachedClearTimeout === clearTimeout) {
29367 //normal enviroments in sane situations
29368 return clearTimeout(marker);
29369 }
29370 // if clearTimeout wasn't available but was latter defined
29371 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
29372 cachedClearTimeout = clearTimeout;
29373 return clearTimeout(marker);
29374 }
29375 try {
29376 // when when somebody has screwed with setTimeout but no I.E. maddness
29377 return cachedClearTimeout(marker);
29378 } catch (e){
29379 try {
29380 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
29381 return cachedClearTimeout.call(null, marker);
29382 } catch (e){
29383 // 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.
29384 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
29385 return cachedClearTimeout.call(this, marker);
29386 }
29387 }
29388
29389
29390
29391}
29392var queue = [];
29393var draining = false;
29394var currentQueue;
29395var queueIndex = -1;
29396
29397function cleanUpNextTick() {
29398 if (!draining || !currentQueue) {
29399 return;
29400 }
29401 draining = false;
29402 if (currentQueue.length) {
29403 queue = currentQueue.concat(queue);
29404 } else {
29405 queueIndex = -1;
29406 }
29407 if (queue.length) {
29408 drainQueue();
29409 }
29410}
29411
29412function drainQueue() {
29413 if (draining) {
29414 return;
29415 }
29416 var timeout = runTimeout(cleanUpNextTick);
29417 draining = true;
29418
29419 var len = queue.length;
29420 while(len) {
29421 currentQueue = queue;
29422 queue = [];
29423 while (++queueIndex < len) {
29424 if (currentQueue) {
29425 currentQueue[queueIndex].run();
29426 }
29427 }
29428 queueIndex = -1;
29429 len = queue.length;
29430 }
29431 currentQueue = null;
29432 draining = false;
29433 runClearTimeout(timeout);
29434}
29435
29436process.nextTick = function (fun) {
29437 var args = new Array(arguments.length - 1);
29438 if (arguments.length > 1) {
29439 for (var i = 1; i < arguments.length; i++) {
29440 args[i - 1] = arguments[i];
29441 }
29442 }
29443 queue.push(new Item(fun, args));
29444 if (queue.length === 1 && !draining) {
29445 runTimeout(drainQueue);
29446 }
29447};
29448
29449// v8 likes predictible objects
29450function Item(fun, array) {
29451 this.fun = fun;
29452 this.array = array;
29453}
29454Item.prototype.run = function () {
29455 this.fun.apply(null, this.array);
29456};
29457process.title = 'browser';
29458process.browser = true;
29459process.env = {};
29460process.argv = [];
29461process.version = ''; // empty string to avoid regexp issues
29462process.versions = {};
29463
29464function noop() {}
29465
29466process.on = noop;
29467process.addListener = noop;
29468process.once = noop;
29469process.off = noop;
29470process.removeListener = noop;
29471process.removeAllListeners = noop;
29472process.emit = noop;
29473process.prependListener = noop;
29474process.prependOnceListener = noop;
29475
29476process.listeners = function (name) { return [] }
29477
29478process.binding = function (name) {
29479 throw new Error('process.binding is not supported');
29480};
29481
29482process.cwd = function () { return '/' };
29483process.chdir = function (dir) {
29484 throw new Error('process.chdir is not supported');
29485};
29486process.umask = function() { return 0; };
29487
29488},{}],175:[function(require,module,exports){
29489exports.publicEncrypt = require('./publicEncrypt')
29490exports.privateDecrypt = require('./privateDecrypt')
29491
29492exports.privateEncrypt = function privateEncrypt (key, buf) {
29493 return exports.publicEncrypt(key, buf, true)
29494}
29495
29496exports.publicDecrypt = function publicDecrypt (key, buf) {
29497 return exports.privateDecrypt(key, buf, true)
29498}
29499
29500},{"./privateDecrypt":178,"./publicEncrypt":179}],176:[function(require,module,exports){
29501var createHash = require('create-hash')
29502var Buffer = require('safe-buffer').Buffer
29503
29504module.exports = function (seed, len) {
29505 var t = Buffer.alloc(0)
29506 var i = 0
29507 var c
29508 while (t.length < len) {
29509 c = i2ops(i++)
29510 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
29511 }
29512 return t.slice(0, len)
29513}
29514
29515function i2ops (c) {
29516 var out = Buffer.allocUnsafe(4)
29517 out.writeUInt32BE(c, 0)
29518 return out
29519}
29520
29521},{"create-hash":82,"safe-buffer":200}],177:[function(require,module,exports){
29522arguments[4][21][0].apply(exports,arguments)
29523},{"buffer":33,"dup":21}],178:[function(require,module,exports){
29524var parseKeys = require('parse-asn1')
29525var mgf = require('./mgf')
29526var xor = require('./xor')
29527var BN = require('bn.js')
29528var crt = require('browserify-rsa')
29529var createHash = require('create-hash')
29530var withPublic = require('./withPublic')
29531var Buffer = require('safe-buffer').Buffer
29532
29533module.exports = function privateDecrypt (privateKey, enc, reverse) {
29534 var padding
29535 if (privateKey.padding) {
29536 padding = privateKey.padding
29537 } else if (reverse) {
29538 padding = 1
29539 } else {
29540 padding = 4
29541 }
29542
29543 var key = parseKeys(privateKey)
29544 var k = key.modulus.byteLength()
29545 if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
29546 throw new Error('decryption error')
29547 }
29548 var msg
29549 if (reverse) {
29550 msg = withPublic(new BN(enc), key)
29551 } else {
29552 msg = crt(enc, key)
29553 }
29554 var zBuffer = Buffer.alloc(k - msg.length)
29555 msg = Buffer.concat([zBuffer, msg], k)
29556 if (padding === 4) {
29557 return oaep(key, msg)
29558 } else if (padding === 1) {
29559 return pkcs1(key, msg, reverse)
29560 } else if (padding === 3) {
29561 return msg
29562 } else {
29563 throw new Error('unknown padding')
29564 }
29565}
29566
29567function oaep (key, msg) {
29568 var k = key.modulus.byteLength()
29569 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
29570 var hLen = iHash.length
29571 if (msg[0] !== 0) {
29572 throw new Error('decryption error')
29573 }
29574 var maskedSeed = msg.slice(1, hLen + 1)
29575 var maskedDb = msg.slice(hLen + 1)
29576 var seed = xor(maskedSeed, mgf(maskedDb, hLen))
29577 var db = xor(maskedDb, mgf(seed, k - hLen - 1))
29578 if (compare(iHash, db.slice(0, hLen))) {
29579 throw new Error('decryption error')
29580 }
29581 var i = hLen
29582 while (db[i] === 0) {
29583 i++
29584 }
29585 if (db[i++] !== 1) {
29586 throw new Error('decryption error')
29587 }
29588 return db.slice(i)
29589}
29590
29591function pkcs1 (key, msg, reverse) {
29592 var p1 = msg.slice(0, 2)
29593 var i = 2
29594 var status = 0
29595 while (msg[i++] !== 0) {
29596 if (i >= msg.length) {
29597 status++
29598 break
29599 }
29600 }
29601 var ps = msg.slice(2, i - 1)
29602
29603 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
29604 status++
29605 }
29606 if (ps.length < 8) {
29607 status++
29608 }
29609 if (status) {
29610 throw new Error('decryption error')
29611 }
29612 return msg.slice(i)
29613}
29614function compare (a, b) {
29615 a = Buffer.from(a)
29616 b = Buffer.from(b)
29617 var dif = 0
29618 var len = a.length
29619 if (a.length !== b.length) {
29620 dif++
29621 len = Math.min(a.length, b.length)
29622 }
29623 var i = -1
29624 while (++i < len) {
29625 dif += (a[i] ^ b[i])
29626 }
29627 return dif
29628}
29629
29630},{"./mgf":176,"./withPublic":180,"./xor":181,"bn.js":177,"browserify-rsa":54,"create-hash":82,"parse-asn1":166,"safe-buffer":200}],179:[function(require,module,exports){
29631var parseKeys = require('parse-asn1')
29632var randomBytes = require('randombytes')
29633var createHash = require('create-hash')
29634var mgf = require('./mgf')
29635var xor = require('./xor')
29636var BN = require('bn.js')
29637var withPublic = require('./withPublic')
29638var crt = require('browserify-rsa')
29639var Buffer = require('safe-buffer').Buffer
29640
29641module.exports = function publicEncrypt (publicKey, msg, reverse) {
29642 var padding
29643 if (publicKey.padding) {
29644 padding = publicKey.padding
29645 } else if (reverse) {
29646 padding = 1
29647 } else {
29648 padding = 4
29649 }
29650 var key = parseKeys(publicKey)
29651 var paddedMsg
29652 if (padding === 4) {
29653 paddedMsg = oaep(key, msg)
29654 } else if (padding === 1) {
29655 paddedMsg = pkcs1(key, msg, reverse)
29656 } else if (padding === 3) {
29657 paddedMsg = new BN(msg)
29658 if (paddedMsg.cmp(key.modulus) >= 0) {
29659 throw new Error('data too long for modulus')
29660 }
29661 } else {
29662 throw new Error('unknown padding')
29663 }
29664 if (reverse) {
29665 return crt(paddedMsg, key)
29666 } else {
29667 return withPublic(paddedMsg, key)
29668 }
29669}
29670
29671function oaep (key, msg) {
29672 var k = key.modulus.byteLength()
29673 var mLen = msg.length
29674 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
29675 var hLen = iHash.length
29676 var hLen2 = 2 * hLen
29677 if (mLen > k - hLen2 - 2) {
29678 throw new Error('message too long')
29679 }
29680 var ps = Buffer.alloc(k - mLen - hLen2 - 2)
29681 var dblen = k - hLen - 1
29682 var seed = randomBytes(hLen)
29683 var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
29684 var maskedSeed = xor(seed, mgf(maskedDb, hLen))
29685 return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
29686}
29687function pkcs1 (key, msg, reverse) {
29688 var mLen = msg.length
29689 var k = key.modulus.byteLength()
29690 if (mLen > k - 11) {
29691 throw new Error('message too long')
29692 }
29693 var ps
29694 if (reverse) {
29695 ps = Buffer.alloc(k - mLen - 3, 0xff)
29696 } else {
29697 ps = nonZero(k - mLen - 3)
29698 }
29699 return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
29700}
29701function nonZero (len) {
29702 var out = Buffer.allocUnsafe(len)
29703 var i = 0
29704 var cache = randomBytes(len * 2)
29705 var cur = 0
29706 var num
29707 while (i < len) {
29708 if (cur === cache.length) {
29709 cache = randomBytes(len * 2)
29710 cur = 0
29711 }
29712 num = cache[cur++]
29713 if (num) {
29714 out[i++] = num
29715 }
29716 }
29717 return out
29718}
29719
29720},{"./mgf":176,"./withPublic":180,"./xor":181,"bn.js":177,"browserify-rsa":54,"create-hash":82,"parse-asn1":166,"randombytes":182,"safe-buffer":200}],180:[function(require,module,exports){
29721var BN = require('bn.js')
29722var Buffer = require('safe-buffer').Buffer
29723
29724function withPublic (paddedMsg, key) {
29725 return Buffer.from(paddedMsg
29726 .toRed(BN.mont(key.modulus))
29727 .redPow(new BN(key.publicExponent))
29728 .fromRed()
29729 .toArray())
29730}
29731
29732module.exports = withPublic
29733
29734},{"bn.js":177,"safe-buffer":200}],181:[function(require,module,exports){
29735module.exports = function xor (a, b) {
29736 var len = a.length
29737 var i = -1
29738 while (++i < len) {
29739 a[i] ^= b[i]
29740 }
29741 return a
29742}
29743
29744},{}],182:[function(require,module,exports){
29745(function (process,global){(function (){
29746'use strict'
29747
29748// limit of Crypto.getRandomValues()
29749// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
29750var MAX_BYTES = 65536
29751
29752// Node supports requesting up to this number of bytes
29753// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
29754var MAX_UINT32 = 4294967295
29755
29756function oldBrowser () {
29757 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
29758}
29759
29760var Buffer = require('safe-buffer').Buffer
29761var crypto = global.crypto || global.msCrypto
29762
29763if (crypto && crypto.getRandomValues) {
29764 module.exports = randomBytes
29765} else {
29766 module.exports = oldBrowser
29767}
29768
29769function randomBytes (size, cb) {
29770 // phantomjs needs to throw
29771 if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
29772
29773 var bytes = Buffer.allocUnsafe(size)
29774
29775 if (size > 0) { // getRandomValues fails on IE if size == 0
29776 if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
29777 // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
29778 for (var generated = 0; generated < size; generated += MAX_BYTES) {
29779 // buffer.slice automatically checks if the end is past the end of
29780 // the buffer so we don't have to here
29781 crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
29782 }
29783 } else {
29784 crypto.getRandomValues(bytes)
29785 }
29786 }
29787
29788 if (typeof cb === 'function') {
29789 return process.nextTick(function () {
29790 cb(null, bytes)
29791 })
29792 }
29793
29794 return bytes
29795}
29796
29797}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
29798},{"_process":174,"safe-buffer":200}],183:[function(require,module,exports){
29799(function (process,global){(function (){
29800'use strict'
29801
29802function oldBrowser () {
29803 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
29804}
29805var safeBuffer = require('safe-buffer')
29806var randombytes = require('randombytes')
29807var Buffer = safeBuffer.Buffer
29808var kBufferMaxLength = safeBuffer.kMaxLength
29809var crypto = global.crypto || global.msCrypto
29810var kMaxUint32 = Math.pow(2, 32) - 1
29811function assertOffset (offset, length) {
29812 if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
29813 throw new TypeError('offset must be a number')
29814 }
29815
29816 if (offset > kMaxUint32 || offset < 0) {
29817 throw new TypeError('offset must be a uint32')
29818 }
29819
29820 if (offset > kBufferMaxLength || offset > length) {
29821 throw new RangeError('offset out of range')
29822 }
29823}
29824
29825function assertSize (size, offset, length) {
29826 if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
29827 throw new TypeError('size must be a number')
29828 }
29829
29830 if (size > kMaxUint32 || size < 0) {
29831 throw new TypeError('size must be a uint32')
29832 }
29833
29834 if (size + offset > length || size > kBufferMaxLength) {
29835 throw new RangeError('buffer too small')
29836 }
29837}
29838if ((crypto && crypto.getRandomValues) || !process.browser) {
29839 exports.randomFill = randomFill
29840 exports.randomFillSync = randomFillSync
29841} else {
29842 exports.randomFill = oldBrowser
29843 exports.randomFillSync = oldBrowser
29844}
29845function randomFill (buf, offset, size, cb) {
29846 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
29847 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
29848 }
29849
29850 if (typeof offset === 'function') {
29851 cb = offset
29852 offset = 0
29853 size = buf.length
29854 } else if (typeof size === 'function') {
29855 cb = size
29856 size = buf.length - offset
29857 } else if (typeof cb !== 'function') {
29858 throw new TypeError('"cb" argument must be a function')
29859 }
29860 assertOffset(offset, buf.length)
29861 assertSize(size, offset, buf.length)
29862 return actualFill(buf, offset, size, cb)
29863}
29864
29865function actualFill (buf, offset, size, cb) {
29866 if (process.browser) {
29867 var ourBuf = buf.buffer
29868 var uint = new Uint8Array(ourBuf, offset, size)
29869 crypto.getRandomValues(uint)
29870 if (cb) {
29871 process.nextTick(function () {
29872 cb(null, buf)
29873 })
29874 return
29875 }
29876 return buf
29877 }
29878 if (cb) {
29879 randombytes(size, function (err, bytes) {
29880 if (err) {
29881 return cb(err)
29882 }
29883 bytes.copy(buf, offset)
29884 cb(null, buf)
29885 })
29886 return
29887 }
29888 var bytes = randombytes(size)
29889 bytes.copy(buf, offset)
29890 return buf
29891}
29892function randomFillSync (buf, offset, size) {
29893 if (typeof offset === 'undefined') {
29894 offset = 0
29895 }
29896 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
29897 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
29898 }
29899
29900 assertOffset(offset, buf.length)
29901
29902 if (size === undefined) size = buf.length - offset
29903
29904 assertSize(size, offset, buf.length)
29905
29906 return actualFill(buf, offset, size)
29907}
29908
29909}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
29910},{"_process":174,"randombytes":182,"safe-buffer":200}],184:[function(require,module,exports){
29911module.exports = require('./lib/_stream_duplex.js');
29912
29913},{"./lib/_stream_duplex.js":185}],185:[function(require,module,exports){
29914// Copyright Joyent, Inc. and other Node contributors.
29915//
29916// Permission is hereby granted, free of charge, to any person obtaining a
29917// copy of this software and associated documentation files (the
29918// "Software"), to deal in the Software without restriction, including
29919// without limitation the rights to use, copy, modify, merge, publish,
29920// distribute, sublicense, and/or sell copies of the Software, and to permit
29921// persons to whom the Software is furnished to do so, subject to the
29922// following conditions:
29923//
29924// The above copyright notice and this permission notice shall be included
29925// in all copies or substantial portions of the Software.
29926//
29927// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
29928// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29929// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
29930// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
29931// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
29932// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
29933// USE OR OTHER DEALINGS IN THE SOFTWARE.
29934
29935// a duplex stream is just a stream that is both readable and writable.
29936// Since JS doesn't have multiple prototypal inheritance, this class
29937// prototypally inherits from Readable, and then parasitically from
29938// Writable.
29939
29940'use strict';
29941
29942/*<replacement>*/
29943
29944var pna = require('process-nextick-args');
29945/*</replacement>*/
29946
29947/*<replacement>*/
29948var objectKeys = Object.keys || function (obj) {
29949 var keys = [];
29950 for (var key in obj) {
29951 keys.push(key);
29952 }return keys;
29953};
29954/*</replacement>*/
29955
29956module.exports = Duplex;
29957
29958/*<replacement>*/
29959var util = Object.create(require('core-util-is'));
29960util.inherits = require('inherits');
29961/*</replacement>*/
29962
29963var Readable = require('./_stream_readable');
29964var Writable = require('./_stream_writable');
29965
29966util.inherits(Duplex, Readable);
29967
29968{
29969 // avoid scope creep, the keys array can then be collected
29970 var keys = objectKeys(Writable.prototype);
29971 for (var v = 0; v < keys.length; v++) {
29972 var method = keys[v];
29973 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
29974 }
29975}
29976
29977function Duplex(options) {
29978 if (!(this instanceof Duplex)) return new Duplex(options);
29979
29980 Readable.call(this, options);
29981 Writable.call(this, options);
29982
29983 if (options && options.readable === false) this.readable = false;
29984
29985 if (options && options.writable === false) this.writable = false;
29986
29987 this.allowHalfOpen = true;
29988 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
29989
29990 this.once('end', onend);
29991}
29992
29993Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
29994 // making it explicit this property is not enumerable
29995 // because otherwise some prototype manipulation in
29996 // userland will fail
29997 enumerable: false,
29998 get: function () {
29999 return this._writableState.highWaterMark;
30000 }
30001});
30002
30003// the no-half-open enforcer
30004function onend() {
30005 // if we allow half-open state, or if the writable side ended,
30006 // then we're ok.
30007 if (this.allowHalfOpen || this._writableState.ended) return;
30008
30009 // no more data can be written.
30010 // But allow more writes to happen in this tick.
30011 pna.nextTick(onEndNT, this);
30012}
30013
30014function onEndNT(self) {
30015 self.end();
30016}
30017
30018Object.defineProperty(Duplex.prototype, 'destroyed', {
30019 get: function () {
30020 if (this._readableState === undefined || this._writableState === undefined) {
30021 return false;
30022 }
30023 return this._readableState.destroyed && this._writableState.destroyed;
30024 },
30025 set: function (value) {
30026 // we ignore the value if the stream
30027 // has not been initialized yet
30028 if (this._readableState === undefined || this._writableState === undefined) {
30029 return;
30030 }
30031
30032 // backward compatibility, the user is explicitly
30033 // managing destroyed
30034 this._readableState.destroyed = value;
30035 this._writableState.destroyed = value;
30036 }
30037});
30038
30039Duplex.prototype._destroy = function (err, cb) {
30040 this.push(null);
30041 this.end();
30042
30043 pna.nextTick(cb, err);
30044};
30045},{"./_stream_readable":187,"./_stream_writable":189,"core-util-is":79,"inherits":152,"process-nextick-args":173}],186:[function(require,module,exports){
30046// Copyright Joyent, Inc. and other Node contributors.
30047//
30048// Permission is hereby granted, free of charge, to any person obtaining a
30049// copy of this software and associated documentation files (the
30050// "Software"), to deal in the Software without restriction, including
30051// without limitation the rights to use, copy, modify, merge, publish,
30052// distribute, sublicense, and/or sell copies of the Software, and to permit
30053// persons to whom the Software is furnished to do so, subject to the
30054// following conditions:
30055//
30056// The above copyright notice and this permission notice shall be included
30057// in all copies or substantial portions of the Software.
30058//
30059// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
30060// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30061// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
30062// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
30063// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
30064// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
30065// USE OR OTHER DEALINGS IN THE SOFTWARE.
30066
30067// a passthrough stream.
30068// basically just the most minimal sort of Transform stream.
30069// Every written chunk gets output as-is.
30070
30071'use strict';
30072
30073module.exports = PassThrough;
30074
30075var Transform = require('./_stream_transform');
30076
30077/*<replacement>*/
30078var util = Object.create(require('core-util-is'));
30079util.inherits = require('inherits');
30080/*</replacement>*/
30081
30082util.inherits(PassThrough, Transform);
30083
30084function PassThrough(options) {
30085 if (!(this instanceof PassThrough)) return new PassThrough(options);
30086
30087 Transform.call(this, options);
30088}
30089
30090PassThrough.prototype._transform = function (chunk, encoding, cb) {
30091 cb(null, chunk);
30092};
30093},{"./_stream_transform":188,"core-util-is":79,"inherits":152}],187:[function(require,module,exports){
30094(function (process,global){(function (){
30095// Copyright Joyent, Inc. and other Node contributors.
30096//
30097// Permission is hereby granted, free of charge, to any person obtaining a
30098// copy of this software and associated documentation files (the
30099// "Software"), to deal in the Software without restriction, including
30100// without limitation the rights to use, copy, modify, merge, publish,
30101// distribute, sublicense, and/or sell copies of the Software, and to permit
30102// persons to whom the Software is furnished to do so, subject to the
30103// following conditions:
30104//
30105// The above copyright notice and this permission notice shall be included
30106// in all copies or substantial portions of the Software.
30107//
30108// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
30109// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30110// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
30111// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
30112// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
30113// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
30114// USE OR OTHER DEALINGS IN THE SOFTWARE.
30115
30116'use strict';
30117
30118/*<replacement>*/
30119
30120var pna = require('process-nextick-args');
30121/*</replacement>*/
30122
30123module.exports = Readable;
30124
30125/*<replacement>*/
30126var isArray = require('isarray');
30127/*</replacement>*/
30128
30129/*<replacement>*/
30130var Duplex;
30131/*</replacement>*/
30132
30133Readable.ReadableState = ReadableState;
30134
30135/*<replacement>*/
30136var EE = require('events').EventEmitter;
30137
30138var EElistenerCount = function (emitter, type) {
30139 return emitter.listeners(type).length;
30140};
30141/*</replacement>*/
30142
30143/*<replacement>*/
30144var Stream = require('./internal/streams/stream');
30145/*</replacement>*/
30146
30147/*<replacement>*/
30148
30149var Buffer = require('safe-buffer').Buffer;
30150var OurUint8Array = global.Uint8Array || function () {};
30151function _uint8ArrayToBuffer(chunk) {
30152 return Buffer.from(chunk);
30153}
30154function _isUint8Array(obj) {
30155 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
30156}
30157
30158/*</replacement>*/
30159
30160/*<replacement>*/
30161var util = Object.create(require('core-util-is'));
30162util.inherits = require('inherits');
30163/*</replacement>*/
30164
30165/*<replacement>*/
30166var debugUtil = require('util');
30167var debug = void 0;
30168if (debugUtil && debugUtil.debuglog) {
30169 debug = debugUtil.debuglog('stream');
30170} else {
30171 debug = function () {};
30172}
30173/*</replacement>*/
30174
30175var BufferList = require('./internal/streams/BufferList');
30176var destroyImpl = require('./internal/streams/destroy');
30177var StringDecoder;
30178
30179util.inherits(Readable, Stream);
30180
30181var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
30182
30183function prependListener(emitter, event, fn) {
30184 // Sadly this is not cacheable as some libraries bundle their own
30185 // event emitter implementation with them.
30186 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
30187
30188 // This is a hack to make sure that our error handler is attached before any
30189 // userland ones. NEVER DO THIS. This is here only because this code needs
30190 // to continue to work with older versions of Node.js that do not include
30191 // the prependListener() method. The goal is to eventually remove this hack.
30192 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
30193}
30194
30195function ReadableState(options, stream) {
30196 Duplex = Duplex || require('./_stream_duplex');
30197
30198 options = options || {};
30199
30200 // Duplex streams are both readable and writable, but share
30201 // the same options object.
30202 // However, some cases require setting options to different
30203 // values for the readable and the writable sides of the duplex stream.
30204 // These options can be provided separately as readableXXX and writableXXX.
30205 var isDuplex = stream instanceof Duplex;
30206
30207 // object stream flag. Used to make read(n) ignore n and to
30208 // make all the buffer merging and length checks go away
30209 this.objectMode = !!options.objectMode;
30210
30211 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
30212
30213 // the point at which it stops calling _read() to fill the buffer
30214 // Note: 0 is a valid value, means "don't call _read preemptively ever"
30215 var hwm = options.highWaterMark;
30216 var readableHwm = options.readableHighWaterMark;
30217 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
30218
30219 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
30220
30221 // cast to ints.
30222 this.highWaterMark = Math.floor(this.highWaterMark);
30223
30224 // A linked list is used to store data chunks instead of an array because the
30225 // linked list can remove elements from the beginning faster than
30226 // array.shift()
30227 this.buffer = new BufferList();
30228 this.length = 0;
30229 this.pipes = null;
30230 this.pipesCount = 0;
30231 this.flowing = null;
30232 this.ended = false;
30233 this.endEmitted = false;
30234 this.reading = false;
30235
30236 // a flag to be able to tell if the event 'readable'/'data' is emitted
30237 // immediately, or on a later tick. We set this to true at first, because
30238 // any actions that shouldn't happen until "later" should generally also
30239 // not happen before the first read call.
30240 this.sync = true;
30241
30242 // whenever we return null, then we set a flag to say
30243 // that we're awaiting a 'readable' event emission.
30244 this.needReadable = false;
30245 this.emittedReadable = false;
30246 this.readableListening = false;
30247 this.resumeScheduled = false;
30248
30249 // has it been destroyed
30250 this.destroyed = false;
30251
30252 // Crypto is kind of old and crusty. Historically, its default string
30253 // encoding is 'binary' so we have to make this configurable.
30254 // Everything else in the universe uses 'utf8', though.
30255 this.defaultEncoding = options.defaultEncoding || 'utf8';
30256
30257 // the number of writers that are awaiting a drain event in .pipe()s
30258 this.awaitDrain = 0;
30259
30260 // if true, a maybeReadMore has been scheduled
30261 this.readingMore = false;
30262
30263 this.decoder = null;
30264 this.encoding = null;
30265 if (options.encoding) {
30266 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
30267 this.decoder = new StringDecoder(options.encoding);
30268 this.encoding = options.encoding;
30269 }
30270}
30271
30272function Readable(options) {
30273 Duplex = Duplex || require('./_stream_duplex');
30274
30275 if (!(this instanceof Readable)) return new Readable(options);
30276
30277 this._readableState = new ReadableState(options, this);
30278
30279 // legacy
30280 this.readable = true;
30281
30282 if (options) {
30283 if (typeof options.read === 'function') this._read = options.read;
30284
30285 if (typeof options.destroy === 'function') this._destroy = options.destroy;
30286 }
30287
30288 Stream.call(this);
30289}
30290
30291Object.defineProperty(Readable.prototype, 'destroyed', {
30292 get: function () {
30293 if (this._readableState === undefined) {
30294 return false;
30295 }
30296 return this._readableState.destroyed;
30297 },
30298 set: function (value) {
30299 // we ignore the value if the stream
30300 // has not been initialized yet
30301 if (!this._readableState) {
30302 return;
30303 }
30304
30305 // backward compatibility, the user is explicitly
30306 // managing destroyed
30307 this._readableState.destroyed = value;
30308 }
30309});
30310
30311Readable.prototype.destroy = destroyImpl.destroy;
30312Readable.prototype._undestroy = destroyImpl.undestroy;
30313Readable.prototype._destroy = function (err, cb) {
30314 this.push(null);
30315 cb(err);
30316};
30317
30318// Manually shove something into the read() buffer.
30319// This returns true if the highWaterMark has not been hit yet,
30320// similar to how Writable.write() returns true if you should
30321// write() some more.
30322Readable.prototype.push = function (chunk, encoding) {
30323 var state = this._readableState;
30324 var skipChunkCheck;
30325
30326 if (!state.objectMode) {
30327 if (typeof chunk === 'string') {
30328 encoding = encoding || state.defaultEncoding;
30329 if (encoding !== state.encoding) {
30330 chunk = Buffer.from(chunk, encoding);
30331 encoding = '';
30332 }
30333 skipChunkCheck = true;
30334 }
30335 } else {
30336 skipChunkCheck = true;
30337 }
30338
30339 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
30340};
30341
30342// Unshift should *always* be something directly out of read()
30343Readable.prototype.unshift = function (chunk) {
30344 return readableAddChunk(this, chunk, null, true, false);
30345};
30346
30347function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
30348 var state = stream._readableState;
30349 if (chunk === null) {
30350 state.reading = false;
30351 onEofChunk(stream, state);
30352 } else {
30353 var er;
30354 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
30355 if (er) {
30356 stream.emit('error', er);
30357 } else if (state.objectMode || chunk && chunk.length > 0) {
30358 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
30359 chunk = _uint8ArrayToBuffer(chunk);
30360 }
30361
30362 if (addToFront) {
30363 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
30364 } else if (state.ended) {
30365 stream.emit('error', new Error('stream.push() after EOF'));
30366 } else {
30367 state.reading = false;
30368 if (state.decoder && !encoding) {
30369 chunk = state.decoder.write(chunk);
30370 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
30371 } else {
30372 addChunk(stream, state, chunk, false);
30373 }
30374 }
30375 } else if (!addToFront) {
30376 state.reading = false;
30377 }
30378 }
30379
30380 return needMoreData(state);
30381}
30382
30383function addChunk(stream, state, chunk, addToFront) {
30384 if (state.flowing && state.length === 0 && !state.sync) {
30385 stream.emit('data', chunk);
30386 stream.read(0);
30387 } else {
30388 // update the buffer info.
30389 state.length += state.objectMode ? 1 : chunk.length;
30390 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
30391
30392 if (state.needReadable) emitReadable(stream);
30393 }
30394 maybeReadMore(stream, state);
30395}
30396
30397function chunkInvalid(state, chunk) {
30398 var er;
30399 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
30400 er = new TypeError('Invalid non-string/buffer chunk');
30401 }
30402 return er;
30403}
30404
30405// if it's past the high water mark, we can push in some more.
30406// Also, if we have no data yet, we can stand some
30407// more bytes. This is to work around cases where hwm=0,
30408// such as the repl. Also, if the push() triggered a
30409// readable event, and the user called read(largeNumber) such that
30410// needReadable was set, then we ought to push more, so that another
30411// 'readable' event will be triggered.
30412function needMoreData(state) {
30413 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
30414}
30415
30416Readable.prototype.isPaused = function () {
30417 return this._readableState.flowing === false;
30418};
30419
30420// backwards compatibility.
30421Readable.prototype.setEncoding = function (enc) {
30422 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
30423 this._readableState.decoder = new StringDecoder(enc);
30424 this._readableState.encoding = enc;
30425 return this;
30426};
30427
30428// Don't raise the hwm > 8MB
30429var MAX_HWM = 0x800000;
30430function computeNewHighWaterMark(n) {
30431 if (n >= MAX_HWM) {
30432 n = MAX_HWM;
30433 } else {
30434 // Get the next highest power of 2 to prevent increasing hwm excessively in
30435 // tiny amounts
30436 n--;
30437 n |= n >>> 1;
30438 n |= n >>> 2;
30439 n |= n >>> 4;
30440 n |= n >>> 8;
30441 n |= n >>> 16;
30442 n++;
30443 }
30444 return n;
30445}
30446
30447// This function is designed to be inlinable, so please take care when making
30448// changes to the function body.
30449function howMuchToRead(n, state) {
30450 if (n <= 0 || state.length === 0 && state.ended) return 0;
30451 if (state.objectMode) return 1;
30452 if (n !== n) {
30453 // Only flow one buffer at a time
30454 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
30455 }
30456 // If we're asking for more than the current hwm, then raise the hwm.
30457 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
30458 if (n <= state.length) return n;
30459 // Don't have enough
30460 if (!state.ended) {
30461 state.needReadable = true;
30462 return 0;
30463 }
30464 return state.length;
30465}
30466
30467// you can override either this method, or the async _read(n) below.
30468Readable.prototype.read = function (n) {
30469 debug('read', n);
30470 n = parseInt(n, 10);
30471 var state = this._readableState;
30472 var nOrig = n;
30473
30474 if (n !== 0) state.emittedReadable = false;
30475
30476 // if we're doing read(0) to trigger a readable event, but we
30477 // already have a bunch of data in the buffer, then just trigger
30478 // the 'readable' event and move on.
30479 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
30480 debug('read: emitReadable', state.length, state.ended);
30481 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
30482 return null;
30483 }
30484
30485 n = howMuchToRead(n, state);
30486
30487 // if we've ended, and we're now clear, then finish it up.
30488 if (n === 0 && state.ended) {
30489 if (state.length === 0) endReadable(this);
30490 return null;
30491 }
30492
30493 // All the actual chunk generation logic needs to be
30494 // *below* the call to _read. The reason is that in certain
30495 // synthetic stream cases, such as passthrough streams, _read
30496 // may be a completely synchronous operation which may change
30497 // the state of the read buffer, providing enough data when
30498 // before there was *not* enough.
30499 //
30500 // So, the steps are:
30501 // 1. Figure out what the state of things will be after we do
30502 // a read from the buffer.
30503 //
30504 // 2. If that resulting state will trigger a _read, then call _read.
30505 // Note that this may be asynchronous, or synchronous. Yes, it is
30506 // deeply ugly to write APIs this way, but that still doesn't mean
30507 // that the Readable class should behave improperly, as streams are
30508 // designed to be sync/async agnostic.
30509 // Take note if the _read call is sync or async (ie, if the read call
30510 // has returned yet), so that we know whether or not it's safe to emit
30511 // 'readable' etc.
30512 //
30513 // 3. Actually pull the requested chunks out of the buffer and return.
30514
30515 // if we need a readable event, then we need to do some reading.
30516 var doRead = state.needReadable;
30517 debug('need readable', doRead);
30518
30519 // if we currently have less than the highWaterMark, then also read some
30520 if (state.length === 0 || state.length - n < state.highWaterMark) {
30521 doRead = true;
30522 debug('length less than watermark', doRead);
30523 }
30524
30525 // however, if we've ended, then there's no point, and if we're already
30526 // reading, then it's unnecessary.
30527 if (state.ended || state.reading) {
30528 doRead = false;
30529 debug('reading or ended', doRead);
30530 } else if (doRead) {
30531 debug('do read');
30532 state.reading = true;
30533 state.sync = true;
30534 // if the length is currently zero, then we *need* a readable event.
30535 if (state.length === 0) state.needReadable = true;
30536 // call internal read method
30537 this._read(state.highWaterMark);
30538 state.sync = false;
30539 // If _read pushed data synchronously, then `reading` will be false,
30540 // and we need to re-evaluate how much data we can return to the user.
30541 if (!state.reading) n = howMuchToRead(nOrig, state);
30542 }
30543
30544 var ret;
30545 if (n > 0) ret = fromList(n, state);else ret = null;
30546
30547 if (ret === null) {
30548 state.needReadable = true;
30549 n = 0;
30550 } else {
30551 state.length -= n;
30552 }
30553
30554 if (state.length === 0) {
30555 // If we have nothing in the buffer, then we want to know
30556 // as soon as we *do* get something into the buffer.
30557 if (!state.ended) state.needReadable = true;
30558
30559 // If we tried to read() past the EOF, then emit end on the next tick.
30560 if (nOrig !== n && state.ended) endReadable(this);
30561 }
30562
30563 if (ret !== null) this.emit('data', ret);
30564
30565 return ret;
30566};
30567
30568function onEofChunk(stream, state) {
30569 if (state.ended) return;
30570 if (state.decoder) {
30571 var chunk = state.decoder.end();
30572 if (chunk && chunk.length) {
30573 state.buffer.push(chunk);
30574 state.length += state.objectMode ? 1 : chunk.length;
30575 }
30576 }
30577 state.ended = true;
30578
30579 // emit 'readable' now to make sure it gets picked up.
30580 emitReadable(stream);
30581}
30582
30583// Don't emit readable right away in sync mode, because this can trigger
30584// another read() call => stack overflow. This way, it might trigger
30585// a nextTick recursion warning, but that's not so bad.
30586function emitReadable(stream) {
30587 var state = stream._readableState;
30588 state.needReadable = false;
30589 if (!state.emittedReadable) {
30590 debug('emitReadable', state.flowing);
30591 state.emittedReadable = true;
30592 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
30593 }
30594}
30595
30596function emitReadable_(stream) {
30597 debug('emit readable');
30598 stream.emit('readable');
30599 flow(stream);
30600}
30601
30602// at this point, the user has presumably seen the 'readable' event,
30603// and called read() to consume some data. that may have triggered
30604// in turn another _read(n) call, in which case reading = true if
30605// it's in progress.
30606// However, if we're not ended, or reading, and the length < hwm,
30607// then go ahead and try to read some more preemptively.
30608function maybeReadMore(stream, state) {
30609 if (!state.readingMore) {
30610 state.readingMore = true;
30611 pna.nextTick(maybeReadMore_, stream, state);
30612 }
30613}
30614
30615function maybeReadMore_(stream, state) {
30616 var len = state.length;
30617 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
30618 debug('maybeReadMore read 0');
30619 stream.read(0);
30620 if (len === state.length)
30621 // didn't get any data, stop spinning.
30622 break;else len = state.length;
30623 }
30624 state.readingMore = false;
30625}
30626
30627// abstract method. to be overridden in specific implementation classes.
30628// call cb(er, data) where data is <= n in length.
30629// for virtual (non-string, non-buffer) streams, "length" is somewhat
30630// arbitrary, and perhaps not very meaningful.
30631Readable.prototype._read = function (n) {
30632 this.emit('error', new Error('_read() is not implemented'));
30633};
30634
30635Readable.prototype.pipe = function (dest, pipeOpts) {
30636 var src = this;
30637 var state = this._readableState;
30638
30639 switch (state.pipesCount) {
30640 case 0:
30641 state.pipes = dest;
30642 break;
30643 case 1:
30644 state.pipes = [state.pipes, dest];
30645 break;
30646 default:
30647 state.pipes.push(dest);
30648 break;
30649 }
30650 state.pipesCount += 1;
30651 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
30652
30653 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
30654
30655 var endFn = doEnd ? onend : unpipe;
30656 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
30657
30658 dest.on('unpipe', onunpipe);
30659 function onunpipe(readable, unpipeInfo) {
30660 debug('onunpipe');
30661 if (readable === src) {
30662 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
30663 unpipeInfo.hasUnpiped = true;
30664 cleanup();
30665 }
30666 }
30667 }
30668
30669 function onend() {
30670 debug('onend');
30671 dest.end();
30672 }
30673
30674 // when the dest drains, it reduces the awaitDrain counter
30675 // on the source. This would be more elegant with a .once()
30676 // handler in flow(), but adding and removing repeatedly is
30677 // too slow.
30678 var ondrain = pipeOnDrain(src);
30679 dest.on('drain', ondrain);
30680
30681 var cleanedUp = false;
30682 function cleanup() {
30683 debug('cleanup');
30684 // cleanup event handlers once the pipe is broken
30685 dest.removeListener('close', onclose);
30686 dest.removeListener('finish', onfinish);
30687 dest.removeListener('drain', ondrain);
30688 dest.removeListener('error', onerror);
30689 dest.removeListener('unpipe', onunpipe);
30690 src.removeListener('end', onend);
30691 src.removeListener('end', unpipe);
30692 src.removeListener('data', ondata);
30693
30694 cleanedUp = true;
30695
30696 // if the reader is waiting for a drain event from this
30697 // specific writer, then it would cause it to never start
30698 // flowing again.
30699 // So, if this is awaiting a drain, then we just call it now.
30700 // If we don't know, then assume that we are waiting for one.
30701 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
30702 }
30703
30704 // If the user pushes more data while we're writing to dest then we'll end up
30705 // in ondata again. However, we only want to increase awaitDrain once because
30706 // dest will only emit one 'drain' event for the multiple writes.
30707 // => Introduce a guard on increasing awaitDrain.
30708 var increasedAwaitDrain = false;
30709 src.on('data', ondata);
30710 function ondata(chunk) {
30711 debug('ondata');
30712 increasedAwaitDrain = false;
30713 var ret = dest.write(chunk);
30714 if (false === ret && !increasedAwaitDrain) {
30715 // If the user unpiped during `dest.write()`, it is possible
30716 // to get stuck in a permanently paused state if that write
30717 // also returned false.
30718 // => Check whether `dest` is still a piping destination.
30719 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
30720 debug('false write response, pause', src._readableState.awaitDrain);
30721 src._readableState.awaitDrain++;
30722 increasedAwaitDrain = true;
30723 }
30724 src.pause();
30725 }
30726 }
30727
30728 // if the dest has an error, then stop piping into it.
30729 // however, don't suppress the throwing behavior for this.
30730 function onerror(er) {
30731 debug('onerror', er);
30732 unpipe();
30733 dest.removeListener('error', onerror);
30734 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
30735 }
30736
30737 // Make sure our error handler is attached before userland ones.
30738 prependListener(dest, 'error', onerror);
30739
30740 // Both close and finish should trigger unpipe, but only once.
30741 function onclose() {
30742 dest.removeListener('finish', onfinish);
30743 unpipe();
30744 }
30745 dest.once('close', onclose);
30746 function onfinish() {
30747 debug('onfinish');
30748 dest.removeListener('close', onclose);
30749 unpipe();
30750 }
30751 dest.once('finish', onfinish);
30752
30753 function unpipe() {
30754 debug('unpipe');
30755 src.unpipe(dest);
30756 }
30757
30758 // tell the dest that it's being piped to
30759 dest.emit('pipe', src);
30760
30761 // start the flow if it hasn't been started already.
30762 if (!state.flowing) {
30763 debug('pipe resume');
30764 src.resume();
30765 }
30766
30767 return dest;
30768};
30769
30770function pipeOnDrain(src) {
30771 return function () {
30772 var state = src._readableState;
30773 debug('pipeOnDrain', state.awaitDrain);
30774 if (state.awaitDrain) state.awaitDrain--;
30775 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
30776 state.flowing = true;
30777 flow(src);
30778 }
30779 };
30780}
30781
30782Readable.prototype.unpipe = function (dest) {
30783 var state = this._readableState;
30784 var unpipeInfo = { hasUnpiped: false };
30785
30786 // if we're not piping anywhere, then do nothing.
30787 if (state.pipesCount === 0) return this;
30788
30789 // just one destination. most common case.
30790 if (state.pipesCount === 1) {
30791 // passed in one, but it's not the right one.
30792 if (dest && dest !== state.pipes) return this;
30793
30794 if (!dest) dest = state.pipes;
30795
30796 // got a match.
30797 state.pipes = null;
30798 state.pipesCount = 0;
30799 state.flowing = false;
30800 if (dest) dest.emit('unpipe', this, unpipeInfo);
30801 return this;
30802 }
30803
30804 // slow case. multiple pipe destinations.
30805
30806 if (!dest) {
30807 // remove all.
30808 var dests = state.pipes;
30809 var len = state.pipesCount;
30810 state.pipes = null;
30811 state.pipesCount = 0;
30812 state.flowing = false;
30813
30814 for (var i = 0; i < len; i++) {
30815 dests[i].emit('unpipe', this, unpipeInfo);
30816 }return this;
30817 }
30818
30819 // try to find the right one.
30820 var index = indexOf(state.pipes, dest);
30821 if (index === -1) return this;
30822
30823 state.pipes.splice(index, 1);
30824 state.pipesCount -= 1;
30825 if (state.pipesCount === 1) state.pipes = state.pipes[0];
30826
30827 dest.emit('unpipe', this, unpipeInfo);
30828
30829 return this;
30830};
30831
30832// set up data events if they are asked for
30833// Ensure readable listeners eventually get something
30834Readable.prototype.on = function (ev, fn) {
30835 var res = Stream.prototype.on.call(this, ev, fn);
30836
30837 if (ev === 'data') {
30838 // Start flowing on next tick if stream isn't explicitly paused
30839 if (this._readableState.flowing !== false) this.resume();
30840 } else if (ev === 'readable') {
30841 var state = this._readableState;
30842 if (!state.endEmitted && !state.readableListening) {
30843 state.readableListening = state.needReadable = true;
30844 state.emittedReadable = false;
30845 if (!state.reading) {
30846 pna.nextTick(nReadingNextTick, this);
30847 } else if (state.length) {
30848 emitReadable(this);
30849 }
30850 }
30851 }
30852
30853 return res;
30854};
30855Readable.prototype.addListener = Readable.prototype.on;
30856
30857function nReadingNextTick(self) {
30858 debug('readable nexttick read 0');
30859 self.read(0);
30860}
30861
30862// pause() and resume() are remnants of the legacy readable stream API
30863// If the user uses them, then switch into old mode.
30864Readable.prototype.resume = function () {
30865 var state = this._readableState;
30866 if (!state.flowing) {
30867 debug('resume');
30868 state.flowing = true;
30869 resume(this, state);
30870 }
30871 return this;
30872};
30873
30874function resume(stream, state) {
30875 if (!state.resumeScheduled) {
30876 state.resumeScheduled = true;
30877 pna.nextTick(resume_, stream, state);
30878 }
30879}
30880
30881function resume_(stream, state) {
30882 if (!state.reading) {
30883 debug('resume read 0');
30884 stream.read(0);
30885 }
30886
30887 state.resumeScheduled = false;
30888 state.awaitDrain = 0;
30889 stream.emit('resume');
30890 flow(stream);
30891 if (state.flowing && !state.reading) stream.read(0);
30892}
30893
30894Readable.prototype.pause = function () {
30895 debug('call pause flowing=%j', this._readableState.flowing);
30896 if (false !== this._readableState.flowing) {
30897 debug('pause');
30898 this._readableState.flowing = false;
30899 this.emit('pause');
30900 }
30901 return this;
30902};
30903
30904function flow(stream) {
30905 var state = stream._readableState;
30906 debug('flow', state.flowing);
30907 while (state.flowing && stream.read() !== null) {}
30908}
30909
30910// wrap an old-style stream as the async data source.
30911// This is *not* part of the readable stream interface.
30912// It is an ugly unfortunate mess of history.
30913Readable.prototype.wrap = function (stream) {
30914 var _this = this;
30915
30916 var state = this._readableState;
30917 var paused = false;
30918
30919 stream.on('end', function () {
30920 debug('wrapped end');
30921 if (state.decoder && !state.ended) {
30922 var chunk = state.decoder.end();
30923 if (chunk && chunk.length) _this.push(chunk);
30924 }
30925
30926 _this.push(null);
30927 });
30928
30929 stream.on('data', function (chunk) {
30930 debug('wrapped data');
30931 if (state.decoder) chunk = state.decoder.write(chunk);
30932
30933 // don't skip over falsy values in objectMode
30934 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
30935
30936 var ret = _this.push(chunk);
30937 if (!ret) {
30938 paused = true;
30939 stream.pause();
30940 }
30941 });
30942
30943 // proxy all the other methods.
30944 // important when wrapping filters and duplexes.
30945 for (var i in stream) {
30946 if (this[i] === undefined && typeof stream[i] === 'function') {
30947 this[i] = function (method) {
30948 return function () {
30949 return stream[method].apply(stream, arguments);
30950 };
30951 }(i);
30952 }
30953 }
30954
30955 // proxy certain important events.
30956 for (var n = 0; n < kProxyEvents.length; n++) {
30957 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
30958 }
30959
30960 // when we try to consume some more bytes, simply unpause the
30961 // underlying stream.
30962 this._read = function (n) {
30963 debug('wrapped _read', n);
30964 if (paused) {
30965 paused = false;
30966 stream.resume();
30967 }
30968 };
30969
30970 return this;
30971};
30972
30973Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
30974 // making it explicit this property is not enumerable
30975 // because otherwise some prototype manipulation in
30976 // userland will fail
30977 enumerable: false,
30978 get: function () {
30979 return this._readableState.highWaterMark;
30980 }
30981});
30982
30983// exposed for testing purposes only.
30984Readable._fromList = fromList;
30985
30986// Pluck off n bytes from an array of buffers.
30987// Length is the combined lengths of all the buffers in the list.
30988// This function is designed to be inlinable, so please take care when making
30989// changes to the function body.
30990function fromList(n, state) {
30991 // nothing buffered
30992 if (state.length === 0) return null;
30993
30994 var ret;
30995 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
30996 // read it all, truncate the list
30997 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
30998 state.buffer.clear();
30999 } else {
31000 // read part of list
31001 ret = fromListPartial(n, state.buffer, state.decoder);
31002 }
31003
31004 return ret;
31005}
31006
31007// Extracts only enough buffered data to satisfy the amount requested.
31008// This function is designed to be inlinable, so please take care when making
31009// changes to the function body.
31010function fromListPartial(n, list, hasStrings) {
31011 var ret;
31012 if (n < list.head.data.length) {
31013 // slice is the same for buffers and strings
31014 ret = list.head.data.slice(0, n);
31015 list.head.data = list.head.data.slice(n);
31016 } else if (n === list.head.data.length) {
31017 // first chunk is a perfect match
31018 ret = list.shift();
31019 } else {
31020 // result spans more than one buffer
31021 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
31022 }
31023 return ret;
31024}
31025
31026// Copies a specified amount of characters from the list of buffered data
31027// chunks.
31028// This function is designed to be inlinable, so please take care when making
31029// changes to the function body.
31030function copyFromBufferString(n, list) {
31031 var p = list.head;
31032 var c = 1;
31033 var ret = p.data;
31034 n -= ret.length;
31035 while (p = p.next) {
31036 var str = p.data;
31037 var nb = n > str.length ? str.length : n;
31038 if (nb === str.length) ret += str;else ret += str.slice(0, n);
31039 n -= nb;
31040 if (n === 0) {
31041 if (nb === str.length) {
31042 ++c;
31043 if (p.next) list.head = p.next;else list.head = list.tail = null;
31044 } else {
31045 list.head = p;
31046 p.data = str.slice(nb);
31047 }
31048 break;
31049 }
31050 ++c;
31051 }
31052 list.length -= c;
31053 return ret;
31054}
31055
31056// Copies a specified amount of bytes from the list of buffered data chunks.
31057// This function is designed to be inlinable, so please take care when making
31058// changes to the function body.
31059function copyFromBuffer(n, list) {
31060 var ret = Buffer.allocUnsafe(n);
31061 var p = list.head;
31062 var c = 1;
31063 p.data.copy(ret);
31064 n -= p.data.length;
31065 while (p = p.next) {
31066 var buf = p.data;
31067 var nb = n > buf.length ? buf.length : n;
31068 buf.copy(ret, ret.length - n, 0, nb);
31069 n -= nb;
31070 if (n === 0) {
31071 if (nb === buf.length) {
31072 ++c;
31073 if (p.next) list.head = p.next;else list.head = list.tail = null;
31074 } else {
31075 list.head = p;
31076 p.data = buf.slice(nb);
31077 }
31078 break;
31079 }
31080 ++c;
31081 }
31082 list.length -= c;
31083 return ret;
31084}
31085
31086function endReadable(stream) {
31087 var state = stream._readableState;
31088
31089 // If we get here before consuming all the bytes, then that is a
31090 // bug in node. Should never happen.
31091 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
31092
31093 if (!state.endEmitted) {
31094 state.ended = true;
31095 pna.nextTick(endReadableNT, state, stream);
31096 }
31097}
31098
31099function endReadableNT(state, stream) {
31100 // Check that we didn't get one last unshift.
31101 if (!state.endEmitted && state.length === 0) {
31102 state.endEmitted = true;
31103 stream.readable = false;
31104 stream.emit('end');
31105 }
31106}
31107
31108function indexOf(xs, x) {
31109 for (var i = 0, l = xs.length; i < l; i++) {
31110 if (xs[i] === x) return i;
31111 }
31112 return -1;
31113}
31114}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
31115},{"./_stream_duplex":185,"./internal/streams/BufferList":190,"./internal/streams/destroy":191,"./internal/streams/stream":192,"_process":174,"core-util-is":79,"events":120,"inherits":152,"isarray":154,"process-nextick-args":173,"safe-buffer":193,"string_decoder/":194,"util":33}],188:[function(require,module,exports){
31116// Copyright Joyent, Inc. and other Node contributors.
31117//
31118// Permission is hereby granted, free of charge, to any person obtaining a
31119// copy of this software and associated documentation files (the
31120// "Software"), to deal in the Software without restriction, including
31121// without limitation the rights to use, copy, modify, merge, publish,
31122// distribute, sublicense, and/or sell copies of the Software, and to permit
31123// persons to whom the Software is furnished to do so, subject to the
31124// following conditions:
31125//
31126// The above copyright notice and this permission notice shall be included
31127// in all copies or substantial portions of the Software.
31128//
31129// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
31130// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31131// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
31132// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
31133// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
31134// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
31135// USE OR OTHER DEALINGS IN THE SOFTWARE.
31136
31137// a transform stream is a readable/writable stream where you do
31138// something with the data. Sometimes it's called a "filter",
31139// but that's not a great name for it, since that implies a thing where
31140// some bits pass through, and others are simply ignored. (That would
31141// be a valid example of a transform, of course.)
31142//
31143// While the output is causally related to the input, it's not a
31144// necessarily symmetric or synchronous transformation. For example,
31145// a zlib stream might take multiple plain-text writes(), and then
31146// emit a single compressed chunk some time in the future.
31147//
31148// Here's how this works:
31149//
31150// The Transform stream has all the aspects of the readable and writable
31151// stream classes. When you write(chunk), that calls _write(chunk,cb)
31152// internally, and returns false if there's a lot of pending writes
31153// buffered up. When you call read(), that calls _read(n) until
31154// there's enough pending readable data buffered up.
31155//
31156// In a transform stream, the written data is placed in a buffer. When
31157// _read(n) is called, it transforms the queued up data, calling the
31158// buffered _write cb's as it consumes chunks. If consuming a single
31159// written chunk would result in multiple output chunks, then the first
31160// outputted bit calls the readcb, and subsequent chunks just go into
31161// the read buffer, and will cause it to emit 'readable' if necessary.
31162//
31163// This way, back-pressure is actually determined by the reading side,
31164// since _read has to be called to start processing a new chunk. However,
31165// a pathological inflate type of transform can cause excessive buffering
31166// here. For example, imagine a stream where every byte of input is
31167// interpreted as an integer from 0-255, and then results in that many
31168// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
31169// 1kb of data being output. In this case, you could write a very small
31170// amount of input, and end up with a very large amount of output. In
31171// such a pathological inflating mechanism, there'd be no way to tell
31172// the system to stop doing the transform. A single 4MB write could
31173// cause the system to run out of memory.
31174//
31175// However, even in such a pathological case, only a single written chunk
31176// would be consumed, and then the rest would wait (un-transformed) until
31177// the results of the previous transformed chunk were consumed.
31178
31179'use strict';
31180
31181module.exports = Transform;
31182
31183var Duplex = require('./_stream_duplex');
31184
31185/*<replacement>*/
31186var util = Object.create(require('core-util-is'));
31187util.inherits = require('inherits');
31188/*</replacement>*/
31189
31190util.inherits(Transform, Duplex);
31191
31192function afterTransform(er, data) {
31193 var ts = this._transformState;
31194 ts.transforming = false;
31195
31196 var cb = ts.writecb;
31197
31198 if (!cb) {
31199 return this.emit('error', new Error('write callback called multiple times'));
31200 }
31201
31202 ts.writechunk = null;
31203 ts.writecb = null;
31204
31205 if (data != null) // single equals check for both `null` and `undefined`
31206 this.push(data);
31207
31208 cb(er);
31209
31210 var rs = this._readableState;
31211 rs.reading = false;
31212 if (rs.needReadable || rs.length < rs.highWaterMark) {
31213 this._read(rs.highWaterMark);
31214 }
31215}
31216
31217function Transform(options) {
31218 if (!(this instanceof Transform)) return new Transform(options);
31219
31220 Duplex.call(this, options);
31221
31222 this._transformState = {
31223 afterTransform: afterTransform.bind(this),
31224 needTransform: false,
31225 transforming: false,
31226 writecb: null,
31227 writechunk: null,
31228 writeencoding: null
31229 };
31230
31231 // start out asking for a readable event once data is transformed.
31232 this._readableState.needReadable = true;
31233
31234 // we have implemented the _read method, and done the other things
31235 // that Readable wants before the first _read call, so unset the
31236 // sync guard flag.
31237 this._readableState.sync = false;
31238
31239 if (options) {
31240 if (typeof options.transform === 'function') this._transform = options.transform;
31241
31242 if (typeof options.flush === 'function') this._flush = options.flush;
31243 }
31244
31245 // When the writable side finishes, then flush out anything remaining.
31246 this.on('prefinish', prefinish);
31247}
31248
31249function prefinish() {
31250 var _this = this;
31251
31252 if (typeof this._flush === 'function') {
31253 this._flush(function (er, data) {
31254 done(_this, er, data);
31255 });
31256 } else {
31257 done(this, null, null);
31258 }
31259}
31260
31261Transform.prototype.push = function (chunk, encoding) {
31262 this._transformState.needTransform = false;
31263 return Duplex.prototype.push.call(this, chunk, encoding);
31264};
31265
31266// This is the part where you do stuff!
31267// override this function in implementation classes.
31268// 'chunk' is an input chunk.
31269//
31270// Call `push(newChunk)` to pass along transformed output
31271// to the readable side. You may call 'push' zero or more times.
31272//
31273// Call `cb(err)` when you are done with this chunk. If you pass
31274// an error, then that'll put the hurt on the whole operation. If you
31275// never call cb(), then you'll never get another chunk.
31276Transform.prototype._transform = function (chunk, encoding, cb) {
31277 throw new Error('_transform() is not implemented');
31278};
31279
31280Transform.prototype._write = function (chunk, encoding, cb) {
31281 var ts = this._transformState;
31282 ts.writecb = cb;
31283 ts.writechunk = chunk;
31284 ts.writeencoding = encoding;
31285 if (!ts.transforming) {
31286 var rs = this._readableState;
31287 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
31288 }
31289};
31290
31291// Doesn't matter what the args are here.
31292// _transform does all the work.
31293// That we got here means that the readable side wants more data.
31294Transform.prototype._read = function (n) {
31295 var ts = this._transformState;
31296
31297 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
31298 ts.transforming = true;
31299 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
31300 } else {
31301 // mark that we need a transform, so that any data that comes in
31302 // will get processed, now that we've asked for it.
31303 ts.needTransform = true;
31304 }
31305};
31306
31307Transform.prototype._destroy = function (err, cb) {
31308 var _this2 = this;
31309
31310 Duplex.prototype._destroy.call(this, err, function (err2) {
31311 cb(err2);
31312 _this2.emit('close');
31313 });
31314};
31315
31316function done(stream, er, data) {
31317 if (er) return stream.emit('error', er);
31318
31319 if (data != null) // single equals check for both `null` and `undefined`
31320 stream.push(data);
31321
31322 // if there's nothing in the write buffer, then that means
31323 // that nothing more will ever be provided
31324 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
31325
31326 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
31327
31328 return stream.push(null);
31329}
31330},{"./_stream_duplex":185,"core-util-is":79,"inherits":152}],189:[function(require,module,exports){
31331(function (process,global,setImmediate){(function (){
31332// Copyright Joyent, Inc. and other Node contributors.
31333//
31334// Permission is hereby granted, free of charge, to any person obtaining a
31335// copy of this software and associated documentation files (the
31336// "Software"), to deal in the Software without restriction, including
31337// without limitation the rights to use, copy, modify, merge, publish,
31338// distribute, sublicense, and/or sell copies of the Software, and to permit
31339// persons to whom the Software is furnished to do so, subject to the
31340// following conditions:
31341//
31342// The above copyright notice and this permission notice shall be included
31343// in all copies or substantial portions of the Software.
31344//
31345// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
31346// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31347// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
31348// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
31349// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
31350// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
31351// USE OR OTHER DEALINGS IN THE SOFTWARE.
31352
31353// A bit simpler than readable streams.
31354// Implement an async ._write(chunk, encoding, cb), and it'll handle all
31355// the drain event emission and buffering.
31356
31357'use strict';
31358
31359/*<replacement>*/
31360
31361var pna = require('process-nextick-args');
31362/*</replacement>*/
31363
31364module.exports = Writable;
31365
31366/* <replacement> */
31367function WriteReq(chunk, encoding, cb) {
31368 this.chunk = chunk;
31369 this.encoding = encoding;
31370 this.callback = cb;
31371 this.next = null;
31372}
31373
31374// It seems a linked list but it is not
31375// there will be only 2 of these for each stream
31376function CorkedRequest(state) {
31377 var _this = this;
31378
31379 this.next = null;
31380 this.entry = null;
31381 this.finish = function () {
31382 onCorkedFinish(_this, state);
31383 };
31384}
31385/* </replacement> */
31386
31387/*<replacement>*/
31388var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
31389/*</replacement>*/
31390
31391/*<replacement>*/
31392var Duplex;
31393/*</replacement>*/
31394
31395Writable.WritableState = WritableState;
31396
31397/*<replacement>*/
31398var util = Object.create(require('core-util-is'));
31399util.inherits = require('inherits');
31400/*</replacement>*/
31401
31402/*<replacement>*/
31403var internalUtil = {
31404 deprecate: require('util-deprecate')
31405};
31406/*</replacement>*/
31407
31408/*<replacement>*/
31409var Stream = require('./internal/streams/stream');
31410/*</replacement>*/
31411
31412/*<replacement>*/
31413
31414var Buffer = require('safe-buffer').Buffer;
31415var OurUint8Array = global.Uint8Array || function () {};
31416function _uint8ArrayToBuffer(chunk) {
31417 return Buffer.from(chunk);
31418}
31419function _isUint8Array(obj) {
31420 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
31421}
31422
31423/*</replacement>*/
31424
31425var destroyImpl = require('./internal/streams/destroy');
31426
31427util.inherits(Writable, Stream);
31428
31429function nop() {}
31430
31431function WritableState(options, stream) {
31432 Duplex = Duplex || require('./_stream_duplex');
31433
31434 options = options || {};
31435
31436 // Duplex streams are both readable and writable, but share
31437 // the same options object.
31438 // However, some cases require setting options to different
31439 // values for the readable and the writable sides of the duplex stream.
31440 // These options can be provided separately as readableXXX and writableXXX.
31441 var isDuplex = stream instanceof Duplex;
31442
31443 // object stream flag to indicate whether or not this stream
31444 // contains buffers or objects.
31445 this.objectMode = !!options.objectMode;
31446
31447 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
31448
31449 // the point at which write() starts returning false
31450 // Note: 0 is a valid value, means that we always return false if
31451 // the entire buffer is not flushed immediately on write()
31452 var hwm = options.highWaterMark;
31453 var writableHwm = options.writableHighWaterMark;
31454 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
31455
31456 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
31457
31458 // cast to ints.
31459 this.highWaterMark = Math.floor(this.highWaterMark);
31460
31461 // if _final has been called
31462 this.finalCalled = false;
31463
31464 // drain event flag.
31465 this.needDrain = false;
31466 // at the start of calling end()
31467 this.ending = false;
31468 // when end() has been called, and returned
31469 this.ended = false;
31470 // when 'finish' is emitted
31471 this.finished = false;
31472
31473 // has it been destroyed
31474 this.destroyed = false;
31475
31476 // should we decode strings into buffers before passing to _write?
31477 // this is here so that some node-core streams can optimize string
31478 // handling at a lower level.
31479 var noDecode = options.decodeStrings === false;
31480 this.decodeStrings = !noDecode;
31481
31482 // Crypto is kind of old and crusty. Historically, its default string
31483 // encoding is 'binary' so we have to make this configurable.
31484 // Everything else in the universe uses 'utf8', though.
31485 this.defaultEncoding = options.defaultEncoding || 'utf8';
31486
31487 // not an actual buffer we keep track of, but a measurement
31488 // of how much we're waiting to get pushed to some underlying
31489 // socket or file.
31490 this.length = 0;
31491
31492 // a flag to see when we're in the middle of a write.
31493 this.writing = false;
31494
31495 // when true all writes will be buffered until .uncork() call
31496 this.corked = 0;
31497
31498 // a flag to be able to tell if the onwrite cb is called immediately,
31499 // or on a later tick. We set this to true at first, because any
31500 // actions that shouldn't happen until "later" should generally also
31501 // not happen before the first write call.
31502 this.sync = true;
31503
31504 // a flag to know if we're processing previously buffered items, which
31505 // may call the _write() callback in the same tick, so that we don't
31506 // end up in an overlapped onwrite situation.
31507 this.bufferProcessing = false;
31508
31509 // the callback that's passed to _write(chunk,cb)
31510 this.onwrite = function (er) {
31511 onwrite(stream, er);
31512 };
31513
31514 // the callback that the user supplies to write(chunk,encoding,cb)
31515 this.writecb = null;
31516
31517 // the amount that is being written when _write is called.
31518 this.writelen = 0;
31519
31520 this.bufferedRequest = null;
31521 this.lastBufferedRequest = null;
31522
31523 // number of pending user-supplied write callbacks
31524 // this must be 0 before 'finish' can be emitted
31525 this.pendingcb = 0;
31526
31527 // emit prefinish if the only thing we're waiting for is _write cbs
31528 // This is relevant for synchronous Transform streams
31529 this.prefinished = false;
31530
31531 // True if the error was already emitted and should not be thrown again
31532 this.errorEmitted = false;
31533
31534 // count buffered requests
31535 this.bufferedRequestCount = 0;
31536
31537 // allocate the first CorkedRequest, there is always
31538 // one allocated and free to use, and we maintain at most two
31539 this.corkedRequestsFree = new CorkedRequest(this);
31540}
31541
31542WritableState.prototype.getBuffer = function getBuffer() {
31543 var current = this.bufferedRequest;
31544 var out = [];
31545 while (current) {
31546 out.push(current);
31547 current = current.next;
31548 }
31549 return out;
31550};
31551
31552(function () {
31553 try {
31554 Object.defineProperty(WritableState.prototype, 'buffer', {
31555 get: internalUtil.deprecate(function () {
31556 return this.getBuffer();
31557 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
31558 });
31559 } catch (_) {}
31560})();
31561
31562// Test _writableState for inheritance to account for Duplex streams,
31563// whose prototype chain only points to Readable.
31564var realHasInstance;
31565if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
31566 realHasInstance = Function.prototype[Symbol.hasInstance];
31567 Object.defineProperty(Writable, Symbol.hasInstance, {
31568 value: function (object) {
31569 if (realHasInstance.call(this, object)) return true;
31570 if (this !== Writable) return false;
31571
31572 return object && object._writableState instanceof WritableState;
31573 }
31574 });
31575} else {
31576 realHasInstance = function (object) {
31577 return object instanceof this;
31578 };
31579}
31580
31581function Writable(options) {
31582 Duplex = Duplex || require('./_stream_duplex');
31583
31584 // Writable ctor is applied to Duplexes, too.
31585 // `realHasInstance` is necessary because using plain `instanceof`
31586 // would return false, as no `_writableState` property is attached.
31587
31588 // Trying to use the custom `instanceof` for Writable here will also break the
31589 // Node.js LazyTransform implementation, which has a non-trivial getter for
31590 // `_writableState` that would lead to infinite recursion.
31591 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
31592 return new Writable(options);
31593 }
31594
31595 this._writableState = new WritableState(options, this);
31596
31597 // legacy.
31598 this.writable = true;
31599
31600 if (options) {
31601 if (typeof options.write === 'function') this._write = options.write;
31602
31603 if (typeof options.writev === 'function') this._writev = options.writev;
31604
31605 if (typeof options.destroy === 'function') this._destroy = options.destroy;
31606
31607 if (typeof options.final === 'function') this._final = options.final;
31608 }
31609
31610 Stream.call(this);
31611}
31612
31613// Otherwise people can pipe Writable streams, which is just wrong.
31614Writable.prototype.pipe = function () {
31615 this.emit('error', new Error('Cannot pipe, not readable'));
31616};
31617
31618function writeAfterEnd(stream, cb) {
31619 var er = new Error('write after end');
31620 // TODO: defer error events consistently everywhere, not just the cb
31621 stream.emit('error', er);
31622 pna.nextTick(cb, er);
31623}
31624
31625// Checks that a user-supplied chunk is valid, especially for the particular
31626// mode the stream is in. Currently this means that `null` is never accepted
31627// and undefined/non-string values are only allowed in object mode.
31628function validChunk(stream, state, chunk, cb) {
31629 var valid = true;
31630 var er = false;
31631
31632 if (chunk === null) {
31633 er = new TypeError('May not write null values to stream');
31634 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
31635 er = new TypeError('Invalid non-string/buffer chunk');
31636 }
31637 if (er) {
31638 stream.emit('error', er);
31639 pna.nextTick(cb, er);
31640 valid = false;
31641 }
31642 return valid;
31643}
31644
31645Writable.prototype.write = function (chunk, encoding, cb) {
31646 var state = this._writableState;
31647 var ret = false;
31648 var isBuf = !state.objectMode && _isUint8Array(chunk);
31649
31650 if (isBuf && !Buffer.isBuffer(chunk)) {
31651 chunk = _uint8ArrayToBuffer(chunk);
31652 }
31653
31654 if (typeof encoding === 'function') {
31655 cb = encoding;
31656 encoding = null;
31657 }
31658
31659 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
31660
31661 if (typeof cb !== 'function') cb = nop;
31662
31663 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
31664 state.pendingcb++;
31665 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
31666 }
31667
31668 return ret;
31669};
31670
31671Writable.prototype.cork = function () {
31672 var state = this._writableState;
31673
31674 state.corked++;
31675};
31676
31677Writable.prototype.uncork = function () {
31678 var state = this._writableState;
31679
31680 if (state.corked) {
31681 state.corked--;
31682
31683 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
31684 }
31685};
31686
31687Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
31688 // node::ParseEncoding() requires lower case.
31689 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
31690 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);
31691 this._writableState.defaultEncoding = encoding;
31692 return this;
31693};
31694
31695function decodeChunk(state, chunk, encoding) {
31696 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
31697 chunk = Buffer.from(chunk, encoding);
31698 }
31699 return chunk;
31700}
31701
31702Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
31703 // making it explicit this property is not enumerable
31704 // because otherwise some prototype manipulation in
31705 // userland will fail
31706 enumerable: false,
31707 get: function () {
31708 return this._writableState.highWaterMark;
31709 }
31710});
31711
31712// if we're already writing something, then just put this
31713// in the queue, and wait our turn. Otherwise, call _write
31714// If we return false, then we need a drain event, so set that flag.
31715function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
31716 if (!isBuf) {
31717 var newChunk = decodeChunk(state, chunk, encoding);
31718 if (chunk !== newChunk) {
31719 isBuf = true;
31720 encoding = 'buffer';
31721 chunk = newChunk;
31722 }
31723 }
31724 var len = state.objectMode ? 1 : chunk.length;
31725
31726 state.length += len;
31727
31728 var ret = state.length < state.highWaterMark;
31729 // we must ensure that previous needDrain will not be reset to false.
31730 if (!ret) state.needDrain = true;
31731
31732 if (state.writing || state.corked) {
31733 var last = state.lastBufferedRequest;
31734 state.lastBufferedRequest = {
31735 chunk: chunk,
31736 encoding: encoding,
31737 isBuf: isBuf,
31738 callback: cb,
31739 next: null
31740 };
31741 if (last) {
31742 last.next = state.lastBufferedRequest;
31743 } else {
31744 state.bufferedRequest = state.lastBufferedRequest;
31745 }
31746 state.bufferedRequestCount += 1;
31747 } else {
31748 doWrite(stream, state, false, len, chunk, encoding, cb);
31749 }
31750
31751 return ret;
31752}
31753
31754function doWrite(stream, state, writev, len, chunk, encoding, cb) {
31755 state.writelen = len;
31756 state.writecb = cb;
31757 state.writing = true;
31758 state.sync = true;
31759 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
31760 state.sync = false;
31761}
31762
31763function onwriteError(stream, state, sync, er, cb) {
31764 --state.pendingcb;
31765
31766 if (sync) {
31767 // defer the callback if we are being called synchronously
31768 // to avoid piling up things on the stack
31769 pna.nextTick(cb, er);
31770 // this can emit finish, and it will always happen
31771 // after error
31772 pna.nextTick(finishMaybe, stream, state);
31773 stream._writableState.errorEmitted = true;
31774 stream.emit('error', er);
31775 } else {
31776 // the caller expect this to happen before if
31777 // it is async
31778 cb(er);
31779 stream._writableState.errorEmitted = true;
31780 stream.emit('error', er);
31781 // this can emit finish, but finish must
31782 // always follow error
31783 finishMaybe(stream, state);
31784 }
31785}
31786
31787function onwriteStateUpdate(state) {
31788 state.writing = false;
31789 state.writecb = null;
31790 state.length -= state.writelen;
31791 state.writelen = 0;
31792}
31793
31794function onwrite(stream, er) {
31795 var state = stream._writableState;
31796 var sync = state.sync;
31797 var cb = state.writecb;
31798
31799 onwriteStateUpdate(state);
31800
31801 if (er) onwriteError(stream, state, sync, er, cb);else {
31802 // Check if we're actually ready to finish, but don't emit yet
31803 var finished = needFinish(state);
31804
31805 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
31806 clearBuffer(stream, state);
31807 }
31808
31809 if (sync) {
31810 /*<replacement>*/
31811 asyncWrite(afterWrite, stream, state, finished, cb);
31812 /*</replacement>*/
31813 } else {
31814 afterWrite(stream, state, finished, cb);
31815 }
31816 }
31817}
31818
31819function afterWrite(stream, state, finished, cb) {
31820 if (!finished) onwriteDrain(stream, state);
31821 state.pendingcb--;
31822 cb();
31823 finishMaybe(stream, state);
31824}
31825
31826// Must force callback to be called on nextTick, so that we don't
31827// emit 'drain' before the write() consumer gets the 'false' return
31828// value, and has a chance to attach a 'drain' listener.
31829function onwriteDrain(stream, state) {
31830 if (state.length === 0 && state.needDrain) {
31831 state.needDrain = false;
31832 stream.emit('drain');
31833 }
31834}
31835
31836// if there's something in the buffer waiting, then process it
31837function clearBuffer(stream, state) {
31838 state.bufferProcessing = true;
31839 var entry = state.bufferedRequest;
31840
31841 if (stream._writev && entry && entry.next) {
31842 // Fast case, write everything using _writev()
31843 var l = state.bufferedRequestCount;
31844 var buffer = new Array(l);
31845 var holder = state.corkedRequestsFree;
31846 holder.entry = entry;
31847
31848 var count = 0;
31849 var allBuffers = true;
31850 while (entry) {
31851 buffer[count] = entry;
31852 if (!entry.isBuf) allBuffers = false;
31853 entry = entry.next;
31854 count += 1;
31855 }
31856 buffer.allBuffers = allBuffers;
31857
31858 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
31859
31860 // doWrite is almost always async, defer these to save a bit of time
31861 // as the hot path ends with doWrite
31862 state.pendingcb++;
31863 state.lastBufferedRequest = null;
31864 if (holder.next) {
31865 state.corkedRequestsFree = holder.next;
31866 holder.next = null;
31867 } else {
31868 state.corkedRequestsFree = new CorkedRequest(state);
31869 }
31870 state.bufferedRequestCount = 0;
31871 } else {
31872 // Slow case, write chunks one-by-one
31873 while (entry) {
31874 var chunk = entry.chunk;
31875 var encoding = entry.encoding;
31876 var cb = entry.callback;
31877 var len = state.objectMode ? 1 : chunk.length;
31878
31879 doWrite(stream, state, false, len, chunk, encoding, cb);
31880 entry = entry.next;
31881 state.bufferedRequestCount--;
31882 // if we didn't call the onwrite immediately, then
31883 // it means that we need to wait until it does.
31884 // also, that means that the chunk and cb are currently
31885 // being processed, so move the buffer counter past them.
31886 if (state.writing) {
31887 break;
31888 }
31889 }
31890
31891 if (entry === null) state.lastBufferedRequest = null;
31892 }
31893
31894 state.bufferedRequest = entry;
31895 state.bufferProcessing = false;
31896}
31897
31898Writable.prototype._write = function (chunk, encoding, cb) {
31899 cb(new Error('_write() is not implemented'));
31900};
31901
31902Writable.prototype._writev = null;
31903
31904Writable.prototype.end = function (chunk, encoding, cb) {
31905 var state = this._writableState;
31906
31907 if (typeof chunk === 'function') {
31908 cb = chunk;
31909 chunk = null;
31910 encoding = null;
31911 } else if (typeof encoding === 'function') {
31912 cb = encoding;
31913 encoding = null;
31914 }
31915
31916 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
31917
31918 // .end() fully uncorks
31919 if (state.corked) {
31920 state.corked = 1;
31921 this.uncork();
31922 }
31923
31924 // ignore unnecessary end() calls.
31925 if (!state.ending && !state.finished) endWritable(this, state, cb);
31926};
31927
31928function needFinish(state) {
31929 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
31930}
31931function callFinal(stream, state) {
31932 stream._final(function (err) {
31933 state.pendingcb--;
31934 if (err) {
31935 stream.emit('error', err);
31936 }
31937 state.prefinished = true;
31938 stream.emit('prefinish');
31939 finishMaybe(stream, state);
31940 });
31941}
31942function prefinish(stream, state) {
31943 if (!state.prefinished && !state.finalCalled) {
31944 if (typeof stream._final === 'function') {
31945 state.pendingcb++;
31946 state.finalCalled = true;
31947 pna.nextTick(callFinal, stream, state);
31948 } else {
31949 state.prefinished = true;
31950 stream.emit('prefinish');
31951 }
31952 }
31953}
31954
31955function finishMaybe(stream, state) {
31956 var need = needFinish(state);
31957 if (need) {
31958 prefinish(stream, state);
31959 if (state.pendingcb === 0) {
31960 state.finished = true;
31961 stream.emit('finish');
31962 }
31963 }
31964 return need;
31965}
31966
31967function endWritable(stream, state, cb) {
31968 state.ending = true;
31969 finishMaybe(stream, state);
31970 if (cb) {
31971 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
31972 }
31973 state.ended = true;
31974 stream.writable = false;
31975}
31976
31977function onCorkedFinish(corkReq, state, err) {
31978 var entry = corkReq.entry;
31979 corkReq.entry = null;
31980 while (entry) {
31981 var cb = entry.callback;
31982 state.pendingcb--;
31983 cb(err);
31984 entry = entry.next;
31985 }
31986 if (state.corkedRequestsFree) {
31987 state.corkedRequestsFree.next = corkReq;
31988 } else {
31989 state.corkedRequestsFree = corkReq;
31990 }
31991}
31992
31993Object.defineProperty(Writable.prototype, 'destroyed', {
31994 get: function () {
31995 if (this._writableState === undefined) {
31996 return false;
31997 }
31998 return this._writableState.destroyed;
31999 },
32000 set: function (value) {
32001 // we ignore the value if the stream
32002 // has not been initialized yet
32003 if (!this._writableState) {
32004 return;
32005 }
32006
32007 // backward compatibility, the user is explicitly
32008 // managing destroyed
32009 this._writableState.destroyed = value;
32010 }
32011});
32012
32013Writable.prototype.destroy = destroyImpl.destroy;
32014Writable.prototype._undestroy = destroyImpl.undestroy;
32015Writable.prototype._destroy = function (err, cb) {
32016 this.end();
32017 cb(err);
32018};
32019}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
32020},{"./_stream_duplex":185,"./internal/streams/destroy":191,"./internal/streams/stream":192,"_process":174,"core-util-is":79,"inherits":152,"process-nextick-args":173,"safe-buffer":193,"timers":212,"util-deprecate":213}],190:[function(require,module,exports){
32021'use strict';
32022
32023function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
32024
32025var Buffer = require('safe-buffer').Buffer;
32026var util = require('util');
32027
32028function copyBuffer(src, target, offset) {
32029 src.copy(target, offset);
32030}
32031
32032module.exports = function () {
32033 function BufferList() {
32034 _classCallCheck(this, BufferList);
32035
32036 this.head = null;
32037 this.tail = null;
32038 this.length = 0;
32039 }
32040
32041 BufferList.prototype.push = function push(v) {
32042 var entry = { data: v, next: null };
32043 if (this.length > 0) this.tail.next = entry;else this.head = entry;
32044 this.tail = entry;
32045 ++this.length;
32046 };
32047
32048 BufferList.prototype.unshift = function unshift(v) {
32049 var entry = { data: v, next: this.head };
32050 if (this.length === 0) this.tail = entry;
32051 this.head = entry;
32052 ++this.length;
32053 };
32054
32055 BufferList.prototype.shift = function shift() {
32056 if (this.length === 0) return;
32057 var ret = this.head.data;
32058 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
32059 --this.length;
32060 return ret;
32061 };
32062
32063 BufferList.prototype.clear = function clear() {
32064 this.head = this.tail = null;
32065 this.length = 0;
32066 };
32067
32068 BufferList.prototype.join = function join(s) {
32069 if (this.length === 0) return '';
32070 var p = this.head;
32071 var ret = '' + p.data;
32072 while (p = p.next) {
32073 ret += s + p.data;
32074 }return ret;
32075 };
32076
32077 BufferList.prototype.concat = function concat(n) {
32078 if (this.length === 0) return Buffer.alloc(0);
32079 if (this.length === 1) return this.head.data;
32080 var ret = Buffer.allocUnsafe(n >>> 0);
32081 var p = this.head;
32082 var i = 0;
32083 while (p) {
32084 copyBuffer(p.data, ret, i);
32085 i += p.data.length;
32086 p = p.next;
32087 }
32088 return ret;
32089 };
32090
32091 return BufferList;
32092}();
32093
32094if (util && util.inspect && util.inspect.custom) {
32095 module.exports.prototype[util.inspect.custom] = function () {
32096 var obj = util.inspect({ length: this.length });
32097 return this.constructor.name + ' ' + obj;
32098 };
32099}
32100},{"safe-buffer":193,"util":33}],191:[function(require,module,exports){
32101'use strict';
32102
32103/*<replacement>*/
32104
32105var pna = require('process-nextick-args');
32106/*</replacement>*/
32107
32108// undocumented cb() API, needed for core, not for public API
32109function destroy(err, cb) {
32110 var _this = this;
32111
32112 var readableDestroyed = this._readableState && this._readableState.destroyed;
32113 var writableDestroyed = this._writableState && this._writableState.destroyed;
32114
32115 if (readableDestroyed || writableDestroyed) {
32116 if (cb) {
32117 cb(err);
32118 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
32119 pna.nextTick(emitErrorNT, this, err);
32120 }
32121 return this;
32122 }
32123
32124 // we set destroyed to true before firing error callbacks in order
32125 // to make it re-entrance safe in case destroy() is called within callbacks
32126
32127 if (this._readableState) {
32128 this._readableState.destroyed = true;
32129 }
32130
32131 // if this is a duplex stream mark the writable part as destroyed as well
32132 if (this._writableState) {
32133 this._writableState.destroyed = true;
32134 }
32135
32136 this._destroy(err || null, function (err) {
32137 if (!cb && err) {
32138 pna.nextTick(emitErrorNT, _this, err);
32139 if (_this._writableState) {
32140 _this._writableState.errorEmitted = true;
32141 }
32142 } else if (cb) {
32143 cb(err);
32144 }
32145 });
32146
32147 return this;
32148}
32149
32150function undestroy() {
32151 if (this._readableState) {
32152 this._readableState.destroyed = false;
32153 this._readableState.reading = false;
32154 this._readableState.ended = false;
32155 this._readableState.endEmitted = false;
32156 }
32157
32158 if (this._writableState) {
32159 this._writableState.destroyed = false;
32160 this._writableState.ended = false;
32161 this._writableState.ending = false;
32162 this._writableState.finished = false;
32163 this._writableState.errorEmitted = false;
32164 }
32165}
32166
32167function emitErrorNT(self, err) {
32168 self.emit('error', err);
32169}
32170
32171module.exports = {
32172 destroy: destroy,
32173 undestroy: undestroy
32174};
32175},{"process-nextick-args":173}],192:[function(require,module,exports){
32176arguments[4][74][0].apply(exports,arguments)
32177},{"dup":74,"events":120}],193:[function(require,module,exports){
32178/* eslint-disable node/no-deprecated-api */
32179var buffer = require('buffer')
32180var Buffer = buffer.Buffer
32181
32182// alternative to using Object.keys for old browsers
32183function copyProps (src, dst) {
32184 for (var key in src) {
32185 dst[key] = src[key]
32186 }
32187}
32188if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
32189 module.exports = buffer
32190} else {
32191 // Copy properties from require('buffer')
32192 copyProps(buffer, exports)
32193 exports.Buffer = SafeBuffer
32194}
32195
32196function SafeBuffer (arg, encodingOrOffset, length) {
32197 return Buffer(arg, encodingOrOffset, length)
32198}
32199
32200// Copy static methods from Buffer
32201copyProps(Buffer, SafeBuffer)
32202
32203SafeBuffer.from = function (arg, encodingOrOffset, length) {
32204 if (typeof arg === 'number') {
32205 throw new TypeError('Argument must not be a number')
32206 }
32207 return Buffer(arg, encodingOrOffset, length)
32208}
32209
32210SafeBuffer.alloc = function (size, fill, encoding) {
32211 if (typeof size !== 'number') {
32212 throw new TypeError('Argument must be a number')
32213 }
32214 var buf = Buffer(size)
32215 if (fill !== undefined) {
32216 if (typeof encoding === 'string') {
32217 buf.fill(fill, encoding)
32218 } else {
32219 buf.fill(fill)
32220 }
32221 } else {
32222 buf.fill(0)
32223 }
32224 return buf
32225}
32226
32227SafeBuffer.allocUnsafe = function (size) {
32228 if (typeof size !== 'number') {
32229 throw new TypeError('Argument must be a number')
32230 }
32231 return Buffer(size)
32232}
32233
32234SafeBuffer.allocUnsafeSlow = function (size) {
32235 if (typeof size !== 'number') {
32236 throw new TypeError('Argument must be a number')
32237 }
32238 return buffer.SlowBuffer(size)
32239}
32240
32241},{"buffer":77}],194:[function(require,module,exports){
32242// Copyright Joyent, Inc. and other Node contributors.
32243//
32244// Permission is hereby granted, free of charge, to any person obtaining a
32245// copy of this software and associated documentation files (the
32246// "Software"), to deal in the Software without restriction, including
32247// without limitation the rights to use, copy, modify, merge, publish,
32248// distribute, sublicense, and/or sell copies of the Software, and to permit
32249// persons to whom the Software is furnished to do so, subject to the
32250// following conditions:
32251//
32252// The above copyright notice and this permission notice shall be included
32253// in all copies or substantial portions of the Software.
32254//
32255// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
32256// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32257// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
32258// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
32259// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
32260// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
32261// USE OR OTHER DEALINGS IN THE SOFTWARE.
32262
32263'use strict';
32264
32265/*<replacement>*/
32266
32267var Buffer = require('safe-buffer').Buffer;
32268/*</replacement>*/
32269
32270var isEncoding = Buffer.isEncoding || function (encoding) {
32271 encoding = '' + encoding;
32272 switch (encoding && encoding.toLowerCase()) {
32273 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':
32274 return true;
32275 default:
32276 return false;
32277 }
32278};
32279
32280function _normalizeEncoding(enc) {
32281 if (!enc) return 'utf8';
32282 var retried;
32283 while (true) {
32284 switch (enc) {
32285 case 'utf8':
32286 case 'utf-8':
32287 return 'utf8';
32288 case 'ucs2':
32289 case 'ucs-2':
32290 case 'utf16le':
32291 case 'utf-16le':
32292 return 'utf16le';
32293 case 'latin1':
32294 case 'binary':
32295 return 'latin1';
32296 case 'base64':
32297 case 'ascii':
32298 case 'hex':
32299 return enc;
32300 default:
32301 if (retried) return; // undefined
32302 enc = ('' + enc).toLowerCase();
32303 retried = true;
32304 }
32305 }
32306};
32307
32308// Do not cache `Buffer.isEncoding` when checking encoding names as some
32309// modules monkey-patch it to support additional encodings
32310function normalizeEncoding(enc) {
32311 var nenc = _normalizeEncoding(enc);
32312 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
32313 return nenc || enc;
32314}
32315
32316// StringDecoder provides an interface for efficiently splitting a series of
32317// buffers into a series of JS strings without breaking apart multi-byte
32318// characters.
32319exports.StringDecoder = StringDecoder;
32320function StringDecoder(encoding) {
32321 this.encoding = normalizeEncoding(encoding);
32322 var nb;
32323 switch (this.encoding) {
32324 case 'utf16le':
32325 this.text = utf16Text;
32326 this.end = utf16End;
32327 nb = 4;
32328 break;
32329 case 'utf8':
32330 this.fillLast = utf8FillLast;
32331 nb = 4;
32332 break;
32333 case 'base64':
32334 this.text = base64Text;
32335 this.end = base64End;
32336 nb = 3;
32337 break;
32338 default:
32339 this.write = simpleWrite;
32340 this.end = simpleEnd;
32341 return;
32342 }
32343 this.lastNeed = 0;
32344 this.lastTotal = 0;
32345 this.lastChar = Buffer.allocUnsafe(nb);
32346}
32347
32348StringDecoder.prototype.write = function (buf) {
32349 if (buf.length === 0) return '';
32350 var r;
32351 var i;
32352 if (this.lastNeed) {
32353 r = this.fillLast(buf);
32354 if (r === undefined) return '';
32355 i = this.lastNeed;
32356 this.lastNeed = 0;
32357 } else {
32358 i = 0;
32359 }
32360 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
32361 return r || '';
32362};
32363
32364StringDecoder.prototype.end = utf8End;
32365
32366// Returns only complete characters in a Buffer
32367StringDecoder.prototype.text = utf8Text;
32368
32369// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
32370StringDecoder.prototype.fillLast = function (buf) {
32371 if (this.lastNeed <= buf.length) {
32372 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
32373 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
32374 }
32375 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
32376 this.lastNeed -= buf.length;
32377};
32378
32379// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
32380// continuation byte. If an invalid byte is detected, -2 is returned.
32381function utf8CheckByte(byte) {
32382 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;
32383 return byte >> 6 === 0x02 ? -1 : -2;
32384}
32385
32386// Checks at most 3 bytes at the end of a Buffer in order to detect an
32387// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
32388// needed to complete the UTF-8 character (if applicable) are returned.
32389function utf8CheckIncomplete(self, buf, i) {
32390 var j = buf.length - 1;
32391 if (j < i) return 0;
32392 var nb = utf8CheckByte(buf[j]);
32393 if (nb >= 0) {
32394 if (nb > 0) self.lastNeed = nb - 1;
32395 return nb;
32396 }
32397 if (--j < i || nb === -2) return 0;
32398 nb = utf8CheckByte(buf[j]);
32399 if (nb >= 0) {
32400 if (nb > 0) self.lastNeed = nb - 2;
32401 return nb;
32402 }
32403 if (--j < i || nb === -2) return 0;
32404 nb = utf8CheckByte(buf[j]);
32405 if (nb >= 0) {
32406 if (nb > 0) {
32407 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
32408 }
32409 return nb;
32410 }
32411 return 0;
32412}
32413
32414// Validates as many continuation bytes for a multi-byte UTF-8 character as
32415// needed or are available. If we see a non-continuation byte where we expect
32416// one, we "replace" the validated continuation bytes we've seen so far with
32417// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
32418// behavior. The continuation byte check is included three times in the case
32419// where all of the continuation bytes for a character exist in the same buffer.
32420// It is also done this way as a slight performance increase instead of using a
32421// loop.
32422function utf8CheckExtraBytes(self, buf, p) {
32423 if ((buf[0] & 0xC0) !== 0x80) {
32424 self.lastNeed = 0;
32425 return '\ufffd';
32426 }
32427 if (self.lastNeed > 1 && buf.length > 1) {
32428 if ((buf[1] & 0xC0) !== 0x80) {
32429 self.lastNeed = 1;
32430 return '\ufffd';
32431 }
32432 if (self.lastNeed > 2 && buf.length > 2) {
32433 if ((buf[2] & 0xC0) !== 0x80) {
32434 self.lastNeed = 2;
32435 return '\ufffd';
32436 }
32437 }
32438 }
32439}
32440
32441// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
32442function utf8FillLast(buf) {
32443 var p = this.lastTotal - this.lastNeed;
32444 var r = utf8CheckExtraBytes(this, buf, p);
32445 if (r !== undefined) return r;
32446 if (this.lastNeed <= buf.length) {
32447 buf.copy(this.lastChar, p, 0, this.lastNeed);
32448 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
32449 }
32450 buf.copy(this.lastChar, p, 0, buf.length);
32451 this.lastNeed -= buf.length;
32452}
32453
32454// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
32455// partial character, the character's bytes are buffered until the required
32456// number of bytes are available.
32457function utf8Text(buf, i) {
32458 var total = utf8CheckIncomplete(this, buf, i);
32459 if (!this.lastNeed) return buf.toString('utf8', i);
32460 this.lastTotal = total;
32461 var end = buf.length - (total - this.lastNeed);
32462 buf.copy(this.lastChar, 0, end);
32463 return buf.toString('utf8', i, end);
32464}
32465
32466// For UTF-8, a replacement character is added when ending on a partial
32467// character.
32468function utf8End(buf) {
32469 var r = buf && buf.length ? this.write(buf) : '';
32470 if (this.lastNeed) return r + '\ufffd';
32471 return r;
32472}
32473
32474// UTF-16LE typically needs two bytes per character, but even if we have an even
32475// number of bytes available, we need to check if we end on a leading/high
32476// surrogate. In that case, we need to wait for the next two bytes in order to
32477// decode the last character properly.
32478function utf16Text(buf, i) {
32479 if ((buf.length - i) % 2 === 0) {
32480 var r = buf.toString('utf16le', i);
32481 if (r) {
32482 var c = r.charCodeAt(r.length - 1);
32483 if (c >= 0xD800 && c <= 0xDBFF) {
32484 this.lastNeed = 2;
32485 this.lastTotal = 4;
32486 this.lastChar[0] = buf[buf.length - 2];
32487 this.lastChar[1] = buf[buf.length - 1];
32488 return r.slice(0, -1);
32489 }
32490 }
32491 return r;
32492 }
32493 this.lastNeed = 1;
32494 this.lastTotal = 2;
32495 this.lastChar[0] = buf[buf.length - 1];
32496 return buf.toString('utf16le', i, buf.length - 1);
32497}
32498
32499// For UTF-16LE we do not explicitly append special replacement characters if we
32500// end on a partial character, we simply let v8 handle that.
32501function utf16End(buf) {
32502 var r = buf && buf.length ? this.write(buf) : '';
32503 if (this.lastNeed) {
32504 var end = this.lastTotal - this.lastNeed;
32505 return r + this.lastChar.toString('utf16le', 0, end);
32506 }
32507 return r;
32508}
32509
32510function base64Text(buf, i) {
32511 var n = (buf.length - i) % 3;
32512 if (n === 0) return buf.toString('base64', i);
32513 this.lastNeed = 3 - n;
32514 this.lastTotal = 3;
32515 if (n === 1) {
32516 this.lastChar[0] = buf[buf.length - 1];
32517 } else {
32518 this.lastChar[0] = buf[buf.length - 2];
32519 this.lastChar[1] = buf[buf.length - 1];
32520 }
32521 return buf.toString('base64', i, buf.length - n);
32522}
32523
32524function base64End(buf) {
32525 var r = buf && buf.length ? this.write(buf) : '';
32526 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
32527 return r;
32528}
32529
32530// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
32531function simpleWrite(buf) {
32532 return buf.toString(this.encoding);
32533}
32534
32535function simpleEnd(buf) {
32536 return buf && buf.length ? this.write(buf) : '';
32537}
32538},{"safe-buffer":193}],195:[function(require,module,exports){
32539module.exports = require('./readable').PassThrough
32540
32541},{"./readable":196}],196:[function(require,module,exports){
32542exports = module.exports = require('./lib/_stream_readable.js');
32543exports.Stream = exports;
32544exports.Readable = exports;
32545exports.Writable = require('./lib/_stream_writable.js');
32546exports.Duplex = require('./lib/_stream_duplex.js');
32547exports.Transform = require('./lib/_stream_transform.js');
32548exports.PassThrough = require('./lib/_stream_passthrough.js');
32549
32550},{"./lib/_stream_duplex.js":185,"./lib/_stream_passthrough.js":186,"./lib/_stream_readable.js":187,"./lib/_stream_transform.js":188,"./lib/_stream_writable.js":189}],197:[function(require,module,exports){
32551module.exports = require('./readable').Transform
32552
32553},{"./readable":196}],198:[function(require,module,exports){
32554module.exports = require('./lib/_stream_writable.js');
32555
32556},{"./lib/_stream_writable.js":189}],199:[function(require,module,exports){
32557'use strict'
32558var Buffer = require('buffer').Buffer
32559var inherits = require('inherits')
32560var HashBase = require('hash-base')
32561
32562var ARRAY16 = new Array(16)
32563
32564var zl = [
32565 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
32566 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
32567 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
32568 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
32569 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
32570]
32571
32572var zr = [
32573 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
32574 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
32575 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
32576 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
32577 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
32578]
32579
32580var sl = [
32581 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
32582 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
32583 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
32584 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
32585 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
32586]
32587
32588var sr = [
32589 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
32590 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
32591 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
32592 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
32593 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
32594]
32595
32596var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
32597var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]
32598
32599function RIPEMD160 () {
32600 HashBase.call(this, 64)
32601
32602 // state
32603 this._a = 0x67452301
32604 this._b = 0xefcdab89
32605 this._c = 0x98badcfe
32606 this._d = 0x10325476
32607 this._e = 0xc3d2e1f0
32608}
32609
32610inherits(RIPEMD160, HashBase)
32611
32612RIPEMD160.prototype._update = function () {
32613 var words = ARRAY16
32614 for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)
32615
32616 var al = this._a | 0
32617 var bl = this._b | 0
32618 var cl = this._c | 0
32619 var dl = this._d | 0
32620 var el = this._e | 0
32621
32622 var ar = this._a | 0
32623 var br = this._b | 0
32624 var cr = this._c | 0
32625 var dr = this._d | 0
32626 var er = this._e | 0
32627
32628 // computation
32629 for (var i = 0; i < 80; i += 1) {
32630 var tl
32631 var tr
32632 if (i < 16) {
32633 tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
32634 tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
32635 } else if (i < 32) {
32636 tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
32637 tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
32638 } else if (i < 48) {
32639 tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
32640 tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
32641 } else if (i < 64) {
32642 tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
32643 tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
32644 } else { // if (i<80) {
32645 tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
32646 tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
32647 }
32648
32649 al = el
32650 el = dl
32651 dl = rotl(cl, 10)
32652 cl = bl
32653 bl = tl
32654
32655 ar = er
32656 er = dr
32657 dr = rotl(cr, 10)
32658 cr = br
32659 br = tr
32660 }
32661
32662 // update state
32663 var t = (this._b + cl + dr) | 0
32664 this._b = (this._c + dl + er) | 0
32665 this._c = (this._d + el + ar) | 0
32666 this._d = (this._e + al + br) | 0
32667 this._e = (this._a + bl + cr) | 0
32668 this._a = t
32669}
32670
32671RIPEMD160.prototype._digest = function () {
32672 // create padding and handle blocks
32673 this._block[this._blockOffset++] = 0x80
32674 if (this._blockOffset > 56) {
32675 this._block.fill(0, this._blockOffset, 64)
32676 this._update()
32677 this._blockOffset = 0
32678 }
32679
32680 this._block.fill(0, this._blockOffset, 56)
32681 this._block.writeUInt32LE(this._length[0], 56)
32682 this._block.writeUInt32LE(this._length[1], 60)
32683 this._update()
32684
32685 // produce result
32686 var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
32687 buffer.writeInt32LE(this._a, 0)
32688 buffer.writeInt32LE(this._b, 4)
32689 buffer.writeInt32LE(this._c, 8)
32690 buffer.writeInt32LE(this._d, 12)
32691 buffer.writeInt32LE(this._e, 16)
32692 return buffer
32693}
32694
32695function rotl (x, n) {
32696 return (x << n) | (x >>> (32 - n))
32697}
32698
32699function fn1 (a, b, c, d, e, m, k, s) {
32700 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
32701}
32702
32703function fn2 (a, b, c, d, e, m, k, s) {
32704 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
32705}
32706
32707function fn3 (a, b, c, d, e, m, k, s) {
32708 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
32709}
32710
32711function fn4 (a, b, c, d, e, m, k, s) {
32712 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
32713}
32714
32715function fn5 (a, b, c, d, e, m, k, s) {
32716 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
32717}
32718
32719module.exports = RIPEMD160
32720
32721},{"buffer":77,"hash-base":122,"inherits":152}],200:[function(require,module,exports){
32722/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
32723/* eslint-disable node/no-deprecated-api */
32724var buffer = require('buffer')
32725var Buffer = buffer.Buffer
32726
32727// alternative to using Object.keys for old browsers
32728function copyProps (src, dst) {
32729 for (var key in src) {
32730 dst[key] = src[key]
32731 }
32732}
32733if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
32734 module.exports = buffer
32735} else {
32736 // Copy properties from require('buffer')
32737 copyProps(buffer, exports)
32738 exports.Buffer = SafeBuffer
32739}
32740
32741function SafeBuffer (arg, encodingOrOffset, length) {
32742 return Buffer(arg, encodingOrOffset, length)
32743}
32744
32745SafeBuffer.prototype = Object.create(Buffer.prototype)
32746
32747// Copy static methods from Buffer
32748copyProps(Buffer, SafeBuffer)
32749
32750SafeBuffer.from = function (arg, encodingOrOffset, length) {
32751 if (typeof arg === 'number') {
32752 throw new TypeError('Argument must not be a number')
32753 }
32754 return Buffer(arg, encodingOrOffset, length)
32755}
32756
32757SafeBuffer.alloc = function (size, fill, encoding) {
32758 if (typeof size !== 'number') {
32759 throw new TypeError('Argument must be a number')
32760 }
32761 var buf = Buffer(size)
32762 if (fill !== undefined) {
32763 if (typeof encoding === 'string') {
32764 buf.fill(fill, encoding)
32765 } else {
32766 buf.fill(fill)
32767 }
32768 } else {
32769 buf.fill(0)
32770 }
32771 return buf
32772}
32773
32774SafeBuffer.allocUnsafe = function (size) {
32775 if (typeof size !== 'number') {
32776 throw new TypeError('Argument must be a number')
32777 }
32778 return Buffer(size)
32779}
32780
32781SafeBuffer.allocUnsafeSlow = function (size) {
32782 if (typeof size !== 'number') {
32783 throw new TypeError('Argument must be a number')
32784 }
32785 return buffer.SlowBuffer(size)
32786}
32787
32788},{"buffer":77}],201:[function(require,module,exports){
32789(function (process){(function (){
32790/* eslint-disable node/no-deprecated-api */
32791
32792'use strict'
32793
32794var buffer = require('buffer')
32795var Buffer = buffer.Buffer
32796
32797var safer = {}
32798
32799var key
32800
32801for (key in buffer) {
32802 if (!buffer.hasOwnProperty(key)) continue
32803 if (key === 'SlowBuffer' || key === 'Buffer') continue
32804 safer[key] = buffer[key]
32805}
32806
32807var Safer = safer.Buffer = {}
32808for (key in Buffer) {
32809 if (!Buffer.hasOwnProperty(key)) continue
32810 if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
32811 Safer[key] = Buffer[key]
32812}
32813
32814safer.Buffer.prototype = Buffer.prototype
32815
32816if (!Safer.from || Safer.from === Uint8Array.from) {
32817 Safer.from = function (value, encodingOrOffset, length) {
32818 if (typeof value === 'number') {
32819 throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
32820 }
32821 if (value && typeof value.length === 'undefined') {
32822 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
32823 }
32824 return Buffer(value, encodingOrOffset, length)
32825 }
32826}
32827
32828if (!Safer.alloc) {
32829 Safer.alloc = function (size, fill, encoding) {
32830 if (typeof size !== 'number') {
32831 throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
32832 }
32833 if (size < 0 || size >= 2 * (1 << 30)) {
32834 throw new RangeError('The value "' + size + '" is invalid for option "size"')
32835 }
32836 var buf = Buffer(size)
32837 if (!fill || fill.length === 0) {
32838 buf.fill(0)
32839 } else if (typeof encoding === 'string') {
32840 buf.fill(fill, encoding)
32841 } else {
32842 buf.fill(fill)
32843 }
32844 return buf
32845 }
32846}
32847
32848if (!safer.kStringMaxLength) {
32849 try {
32850 safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
32851 } catch (e) {
32852 // we can't determine kStringMaxLength in environments where process.binding
32853 // is unsupported, so let's not set it
32854 }
32855}
32856
32857if (!safer.constants) {
32858 safer.constants = {
32859 MAX_LENGTH: safer.kMaxLength
32860 }
32861 if (safer.kStringMaxLength) {
32862 safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
32863 }
32864}
32865
32866module.exports = safer
32867
32868}).call(this)}).call(this,require('_process'))
32869},{"_process":174,"buffer":77}],202:[function(require,module,exports){
32870var Buffer = require('safe-buffer').Buffer
32871
32872// prototype class for hash functions
32873function Hash (blockSize, finalSize) {
32874 this._block = Buffer.alloc(blockSize)
32875 this._finalSize = finalSize
32876 this._blockSize = blockSize
32877 this._len = 0
32878}
32879
32880Hash.prototype.update = function (data, enc) {
32881 if (typeof data === 'string') {
32882 enc = enc || 'utf8'
32883 data = Buffer.from(data, enc)
32884 }
32885
32886 var block = this._block
32887 var blockSize = this._blockSize
32888 var length = data.length
32889 var accum = this._len
32890
32891 for (var offset = 0; offset < length;) {
32892 var assigned = accum % blockSize
32893 var remainder = Math.min(length - offset, blockSize - assigned)
32894
32895 for (var i = 0; i < remainder; i++) {
32896 block[assigned + i] = data[offset + i]
32897 }
32898
32899 accum += remainder
32900 offset += remainder
32901
32902 if ((accum % blockSize) === 0) {
32903 this._update(block)
32904 }
32905 }
32906
32907 this._len += length
32908 return this
32909}
32910
32911Hash.prototype.digest = function (enc) {
32912 var rem = this._len % this._blockSize
32913
32914 this._block[rem] = 0x80
32915
32916 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
32917 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
32918 this._block.fill(0, rem + 1)
32919
32920 if (rem >= this._finalSize) {
32921 this._update(this._block)
32922 this._block.fill(0)
32923 }
32924
32925 var bits = this._len * 8
32926
32927 // uint32
32928 if (bits <= 0xffffffff) {
32929 this._block.writeUInt32BE(bits, this._blockSize - 4)
32930
32931 // uint64
32932 } else {
32933 var lowBits = (bits & 0xffffffff) >>> 0
32934 var highBits = (bits - lowBits) / 0x100000000
32935
32936 this._block.writeUInt32BE(highBits, this._blockSize - 8)
32937 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
32938 }
32939
32940 this._update(this._block)
32941 var hash = this._hash()
32942
32943 return enc ? hash.toString(enc) : hash
32944}
32945
32946Hash.prototype._update = function () {
32947 throw new Error('_update must be implemented by subclass')
32948}
32949
32950module.exports = Hash
32951
32952},{"safe-buffer":200}],203:[function(require,module,exports){
32953var exports = module.exports = function SHA (algorithm) {
32954 algorithm = algorithm.toLowerCase()
32955
32956 var Algorithm = exports[algorithm]
32957 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
32958
32959 return new Algorithm()
32960}
32961
32962exports.sha = require('./sha')
32963exports.sha1 = require('./sha1')
32964exports.sha224 = require('./sha224')
32965exports.sha256 = require('./sha256')
32966exports.sha384 = require('./sha384')
32967exports.sha512 = require('./sha512')
32968
32969},{"./sha":204,"./sha1":205,"./sha224":206,"./sha256":207,"./sha384":208,"./sha512":209}],204:[function(require,module,exports){
32970/*
32971 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
32972 * in FIPS PUB 180-1
32973 * This source code is derived from sha1.js of the same repository.
32974 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
32975 * operation was added.
32976 */
32977
32978var inherits = require('inherits')
32979var Hash = require('./hash')
32980var Buffer = require('safe-buffer').Buffer
32981
32982var K = [
32983 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
32984]
32985
32986var W = new Array(80)
32987
32988function Sha () {
32989 this.init()
32990 this._w = W
32991
32992 Hash.call(this, 64, 56)
32993}
32994
32995inherits(Sha, Hash)
32996
32997Sha.prototype.init = function () {
32998 this._a = 0x67452301
32999 this._b = 0xefcdab89
33000 this._c = 0x98badcfe
33001 this._d = 0x10325476
33002 this._e = 0xc3d2e1f0
33003
33004 return this
33005}
33006
33007function rotl5 (num) {
33008 return (num << 5) | (num >>> 27)
33009}
33010
33011function rotl30 (num) {
33012 return (num << 30) | (num >>> 2)
33013}
33014
33015function ft (s, b, c, d) {
33016 if (s === 0) return (b & c) | ((~b) & d)
33017 if (s === 2) return (b & c) | (b & d) | (c & d)
33018 return b ^ c ^ d
33019}
33020
33021Sha.prototype._update = function (M) {
33022 var W = this._w
33023
33024 var a = this._a | 0
33025 var b = this._b | 0
33026 var c = this._c | 0
33027 var d = this._d | 0
33028 var e = this._e | 0
33029
33030 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
33031 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
33032
33033 for (var j = 0; j < 80; ++j) {
33034 var s = ~~(j / 20)
33035 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
33036
33037 e = d
33038 d = c
33039 c = rotl30(b)
33040 b = a
33041 a = t
33042 }
33043
33044 this._a = (a + this._a) | 0
33045 this._b = (b + this._b) | 0
33046 this._c = (c + this._c) | 0
33047 this._d = (d + this._d) | 0
33048 this._e = (e + this._e) | 0
33049}
33050
33051Sha.prototype._hash = function () {
33052 var H = Buffer.allocUnsafe(20)
33053
33054 H.writeInt32BE(this._a | 0, 0)
33055 H.writeInt32BE(this._b | 0, 4)
33056 H.writeInt32BE(this._c | 0, 8)
33057 H.writeInt32BE(this._d | 0, 12)
33058 H.writeInt32BE(this._e | 0, 16)
33059
33060 return H
33061}
33062
33063module.exports = Sha
33064
33065},{"./hash":202,"inherits":152,"safe-buffer":200}],205:[function(require,module,exports){
33066/*
33067 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
33068 * in FIPS PUB 180-1
33069 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
33070 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
33071 * Distributed under the BSD License
33072 * See http://pajhome.org.uk/crypt/md5 for details.
33073 */
33074
33075var inherits = require('inherits')
33076var Hash = require('./hash')
33077var Buffer = require('safe-buffer').Buffer
33078
33079var K = [
33080 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
33081]
33082
33083var W = new Array(80)
33084
33085function Sha1 () {
33086 this.init()
33087 this._w = W
33088
33089 Hash.call(this, 64, 56)
33090}
33091
33092inherits(Sha1, Hash)
33093
33094Sha1.prototype.init = function () {
33095 this._a = 0x67452301
33096 this._b = 0xefcdab89
33097 this._c = 0x98badcfe
33098 this._d = 0x10325476
33099 this._e = 0xc3d2e1f0
33100
33101 return this
33102}
33103
33104function rotl1 (num) {
33105 return (num << 1) | (num >>> 31)
33106}
33107
33108function rotl5 (num) {
33109 return (num << 5) | (num >>> 27)
33110}
33111
33112function rotl30 (num) {
33113 return (num << 30) | (num >>> 2)
33114}
33115
33116function ft (s, b, c, d) {
33117 if (s === 0) return (b & c) | ((~b) & d)
33118 if (s === 2) return (b & c) | (b & d) | (c & d)
33119 return b ^ c ^ d
33120}
33121
33122Sha1.prototype._update = function (M) {
33123 var W = this._w
33124
33125 var a = this._a | 0
33126 var b = this._b | 0
33127 var c = this._c | 0
33128 var d = this._d | 0
33129 var e = this._e | 0
33130
33131 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
33132 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
33133
33134 for (var j = 0; j < 80; ++j) {
33135 var s = ~~(j / 20)
33136 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
33137
33138 e = d
33139 d = c
33140 c = rotl30(b)
33141 b = a
33142 a = t
33143 }
33144
33145 this._a = (a + this._a) | 0
33146 this._b = (b + this._b) | 0
33147 this._c = (c + this._c) | 0
33148 this._d = (d + this._d) | 0
33149 this._e = (e + this._e) | 0
33150}
33151
33152Sha1.prototype._hash = function () {
33153 var H = Buffer.allocUnsafe(20)
33154
33155 H.writeInt32BE(this._a | 0, 0)
33156 H.writeInt32BE(this._b | 0, 4)
33157 H.writeInt32BE(this._c | 0, 8)
33158 H.writeInt32BE(this._d | 0, 12)
33159 H.writeInt32BE(this._e | 0, 16)
33160
33161 return H
33162}
33163
33164module.exports = Sha1
33165
33166},{"./hash":202,"inherits":152,"safe-buffer":200}],206:[function(require,module,exports){
33167/**
33168 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
33169 * in FIPS 180-2
33170 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
33171 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
33172 *
33173 */
33174
33175var inherits = require('inherits')
33176var Sha256 = require('./sha256')
33177var Hash = require('./hash')
33178var Buffer = require('safe-buffer').Buffer
33179
33180var W = new Array(64)
33181
33182function Sha224 () {
33183 this.init()
33184
33185 this._w = W // new Array(64)
33186
33187 Hash.call(this, 64, 56)
33188}
33189
33190inherits(Sha224, Sha256)
33191
33192Sha224.prototype.init = function () {
33193 this._a = 0xc1059ed8
33194 this._b = 0x367cd507
33195 this._c = 0x3070dd17
33196 this._d = 0xf70e5939
33197 this._e = 0xffc00b31
33198 this._f = 0x68581511
33199 this._g = 0x64f98fa7
33200 this._h = 0xbefa4fa4
33201
33202 return this
33203}
33204
33205Sha224.prototype._hash = function () {
33206 var H = Buffer.allocUnsafe(28)
33207
33208 H.writeInt32BE(this._a, 0)
33209 H.writeInt32BE(this._b, 4)
33210 H.writeInt32BE(this._c, 8)
33211 H.writeInt32BE(this._d, 12)
33212 H.writeInt32BE(this._e, 16)
33213 H.writeInt32BE(this._f, 20)
33214 H.writeInt32BE(this._g, 24)
33215
33216 return H
33217}
33218
33219module.exports = Sha224
33220
33221},{"./hash":202,"./sha256":207,"inherits":152,"safe-buffer":200}],207:[function(require,module,exports){
33222/**
33223 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
33224 * in FIPS 180-2
33225 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
33226 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
33227 *
33228 */
33229
33230var inherits = require('inherits')
33231var Hash = require('./hash')
33232var Buffer = require('safe-buffer').Buffer
33233
33234var K = [
33235 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
33236 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
33237 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
33238 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
33239 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
33240 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
33241 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
33242 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
33243 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
33244 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
33245 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
33246 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
33247 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
33248 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
33249 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
33250 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
33251]
33252
33253var W = new Array(64)
33254
33255function Sha256 () {
33256 this.init()
33257
33258 this._w = W // new Array(64)
33259
33260 Hash.call(this, 64, 56)
33261}
33262
33263inherits(Sha256, Hash)
33264
33265Sha256.prototype.init = function () {
33266 this._a = 0x6a09e667
33267 this._b = 0xbb67ae85
33268 this._c = 0x3c6ef372
33269 this._d = 0xa54ff53a
33270 this._e = 0x510e527f
33271 this._f = 0x9b05688c
33272 this._g = 0x1f83d9ab
33273 this._h = 0x5be0cd19
33274
33275 return this
33276}
33277
33278function ch (x, y, z) {
33279 return z ^ (x & (y ^ z))
33280}
33281
33282function maj (x, y, z) {
33283 return (x & y) | (z & (x | y))
33284}
33285
33286function sigma0 (x) {
33287 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
33288}
33289
33290function sigma1 (x) {
33291 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
33292}
33293
33294function gamma0 (x) {
33295 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
33296}
33297
33298function gamma1 (x) {
33299 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
33300}
33301
33302Sha256.prototype._update = function (M) {
33303 var W = this._w
33304
33305 var a = this._a | 0
33306 var b = this._b | 0
33307 var c = this._c | 0
33308 var d = this._d | 0
33309 var e = this._e | 0
33310 var f = this._f | 0
33311 var g = this._g | 0
33312 var h = this._h | 0
33313
33314 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
33315 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
33316
33317 for (var j = 0; j < 64; ++j) {
33318 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
33319 var T2 = (sigma0(a) + maj(a, b, c)) | 0
33320
33321 h = g
33322 g = f
33323 f = e
33324 e = (d + T1) | 0
33325 d = c
33326 c = b
33327 b = a
33328 a = (T1 + T2) | 0
33329 }
33330
33331 this._a = (a + this._a) | 0
33332 this._b = (b + this._b) | 0
33333 this._c = (c + this._c) | 0
33334 this._d = (d + this._d) | 0
33335 this._e = (e + this._e) | 0
33336 this._f = (f + this._f) | 0
33337 this._g = (g + this._g) | 0
33338 this._h = (h + this._h) | 0
33339}
33340
33341Sha256.prototype._hash = function () {
33342 var H = Buffer.allocUnsafe(32)
33343
33344 H.writeInt32BE(this._a, 0)
33345 H.writeInt32BE(this._b, 4)
33346 H.writeInt32BE(this._c, 8)
33347 H.writeInt32BE(this._d, 12)
33348 H.writeInt32BE(this._e, 16)
33349 H.writeInt32BE(this._f, 20)
33350 H.writeInt32BE(this._g, 24)
33351 H.writeInt32BE(this._h, 28)
33352
33353 return H
33354}
33355
33356module.exports = Sha256
33357
33358},{"./hash":202,"inherits":152,"safe-buffer":200}],208:[function(require,module,exports){
33359var inherits = require('inherits')
33360var SHA512 = require('./sha512')
33361var Hash = require('./hash')
33362var Buffer = require('safe-buffer').Buffer
33363
33364var W = new Array(160)
33365
33366function Sha384 () {
33367 this.init()
33368 this._w = W
33369
33370 Hash.call(this, 128, 112)
33371}
33372
33373inherits(Sha384, SHA512)
33374
33375Sha384.prototype.init = function () {
33376 this._ah = 0xcbbb9d5d
33377 this._bh = 0x629a292a
33378 this._ch = 0x9159015a
33379 this._dh = 0x152fecd8
33380 this._eh = 0x67332667
33381 this._fh = 0x8eb44a87
33382 this._gh = 0xdb0c2e0d
33383 this._hh = 0x47b5481d
33384
33385 this._al = 0xc1059ed8
33386 this._bl = 0x367cd507
33387 this._cl = 0x3070dd17
33388 this._dl = 0xf70e5939
33389 this._el = 0xffc00b31
33390 this._fl = 0x68581511
33391 this._gl = 0x64f98fa7
33392 this._hl = 0xbefa4fa4
33393
33394 return this
33395}
33396
33397Sha384.prototype._hash = function () {
33398 var H = Buffer.allocUnsafe(48)
33399
33400 function writeInt64BE (h, l, offset) {
33401 H.writeInt32BE(h, offset)
33402 H.writeInt32BE(l, offset + 4)
33403 }
33404
33405 writeInt64BE(this._ah, this._al, 0)
33406 writeInt64BE(this._bh, this._bl, 8)
33407 writeInt64BE(this._ch, this._cl, 16)
33408 writeInt64BE(this._dh, this._dl, 24)
33409 writeInt64BE(this._eh, this._el, 32)
33410 writeInt64BE(this._fh, this._fl, 40)
33411
33412 return H
33413}
33414
33415module.exports = Sha384
33416
33417},{"./hash":202,"./sha512":209,"inherits":152,"safe-buffer":200}],209:[function(require,module,exports){
33418var inherits = require('inherits')
33419var Hash = require('./hash')
33420var Buffer = require('safe-buffer').Buffer
33421
33422var K = [
33423 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
33424 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
33425 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
33426 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
33427 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
33428 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
33429 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
33430 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
33431 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
33432 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
33433 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
33434 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
33435 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
33436 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
33437 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
33438 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
33439 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
33440 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
33441 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
33442 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
33443 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
33444 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
33445 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
33446 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
33447 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
33448 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
33449 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
33450 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
33451 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
33452 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
33453 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
33454 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
33455 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
33456 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
33457 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
33458 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
33459 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
33460 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
33461 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
33462 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
33463]
33464
33465var W = new Array(160)
33466
33467function Sha512 () {
33468 this.init()
33469 this._w = W
33470
33471 Hash.call(this, 128, 112)
33472}
33473
33474inherits(Sha512, Hash)
33475
33476Sha512.prototype.init = function () {
33477 this._ah = 0x6a09e667
33478 this._bh = 0xbb67ae85
33479 this._ch = 0x3c6ef372
33480 this._dh = 0xa54ff53a
33481 this._eh = 0x510e527f
33482 this._fh = 0x9b05688c
33483 this._gh = 0x1f83d9ab
33484 this._hh = 0x5be0cd19
33485
33486 this._al = 0xf3bcc908
33487 this._bl = 0x84caa73b
33488 this._cl = 0xfe94f82b
33489 this._dl = 0x5f1d36f1
33490 this._el = 0xade682d1
33491 this._fl = 0x2b3e6c1f
33492 this._gl = 0xfb41bd6b
33493 this._hl = 0x137e2179
33494
33495 return this
33496}
33497
33498function Ch (x, y, z) {
33499 return z ^ (x & (y ^ z))
33500}
33501
33502function maj (x, y, z) {
33503 return (x & y) | (z & (x | y))
33504}
33505
33506function sigma0 (x, xl) {
33507 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
33508}
33509
33510function sigma1 (x, xl) {
33511 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
33512}
33513
33514function Gamma0 (x, xl) {
33515 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
33516}
33517
33518function Gamma0l (x, xl) {
33519 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
33520}
33521
33522function Gamma1 (x, xl) {
33523 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
33524}
33525
33526function Gamma1l (x, xl) {
33527 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
33528}
33529
33530function getCarry (a, b) {
33531 return (a >>> 0) < (b >>> 0) ? 1 : 0
33532}
33533
33534Sha512.prototype._update = function (M) {
33535 var W = this._w
33536
33537 var ah = this._ah | 0
33538 var bh = this._bh | 0
33539 var ch = this._ch | 0
33540 var dh = this._dh | 0
33541 var eh = this._eh | 0
33542 var fh = this._fh | 0
33543 var gh = this._gh | 0
33544 var hh = this._hh | 0
33545
33546 var al = this._al | 0
33547 var bl = this._bl | 0
33548 var cl = this._cl | 0
33549 var dl = this._dl | 0
33550 var el = this._el | 0
33551 var fl = this._fl | 0
33552 var gl = this._gl | 0
33553 var hl = this._hl | 0
33554
33555 for (var i = 0; i < 32; i += 2) {
33556 W[i] = M.readInt32BE(i * 4)
33557 W[i + 1] = M.readInt32BE(i * 4 + 4)
33558 }
33559 for (; i < 160; i += 2) {
33560 var xh = W[i - 15 * 2]
33561 var xl = W[i - 15 * 2 + 1]
33562 var gamma0 = Gamma0(xh, xl)
33563 var gamma0l = Gamma0l(xl, xh)
33564
33565 xh = W[i - 2 * 2]
33566 xl = W[i - 2 * 2 + 1]
33567 var gamma1 = Gamma1(xh, xl)
33568 var gamma1l = Gamma1l(xl, xh)
33569
33570 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
33571 var Wi7h = W[i - 7 * 2]
33572 var Wi7l = W[i - 7 * 2 + 1]
33573
33574 var Wi16h = W[i - 16 * 2]
33575 var Wi16l = W[i - 16 * 2 + 1]
33576
33577 var Wil = (gamma0l + Wi7l) | 0
33578 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
33579 Wil = (Wil + gamma1l) | 0
33580 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
33581 Wil = (Wil + Wi16l) | 0
33582 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
33583
33584 W[i] = Wih
33585 W[i + 1] = Wil
33586 }
33587
33588 for (var j = 0; j < 160; j += 2) {
33589 Wih = W[j]
33590 Wil = W[j + 1]
33591
33592 var majh = maj(ah, bh, ch)
33593 var majl = maj(al, bl, cl)
33594
33595 var sigma0h = sigma0(ah, al)
33596 var sigma0l = sigma0(al, ah)
33597 var sigma1h = sigma1(eh, el)
33598 var sigma1l = sigma1(el, eh)
33599
33600 // t1 = h + sigma1 + ch + K[j] + W[j]
33601 var Kih = K[j]
33602 var Kil = K[j + 1]
33603
33604 var chh = Ch(eh, fh, gh)
33605 var chl = Ch(el, fl, gl)
33606
33607 var t1l = (hl + sigma1l) | 0
33608 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
33609 t1l = (t1l + chl) | 0
33610 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
33611 t1l = (t1l + Kil) | 0
33612 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
33613 t1l = (t1l + Wil) | 0
33614 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
33615
33616 // t2 = sigma0 + maj
33617 var t2l = (sigma0l + majl) | 0
33618 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
33619
33620 hh = gh
33621 hl = gl
33622 gh = fh
33623 gl = fl
33624 fh = eh
33625 fl = el
33626 el = (dl + t1l) | 0
33627 eh = (dh + t1h + getCarry(el, dl)) | 0
33628 dh = ch
33629 dl = cl
33630 ch = bh
33631 cl = bl
33632 bh = ah
33633 bl = al
33634 al = (t1l + t2l) | 0
33635 ah = (t1h + t2h + getCarry(al, t1l)) | 0
33636 }
33637
33638 this._al = (this._al + al) | 0
33639 this._bl = (this._bl + bl) | 0
33640 this._cl = (this._cl + cl) | 0
33641 this._dl = (this._dl + dl) | 0
33642 this._el = (this._el + el) | 0
33643 this._fl = (this._fl + fl) | 0
33644 this._gl = (this._gl + gl) | 0
33645 this._hl = (this._hl + hl) | 0
33646
33647 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
33648 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
33649 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
33650 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
33651 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
33652 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
33653 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
33654 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
33655}
33656
33657Sha512.prototype._hash = function () {
33658 var H = Buffer.allocUnsafe(64)
33659
33660 function writeInt64BE (h, l, offset) {
33661 H.writeInt32BE(h, offset)
33662 H.writeInt32BE(l, offset + 4)
33663 }
33664
33665 writeInt64BE(this._ah, this._al, 0)
33666 writeInt64BE(this._bh, this._bl, 8)
33667 writeInt64BE(this._ch, this._cl, 16)
33668 writeInt64BE(this._dh, this._dl, 24)
33669 writeInt64BE(this._eh, this._el, 32)
33670 writeInt64BE(this._fh, this._fl, 40)
33671 writeInt64BE(this._gh, this._gl, 48)
33672 writeInt64BE(this._hh, this._hl, 56)
33673
33674 return H
33675}
33676
33677module.exports = Sha512
33678
33679},{"./hash":202,"inherits":152,"safe-buffer":200}],210:[function(require,module,exports){
33680// Copyright Joyent, Inc. and other Node contributors.
33681//
33682// Permission is hereby granted, free of charge, to any person obtaining a
33683// copy of this software and associated documentation files (the
33684// "Software"), to deal in the Software without restriction, including
33685// without limitation the rights to use, copy, modify, merge, publish,
33686// distribute, sublicense, and/or sell copies of the Software, and to permit
33687// persons to whom the Software is furnished to do so, subject to the
33688// following conditions:
33689//
33690// The above copyright notice and this permission notice shall be included
33691// in all copies or substantial portions of the Software.
33692//
33693// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
33694// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33695// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
33696// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
33697// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
33698// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
33699// USE OR OTHER DEALINGS IN THE SOFTWARE.
33700
33701module.exports = Stream;
33702
33703var EE = require('events').EventEmitter;
33704var inherits = require('inherits');
33705
33706inherits(Stream, EE);
33707Stream.Readable = require('readable-stream/readable.js');
33708Stream.Writable = require('readable-stream/writable.js');
33709Stream.Duplex = require('readable-stream/duplex.js');
33710Stream.Transform = require('readable-stream/transform.js');
33711Stream.PassThrough = require('readable-stream/passthrough.js');
33712
33713// Backwards-compat with node 0.4.x
33714Stream.Stream = Stream;
33715
33716
33717
33718// old-style streams. Note that the pipe method (the only relevant
33719// part of this class) is overridden in the Readable class.
33720
33721function Stream() {
33722 EE.call(this);
33723}
33724
33725Stream.prototype.pipe = function(dest, options) {
33726 var source = this;
33727
33728 function ondata(chunk) {
33729 if (dest.writable) {
33730 if (false === dest.write(chunk) && source.pause) {
33731 source.pause();
33732 }
33733 }
33734 }
33735
33736 source.on('data', ondata);
33737
33738 function ondrain() {
33739 if (source.readable && source.resume) {
33740 source.resume();
33741 }
33742 }
33743
33744 dest.on('drain', ondrain);
33745
33746 // If the 'end' option is not supplied, dest.end() will be called when
33747 // source gets the 'end' or 'close' events. Only dest.end() once.
33748 if (!dest._isStdio && (!options || options.end !== false)) {
33749 source.on('end', onend);
33750 source.on('close', onclose);
33751 }
33752
33753 var didOnEnd = false;
33754 function onend() {
33755 if (didOnEnd) return;
33756 didOnEnd = true;
33757
33758 dest.end();
33759 }
33760
33761
33762 function onclose() {
33763 if (didOnEnd) return;
33764 didOnEnd = true;
33765
33766 if (typeof dest.destroy === 'function') dest.destroy();
33767 }
33768
33769 // don't leave dangling pipes when there are errors.
33770 function onerror(er) {
33771 cleanup();
33772 if (EE.listenerCount(this, 'error') === 0) {
33773 throw er; // Unhandled stream error in pipe.
33774 }
33775 }
33776
33777 source.on('error', onerror);
33778 dest.on('error', onerror);
33779
33780 // remove all the event listeners that were added.
33781 function cleanup() {
33782 source.removeListener('data', ondata);
33783 dest.removeListener('drain', ondrain);
33784
33785 source.removeListener('end', onend);
33786 source.removeListener('close', onclose);
33787
33788 source.removeListener('error', onerror);
33789 dest.removeListener('error', onerror);
33790
33791 source.removeListener('end', cleanup);
33792 source.removeListener('close', cleanup);
33793
33794 dest.removeListener('close', cleanup);
33795 }
33796
33797 source.on('end', cleanup);
33798 source.on('close', cleanup);
33799
33800 dest.on('close', cleanup);
33801
33802 dest.emit('pipe', source);
33803
33804 // Allow for unix-like usage: A.pipe(B).pipe(C)
33805 return dest;
33806};
33807
33808},{"events":120,"inherits":152,"readable-stream/duplex.js":184,"readable-stream/passthrough.js":195,"readable-stream/readable.js":196,"readable-stream/transform.js":197,"readable-stream/writable.js":198}],211:[function(require,module,exports){
33809arguments[4][194][0].apply(exports,arguments)
33810},{"dup":194,"safe-buffer":200}],212:[function(require,module,exports){
33811(function (setImmediate,clearImmediate){(function (){
33812var nextTick = require('process/browser.js').nextTick;
33813var apply = Function.prototype.apply;
33814var slice = Array.prototype.slice;
33815var immediateIds = {};
33816var nextImmediateId = 0;
33817
33818// DOM APIs, for completeness
33819
33820exports.setTimeout = function() {
33821 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
33822};
33823exports.setInterval = function() {
33824 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
33825};
33826exports.clearTimeout =
33827exports.clearInterval = function(timeout) { timeout.close(); };
33828
33829function Timeout(id, clearFn) {
33830 this._id = id;
33831 this._clearFn = clearFn;
33832}
33833Timeout.prototype.unref = Timeout.prototype.ref = function() {};
33834Timeout.prototype.close = function() {
33835 this._clearFn.call(window, this._id);
33836};
33837
33838// Does not start the time, just sets up the members needed.
33839exports.enroll = function(item, msecs) {
33840 clearTimeout(item._idleTimeoutId);
33841 item._idleTimeout = msecs;
33842};
33843
33844exports.unenroll = function(item) {
33845 clearTimeout(item._idleTimeoutId);
33846 item._idleTimeout = -1;
33847};
33848
33849exports._unrefActive = exports.active = function(item) {
33850 clearTimeout(item._idleTimeoutId);
33851
33852 var msecs = item._idleTimeout;
33853 if (msecs >= 0) {
33854 item._idleTimeoutId = setTimeout(function onTimeout() {
33855 if (item._onTimeout)
33856 item._onTimeout();
33857 }, msecs);
33858 }
33859};
33860
33861// That's not how node.js implements it but the exposed api is the same.
33862exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
33863 var id = nextImmediateId++;
33864 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
33865
33866 immediateIds[id] = true;
33867
33868 nextTick(function onNextTick() {
33869 if (immediateIds[id]) {
33870 // fn.call() is faster so we optimize for the common use-case
33871 // @see http://jsperf.com/call-apply-segu
33872 if (args) {
33873 fn.apply(null, args);
33874 } else {
33875 fn.call(null);
33876 }
33877 // Prevent ids from leaking
33878 exports.clearImmediate(id);
33879 }
33880 });
33881
33882 return id;
33883};
33884
33885exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
33886 delete immediateIds[id];
33887};
33888}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
33889},{"process/browser.js":174,"timers":212}],213:[function(require,module,exports){
33890(function (global){(function (){
33891
33892/**
33893 * Module exports.
33894 */
33895
33896module.exports = deprecate;
33897
33898/**
33899 * Mark that a method should not be used.
33900 * Returns a modified function which warns once by default.
33901 *
33902 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
33903 *
33904 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
33905 * will throw an Error when invoked.
33906 *
33907 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
33908 * will invoke `console.trace()` instead of `console.error()`.
33909 *
33910 * @param {Function} fn - the function to deprecate
33911 * @param {String} msg - the string to print to the console when `fn` is invoked
33912 * @returns {Function} a new "deprecated" version of `fn`
33913 * @api public
33914 */
33915
33916function deprecate (fn, msg) {
33917 if (config('noDeprecation')) {
33918 return fn;
33919 }
33920
33921 var warned = false;
33922 function deprecated() {
33923 if (!warned) {
33924 if (config('throwDeprecation')) {
33925 throw new Error(msg);
33926 } else if (config('traceDeprecation')) {
33927 console.trace(msg);
33928 } else {
33929 console.warn(msg);
33930 }
33931 warned = true;
33932 }
33933 return fn.apply(this, arguments);
33934 }
33935
33936 return deprecated;
33937}
33938
33939/**
33940 * Checks `localStorage` for boolean values for the given `name`.
33941 *
33942 * @param {String} name
33943 * @returns {Boolean}
33944 * @api private
33945 */
33946
33947function config (name) {
33948 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
33949 try {
33950 if (!global.localStorage) return false;
33951 } catch (_) {
33952 return false;
33953 }
33954 var val = global.localStorage[name];
33955 if (null == val) return false;
33956 return String(val).toLowerCase() === 'true';
33957}
33958
33959}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
33960},{}]},{},[1])(1)
33961});