aboutsummaryrefslogtreecommitdiff
path: root/src/js/nebulas-account.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/js/nebulas-account.js')
-rw-r--r--src/js/nebulas-account.js27697
1 files changed, 27697 insertions, 0 deletions
diff --git a/src/js/nebulas-account.js b/src/js/nebulas-account.js
new file mode 100644
index 0000000..45d8724
--- /dev/null
+++ b/src/js/nebulas-account.js
@@ -0,0 +1,27697 @@
1require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2
3"use strict";
4
5var Buffer = require('safe-buffer').Buffer;
6
7var jsSHA = require('jssha');
8var createKeccakHash = require('keccak');
9var secp256k1 = require('secp256k1');
10var crypto = require('crypto');
11var scrypt = require('scryptsy');
12var RIPEMD160 = require('ripemd160');
13
14var uuid = require('uuid');
15
16var utils = require('./utils.js');
17
18var keccak = function (a, bits) {
19 a = toBuffer(a);
20 if (!bits) bits = 256;
21
22 return createKeccakHash('keccak' + bits).update(a).digest();
23};
24
25var sha3 = function () {
26 var shaObj = new jsSHA("SHA3-256", "HEX");
27 for (var i = 0; i < arguments.length; i++) {
28 var v = toBuffer(arguments[i]);
29 shaObj.update(v.toString("hex"));
30 }
31 return Buffer.from(shaObj.getHash("HEX"), "hex");
32};
33
34var ripemd160 = function () {
35 var ripemd160stream = new RIPEMD160();
36 for (var i = 0; i < arguments.length; i++) {
37 var v = toBuffer(arguments[i]);
38 ripemd160stream.update(v);
39 }
40 return ripemd160stream.digest();
41};
42
43// check if hex string
44var isHexPrefixed = function (str) {
45 if (typeof str !== 'string') {
46 throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + typeof str + ", while checking isHexPrefixed.");
47 }
48
49 return str.slice(0, 2) === '0x';
50};
51
52// returns hex string without 0x
53var stripHexPrefix = function (str) {
54 if (typeof str !== 'string') {
55 return str;
56 }
57 return isHexPrefixed(str) ? str.slice(2) : str;
58};
59
60function isHexString(value, length) {
61 if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
62 return false;
63 }
64
65 if (length && value.length !== 2 + 2 * length) {
66 return false;
67 }
68
69 return true;
70}
71
72// returns hex string from int
73function intToHex(i) {
74 var hex = i.toString(16); // eslint-disable-line
75
76 return '0x' + padToEven(hex);
77}
78
79// returns buffer from int
80function intToBuffer(i) {
81 var hex = intToHex(i);
82
83 return new Buffer(hex.slice(2), 'hex');
84}
85
86// returns a buffer filled with 0
87var zeros = function (bytes) {
88 return Buffer.allocUnsafe(bytes).fill(0);
89};
90
91var padToEven = function (value) {
92 var a = value; // eslint-disable-line
93
94 if (typeof a !== 'string') {
95 throw new Error('padToEven only support string');
96 }
97
98 if (a.length % 2) {
99 a = '0' + a;
100 }
101
102 return a;
103};
104
105// convert value to digit/8 buffer with BigEndian.
106var padToBigEndian = function (value, digit) {
107 value = toBuffer(value);
108 var buff = Buffer.alloc(digit / 8);
109 for (var i = 0; i < value.length; i++) {
110 var start = buff.length - value.length + i;
111 if (start >= 0) {
112 buff[start] = value[i];
113 }
114 }
115 return buff;
116};
117
118// attempts to turn a value to buffer, the input can be buffer, string,number
119var toBuffer = function (v) {
120 /*jshint maxcomplexity:13 */
121 if (!Buffer.isBuffer(v)) {
122 if (Array.isArray(v)) {
123 v = Buffer.from(v);
124 } else if (typeof v === 'string') {
125 if (isHexString(v)) {
126 v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex');
127 } else {
128 v = Buffer.from(v);
129 }
130 } else if (typeof v === 'number') {
131 v = intToBuffer(v);
132 } else if (v === null || v === undefined) {
133 v = Buffer.allocUnsafe(0);
134 } else if (utils.isBigNumber(v)) {
135 // TODO: neb number is a big int, not support if v is decimal, later fix it.
136 v = Buffer.from(padToEven(v.toString(16)), 'hex');
137 } else if (v.toArray) {
138 v = Buffer.from(v.toArray());
139 } else if (v.subarray) {
140 v = Buffer.from(v);
141 } else if (v === null || typeof v === "undefined") {
142 v = Buffer.allocUnsafe(0);
143 } else {
144 throw new Error('invalid type');
145 }
146 }
147 return v;
148};
149
150var bufferToHex = function (buf) {
151 buf = toBuffer(buf);
152 return '0x' + buf.toString('hex');
153};
154
155// convert secp256k1 private key to public key
156var privateToPublic = function (privateKey) {
157 privateKey = toBuffer(privateKey);
158 // skip the type flag and use the X, Y points
159 return secp256k1.publicKeyCreate(privateKey, false).slice(1);
160};
161
162var isValidPublic = function (publicKey, sanitize) {
163 if (publicKey.length === 64) {
164 // Convert to SEC1 for secp256k1
165 return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey]));
166 }
167
168 if (!sanitize) {
169 return false;
170 }
171
172 return secp256k1.publicKeyVerify(publicKey);
173};
174
175// sign transaction hash
176var sign = function (msgHash, privateKey) {
177
178 var sig = secp256k1.sign(toBuffer(msgHash), toBuffer(privateKey));
179 // var ret = {}
180 // ret.r = sig.signature.slice(0, 32)
181 // ret.s = sig.signature.slice(32, 64)
182 // ret.v = sig.recovery
183 return Buffer.concat([toBuffer(sig.signature), toBuffer(sig.recovery)]);
184};
185
186var verify = function (message, signature, publicKey) {
187 signature = signature.slice(0, -1); //remove the sig.recovery byte
188 publicKey = Buffer.concat([toBuffer([0x04]), toBuffer(publicKey)]); //add 0x04 before publicKey
189 return secp256k1.verify(toBuffer(message), toBuffer(signature), toBuffer(publicKey));
190};
191
192var recover = function (message, signature, recovery, compressed) {
193 return secp256k1.recover(toBuffer(message), toBuffer(signature), recovery, compressed);
194};
195
196module.exports = {
197 secp256k1: secp256k1,
198 keccak: keccak,
199 sha3: sha3,
200 ripemd160: ripemd160,
201 crypto: crypto,
202 scrypt: scrypt,
203 uuid: uuid,
204
205 zeros: zeros,
206 isHexPrefixed: isHexPrefixed,
207 padToBigEndian: padToBigEndian,
208 toBuffer: toBuffer,
209 bufferToHex: bufferToHex,
210 privateToPublic: privateToPublic,
211 isValidPublic: isValidPublic,
212 sign: sign,
213 verify: verify,
214 recover: recover
215};
216
217},{"./utils.js":2,"crypto":62,"jssha":110,"keccak":111,"ripemd160":155,"safe-buffer":156,"scryptsy":157,"secp256k1":158,"uuid":175}],2:[function(require,module,exports){
218
219"use strict";
220
221var BigNumber = require('bignumber.js');
222
223var isNull = function (v) {
224 return v === null || typeof v === "undefined";
225};
226
227var isBrowser = function () {
228 return typeof window !== "undefined";
229};
230
231var isBigNumber = function (obj) {
232 return obj instanceof BigNumber || obj && obj.constructor && obj.constructor.name === 'BigNumber';
233};
234
235var isString = function (obj) {
236 return typeof obj === 'string' && obj.constructor === String;
237};
238
239var isObject = function (obj) {
240 return obj !== null && typeof obj === 'object';
241};
242
243var isFunction = function (object) {
244 return typeof object === 'function';
245};
246
247var isNumber = function (object) {
248 return typeof object === 'number';
249};
250
251var toBigNumber = function (number) {
252 number = number || 0;
253 if (isBigNumber(number)) {
254 return number;
255 }
256 if (isString(number) && number.indexOf('0x') === 0) {
257 return new BigNumber(number.replace('0x', ''), 16);
258 }
259 return new BigNumber(number.toString(10), 10);
260};
261
262var toString = function (obj) {
263 if (isString(obj)) {
264 return obj;
265 } else if (isBigNumber(obj)) {
266 return obj.toString(10);
267 } else if (isObject(obj)) {
268 return JSON.stringify(obj);
269 } else {
270 return obj + "";
271 }
272};
273
274// Transform Array-like arguments object to common array.
275var argumentsToArray = function (args) {
276 var len = args.length,
277 resultArray = new Array(len);
278
279 for (var i = 0; i < len; i += 1) {
280 resultArray[i] = args[i];
281 }
282 return resultArray;
283};
284
285// Create object based on provided arrays
286var zipArraysToObject = function (keysArr, valuesArr) {
287 var resultObject = {};
288
289 for (var i = 0; i < keysArr.length; i += 1) {
290 resultObject[keysArr[i]] = valuesArr[i];
291 }
292 return resultObject;
293};
294
295// Function what make overall view for arguments.
296// If arguments was provided separated by commas like "func(arg1 ,arg2)" we create
297// ArgumentsObject and write keys from argsNames and value from args.
298// in case wheare we provide args in object like "func({arg1: value})"
299// we just return that object
300var argumentsToObject = function (keys, args) {
301 var ArgumentsObject = {};
302
303 args = argumentsToArray(args);
304 if (isObject(args[0])) {
305 ArgumentsObject = args[0];
306 } else {
307 ArgumentsObject = zipArraysToObject(keys, args);
308 }
309
310 return ArgumentsObject;
311};
312
313module.exports = {
314 isNull: isNull,
315 isBrowser: isBrowser,
316 isBigNumber: isBigNumber,
317 isString: isString,
318 isObject: isObject,
319 isFunction: isFunction,
320 isNumber: isNumber,
321 toBigNumber: toBigNumber,
322 toString: toString,
323 argumentsToObject: argumentsToObject,
324 zipArraysToObject: zipArraysToObject
325};
326
327},{"bignumber.js":19}],3:[function(require,module,exports){
328var asn1 = exports;
329
330asn1.bignum = require('bn.js');
331
332asn1.define = require('./asn1/api').define;
333asn1.base = require('./asn1/base');
334asn1.constants = require('./asn1/constants');
335asn1.decoders = require('./asn1/decoders');
336asn1.encoders = require('./asn1/encoders');
337
338},{"./asn1/api":4,"./asn1/base":6,"./asn1/constants":10,"./asn1/decoders":12,"./asn1/encoders":15,"bn.js":21}],4:[function(require,module,exports){
339var asn1 = require('../asn1');
340var inherits = require('inherits');
341
342var api = exports;
343
344api.define = function define(name, body) {
345 return new Entity(name, body);
346};
347
348function Entity(name, body) {
349 this.name = name;
350 this.body = body;
351
352 this.decoders = {};
353 this.encoders = {};
354};
355
356Entity.prototype._createNamed = function createNamed(base) {
357 var named;
358 try {
359 named = require('vm').runInThisContext(
360 '(function ' + this.name + '(entity) {\n' +
361 ' this._initNamed(entity);\n' +
362 '})'
363 );
364 } catch (e) {
365 named = function (entity) {
366 this._initNamed(entity);
367 };
368 }
369 inherits(named, base);
370 named.prototype._initNamed = function initnamed(entity) {
371 base.call(this, entity);
372 };
373
374 return new named(this);
375};
376
377Entity.prototype._getDecoder = function _getDecoder(enc) {
378 enc = enc || 'der';
379 // Lazily create decoder
380 if (!this.decoders.hasOwnProperty(enc))
381 this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
382 return this.decoders[enc];
383};
384
385Entity.prototype.decode = function decode(data, enc, options) {
386 return this._getDecoder(enc).decode(data, options);
387};
388
389Entity.prototype._getEncoder = function _getEncoder(enc) {
390 enc = enc || 'der';
391 // Lazily create encoder
392 if (!this.encoders.hasOwnProperty(enc))
393 this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
394 return this.encoders[enc];
395};
396
397Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
398 return this._getEncoder(enc).encode(data, reporter);
399};
400
401},{"../asn1":3,"inherits":107,"vm":180}],5:[function(require,module,exports){
402var inherits = require('inherits');
403var Reporter = require('../base').Reporter;
404var Buffer = require('buffer').Buffer;
405
406function DecoderBuffer(base, options) {
407 Reporter.call(this, options);
408 if (!Buffer.isBuffer(base)) {
409 this.error('Input not Buffer');
410 return;
411 }
412
413 this.base = base;
414 this.offset = 0;
415 this.length = base.length;
416}
417inherits(DecoderBuffer, Reporter);
418exports.DecoderBuffer = DecoderBuffer;
419
420DecoderBuffer.prototype.save = function save() {
421 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
422};
423
424DecoderBuffer.prototype.restore = function restore(save) {
425 // Return skipped data
426 var res = new DecoderBuffer(this.base);
427 res.offset = save.offset;
428 res.length = this.offset;
429
430 this.offset = save.offset;
431 Reporter.prototype.restore.call(this, save.reporter);
432
433 return res;
434};
435
436DecoderBuffer.prototype.isEmpty = function isEmpty() {
437 return this.offset === this.length;
438};
439
440DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
441 if (this.offset + 1 <= this.length)
442 return this.base.readUInt8(this.offset++, true);
443 else
444 return this.error(fail || 'DecoderBuffer overrun');
445}
446
447DecoderBuffer.prototype.skip = function skip(bytes, fail) {
448 if (!(this.offset + bytes <= this.length))
449 return this.error(fail || 'DecoderBuffer overrun');
450
451 var res = new DecoderBuffer(this.base);
452
453 // Share reporter state
454 res._reporterState = this._reporterState;
455
456 res.offset = this.offset;
457 res.length = this.offset + bytes;
458 this.offset += bytes;
459 return res;
460}
461
462DecoderBuffer.prototype.raw = function raw(save) {
463 return this.base.slice(save ? save.offset : this.offset, this.length);
464}
465
466function EncoderBuffer(value, reporter) {
467 if (Array.isArray(value)) {
468 this.length = 0;
469 this.value = value.map(function(item) {
470 if (!(item instanceof EncoderBuffer))
471 item = new EncoderBuffer(item, reporter);
472 this.length += item.length;
473 return item;
474 }, this);
475 } else if (typeof value === 'number') {
476 if (!(0 <= value && value <= 0xff))
477 return reporter.error('non-byte EncoderBuffer value');
478 this.value = value;
479 this.length = 1;
480 } else if (typeof value === 'string') {
481 this.value = value;
482 this.length = Buffer.byteLength(value);
483 } else if (Buffer.isBuffer(value)) {
484 this.value = value;
485 this.length = value.length;
486 } else {
487 return reporter.error('Unsupported type: ' + typeof value);
488 }
489}
490exports.EncoderBuffer = EncoderBuffer;
491
492EncoderBuffer.prototype.join = function join(out, offset) {
493 if (!out)
494 out = new Buffer(this.length);
495 if (!offset)
496 offset = 0;
497
498 if (this.length === 0)
499 return out;
500
501 if (Array.isArray(this.value)) {
502 this.value.forEach(function(item) {
503 item.join(out, offset);
504 offset += item.length;
505 });
506 } else {
507 if (typeof this.value === 'number')
508 out[offset] = this.value;
509 else if (typeof this.value === 'string')
510 out.write(this.value, offset);
511 else if (Buffer.isBuffer(this.value))
512 this.value.copy(out, offset);
513 offset += this.length;
514 }
515
516 return out;
517};
518
519},{"../base":6,"buffer":53,"inherits":107}],6:[function(require,module,exports){
520var base = exports;
521
522base.Reporter = require('./reporter').Reporter;
523base.DecoderBuffer = require('./buffer').DecoderBuffer;
524base.EncoderBuffer = require('./buffer').EncoderBuffer;
525base.Node = require('./node');
526
527},{"./buffer":5,"./node":7,"./reporter":8}],7:[function(require,module,exports){
528var Reporter = require('../base').Reporter;
529var EncoderBuffer = require('../base').EncoderBuffer;
530var DecoderBuffer = require('../base').DecoderBuffer;
531var assert = require('minimalistic-assert');
532
533// Supported tags
534var tags = [
535 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
536 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
537 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
538 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
539];
540
541// Public methods list
542var methods = [
543 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
544 'any', 'contains'
545].concat(tags);
546
547// Overrided methods list
548var overrided = [
549 '_peekTag', '_decodeTag', '_use',
550 '_decodeStr', '_decodeObjid', '_decodeTime',
551 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
552
553 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
554 '_encodeNull', '_encodeInt', '_encodeBool'
555];
556
557function Node(enc, parent) {
558 var state = {};
559 this._baseState = state;
560
561 state.enc = enc;
562
563 state.parent = parent || null;
564 state.children = null;
565
566 // State
567 state.tag = null;
568 state.args = null;
569 state.reverseArgs = null;
570 state.choice = null;
571 state.optional = false;
572 state.any = false;
573 state.obj = false;
574 state.use = null;
575 state.useDecoder = null;
576 state.key = null;
577 state['default'] = null;
578 state.explicit = null;
579 state.implicit = null;
580 state.contains = null;
581
582 // Should create new instance on each method
583 if (!state.parent) {
584 state.children = [];
585 this._wrap();
586 }
587}
588module.exports = Node;
589
590var stateProps = [
591 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
592 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
593 'implicit', 'contains'
594];
595
596Node.prototype.clone = function clone() {
597 var state = this._baseState;
598 var cstate = {};
599 stateProps.forEach(function(prop) {
600 cstate[prop] = state[prop];
601 });
602 var res = new this.constructor(cstate.parent);
603 res._baseState = cstate;
604 return res;
605};
606
607Node.prototype._wrap = function wrap() {
608 var state = this._baseState;
609 methods.forEach(function(method) {
610 this[method] = function _wrappedMethod() {
611 var clone = new this.constructor(this);
612 state.children.push(clone);
613 return clone[method].apply(clone, arguments);
614 };
615 }, this);
616};
617
618Node.prototype._init = function init(body) {
619 var state = this._baseState;
620
621 assert(state.parent === null);
622 body.call(this);
623
624 // Filter children
625 state.children = state.children.filter(function(child) {
626 return child._baseState.parent === this;
627 }, this);
628 assert.equal(state.children.length, 1, 'Root node can have only one child');
629};
630
631Node.prototype._useArgs = function useArgs(args) {
632 var state = this._baseState;
633
634 // Filter children and args
635 var children = args.filter(function(arg) {
636 return arg instanceof this.constructor;
637 }, this);
638 args = args.filter(function(arg) {
639 return !(arg instanceof this.constructor);
640 }, this);
641
642 if (children.length !== 0) {
643 assert(state.children === null);
644 state.children = children;
645
646 // Replace parent to maintain backward link
647 children.forEach(function(child) {
648 child._baseState.parent = this;
649 }, this);
650 }
651 if (args.length !== 0) {
652 assert(state.args === null);
653 state.args = args;
654 state.reverseArgs = args.map(function(arg) {
655 if (typeof arg !== 'object' || arg.constructor !== Object)
656 return arg;
657
658 var res = {};
659 Object.keys(arg).forEach(function(key) {
660 if (key == (key | 0))
661 key |= 0;
662 var value = arg[key];
663 res[value] = key;
664 });
665 return res;
666 });
667 }
668};
669
670//
671// Overrided methods
672//
673
674overrided.forEach(function(method) {
675 Node.prototype[method] = function _overrided() {
676 var state = this._baseState;
677 throw new Error(method + ' not implemented for encoding: ' + state.enc);
678 };
679});
680
681//
682// Public methods
683//
684
685tags.forEach(function(tag) {
686 Node.prototype[tag] = function _tagMethod() {
687 var state = this._baseState;
688 var args = Array.prototype.slice.call(arguments);
689
690 assert(state.tag === null);
691 state.tag = tag;
692
693 this._useArgs(args);
694
695 return this;
696 };
697});
698
699Node.prototype.use = function use(item) {
700 assert(item);
701 var state = this._baseState;
702
703 assert(state.use === null);
704 state.use = item;
705
706 return this;
707};
708
709Node.prototype.optional = function optional() {
710 var state = this._baseState;
711
712 state.optional = true;
713
714 return this;
715};
716
717Node.prototype.def = function def(val) {
718 var state = this._baseState;
719
720 assert(state['default'] === null);
721 state['default'] = val;
722 state.optional = true;
723
724 return this;
725};
726
727Node.prototype.explicit = function explicit(num) {
728 var state = this._baseState;
729
730 assert(state.explicit === null && state.implicit === null);
731 state.explicit = num;
732
733 return this;
734};
735
736Node.prototype.implicit = function implicit(num) {
737 var state = this._baseState;
738
739 assert(state.explicit === null && state.implicit === null);
740 state.implicit = num;
741
742 return this;
743};
744
745Node.prototype.obj = function obj() {
746 var state = this._baseState;
747 var args = Array.prototype.slice.call(arguments);
748
749 state.obj = true;
750
751 if (args.length !== 0)
752 this._useArgs(args);
753
754 return this;
755};
756
757Node.prototype.key = function key(newKey) {
758 var state = this._baseState;
759
760 assert(state.key === null);
761 state.key = newKey;
762
763 return this;
764};
765
766Node.prototype.any = function any() {
767 var state = this._baseState;
768
769 state.any = true;
770
771 return this;
772};
773
774Node.prototype.choice = function choice(obj) {
775 var state = this._baseState;
776
777 assert(state.choice === null);
778 state.choice = obj;
779 this._useArgs(Object.keys(obj).map(function(key) {
780 return obj[key];
781 }));
782
783 return this;
784};
785
786Node.prototype.contains = function contains(item) {
787 var state = this._baseState;
788
789 assert(state.use === null);
790 state.contains = item;
791
792 return this;
793};
794
795//
796// Decoding
797//
798
799Node.prototype._decode = function decode(input, options) {
800 var state = this._baseState;
801
802 // Decode root node
803 if (state.parent === null)
804 return input.wrapResult(state.children[0]._decode(input, options));
805
806 var result = state['default'];
807 var present = true;
808
809 var prevKey = null;
810 if (state.key !== null)
811 prevKey = input.enterKey(state.key);
812
813 // Check if tag is there
814 if (state.optional) {
815 var tag = null;
816 if (state.explicit !== null)
817 tag = state.explicit;
818 else if (state.implicit !== null)
819 tag = state.implicit;
820 else if (state.tag !== null)
821 tag = state.tag;
822
823 if (tag === null && !state.any) {
824 // Trial and Error
825 var save = input.save();
826 try {
827 if (state.choice === null)
828 this._decodeGeneric(state.tag, input, options);
829 else
830 this._decodeChoice(input, options);
831 present = true;
832 } catch (e) {
833 present = false;
834 }
835 input.restore(save);
836 } else {
837 present = this._peekTag(input, tag, state.any);
838
839 if (input.isError(present))
840 return present;
841 }
842 }
843
844 // Push object on stack
845 var prevObj;
846 if (state.obj && present)
847 prevObj = input.enterObject();
848
849 if (present) {
850 // Unwrap explicit values
851 if (state.explicit !== null) {
852 var explicit = this._decodeTag(input, state.explicit);
853 if (input.isError(explicit))
854 return explicit;
855 input = explicit;
856 }
857
858 var start = input.offset;
859
860 // Unwrap implicit and normal values
861 if (state.use === null && state.choice === null) {
862 if (state.any)
863 var save = input.save();
864 var body = this._decodeTag(
865 input,
866 state.implicit !== null ? state.implicit : state.tag,
867 state.any
868 );
869 if (input.isError(body))
870 return body;
871
872 if (state.any)
873 result = input.raw(save);
874 else
875 input = body;
876 }
877
878 if (options && options.track && state.tag !== null)
879 options.track(input.path(), start, input.length, 'tagged');
880
881 if (options && options.track && state.tag !== null)
882 options.track(input.path(), input.offset, input.length, 'content');
883
884 // Select proper method for tag
885 if (state.any)
886 result = result;
887 else if (state.choice === null)
888 result = this._decodeGeneric(state.tag, input, options);
889 else
890 result = this._decodeChoice(input, options);
891
892 if (input.isError(result))
893 return result;
894
895 // Decode children
896 if (!state.any && state.choice === null && state.children !== null) {
897 state.children.forEach(function decodeChildren(child) {
898 // NOTE: We are ignoring errors here, to let parser continue with other
899 // parts of encoded data
900 child._decode(input, options);
901 });
902 }
903
904 // Decode contained/encoded by schema, only in bit or octet strings
905 if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
906 var data = new DecoderBuffer(result);
907 result = this._getUse(state.contains, input._reporterState.obj)
908 ._decode(data, options);
909 }
910 }
911
912 // Pop object
913 if (state.obj && present)
914 result = input.leaveObject(prevObj);
915
916 // Set key
917 if (state.key !== null && (result !== null || present === true))
918 input.leaveKey(prevKey, state.key, result);
919 else if (prevKey !== null)
920 input.exitKey(prevKey);
921
922 return result;
923};
924
925Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
926 var state = this._baseState;
927
928 if (tag === 'seq' || tag === 'set')
929 return null;
930 if (tag === 'seqof' || tag === 'setof')
931 return this._decodeList(input, tag, state.args[0], options);
932 else if (/str$/.test(tag))
933 return this._decodeStr(input, tag, options);
934 else if (tag === 'objid' && state.args)
935 return this._decodeObjid(input, state.args[0], state.args[1], options);
936 else if (tag === 'objid')
937 return this._decodeObjid(input, null, null, options);
938 else if (tag === 'gentime' || tag === 'utctime')
939 return this._decodeTime(input, tag, options);
940 else if (tag === 'null_')
941 return this._decodeNull(input, options);
942 else if (tag === 'bool')
943 return this._decodeBool(input, options);
944 else if (tag === 'objDesc')
945 return this._decodeStr(input, tag, options);
946 else if (tag === 'int' || tag === 'enum')
947 return this._decodeInt(input, state.args && state.args[0], options);
948
949 if (state.use !== null) {
950 return this._getUse(state.use, input._reporterState.obj)
951 ._decode(input, options);
952 } else {
953 return input.error('unknown tag: ' + tag);
954 }
955};
956
957Node.prototype._getUse = function _getUse(entity, obj) {
958
959 var state = this._baseState;
960 // Create altered use decoder if implicit is set
961 state.useDecoder = this._use(entity, obj);
962 assert(state.useDecoder._baseState.parent === null);
963 state.useDecoder = state.useDecoder._baseState.children[0];
964 if (state.implicit !== state.useDecoder._baseState.implicit) {
965 state.useDecoder = state.useDecoder.clone();
966 state.useDecoder._baseState.implicit = state.implicit;
967 }
968 return state.useDecoder;
969};
970
971Node.prototype._decodeChoice = function decodeChoice(input, options) {
972 var state = this._baseState;
973 var result = null;
974 var match = false;
975
976 Object.keys(state.choice).some(function(key) {
977 var save = input.save();
978 var node = state.choice[key];
979 try {
980 var value = node._decode(input, options);
981 if (input.isError(value))
982 return false;
983
984 result = { type: key, value: value };
985 match = true;
986 } catch (e) {
987 input.restore(save);
988 return false;
989 }
990 return true;
991 }, this);
992
993 if (!match)
994 return input.error('Choice not matched');
995
996 return result;
997};
998
999//
1000// Encoding
1001//
1002
1003Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
1004 return new EncoderBuffer(data, this.reporter);
1005};
1006
1007Node.prototype._encode = function encode(data, reporter, parent) {
1008 var state = this._baseState;
1009 if (state['default'] !== null && state['default'] === data)
1010 return;
1011
1012 var result = this._encodeValue(data, reporter, parent);
1013 if (result === undefined)
1014 return;
1015
1016 if (this._skipDefault(result, reporter, parent))
1017 return;
1018
1019 return result;
1020};
1021
1022Node.prototype._encodeValue = function encode(data, reporter, parent) {
1023 var state = this._baseState;
1024
1025 // Decode root node
1026 if (state.parent === null)
1027 return state.children[0]._encode(data, reporter || new Reporter());
1028
1029 var result = null;
1030
1031 // Set reporter to share it with a child class
1032 this.reporter = reporter;
1033
1034 // Check if data is there
1035 if (state.optional && data === undefined) {
1036 if (state['default'] !== null)
1037 data = state['default']
1038 else
1039 return;
1040 }
1041
1042 // Encode children first
1043 var content = null;
1044 var primitive = false;
1045 if (state.any) {
1046 // Anything that was given is translated to buffer
1047 result = this._createEncoderBuffer(data);
1048 } else if (state.choice) {
1049 result = this._encodeChoice(data, reporter);
1050 } else if (state.contains) {
1051 content = this._getUse(state.contains, parent)._encode(data, reporter);
1052 primitive = true;
1053 } else if (state.children) {
1054 content = state.children.map(function(child) {
1055 if (child._baseState.tag === 'null_')
1056 return child._encode(null, reporter, data);
1057
1058 if (child._baseState.key === null)
1059 return reporter.error('Child should have a key');
1060 var prevKey = reporter.enterKey(child._baseState.key);
1061
1062 if (typeof data !== 'object')
1063 return reporter.error('Child expected, but input is not object');
1064
1065 var res = child._encode(data[child._baseState.key], reporter, data);
1066 reporter.leaveKey(prevKey);
1067
1068 return res;
1069 }, this).filter(function(child) {
1070 return child;
1071 });
1072 content = this._createEncoderBuffer(content);
1073 } else {
1074 if (state.tag === 'seqof' || state.tag === 'setof') {
1075 // TODO(indutny): this should be thrown on DSL level
1076 if (!(state.args && state.args.length === 1))
1077 return reporter.error('Too many args for : ' + state.tag);
1078
1079 if (!Array.isArray(data))
1080 return reporter.error('seqof/setof, but data is not Array');
1081
1082 var child = this.clone();
1083 child._baseState.implicit = null;
1084 content = this._createEncoderBuffer(data.map(function(item) {
1085 var state = this._baseState;
1086
1087 return this._getUse(state.args[0], data)._encode(item, reporter);
1088 }, child));
1089 } else if (state.use !== null) {
1090 result = this._getUse(state.use, parent)._encode(data, reporter);
1091 } else {
1092 content = this._encodePrimitive(state.tag, data);
1093 primitive = true;
1094 }
1095 }
1096
1097 // Encode data itself
1098 var result;
1099 if (!state.any && state.choice === null) {
1100 var tag = state.implicit !== null ? state.implicit : state.tag;
1101 var cls = state.implicit === null ? 'universal' : 'context';
1102
1103 if (tag === null) {
1104 if (state.use === null)
1105 reporter.error('Tag could be omitted only for .use()');
1106 } else {
1107 if (state.use === null)
1108 result = this._encodeComposite(tag, primitive, cls, content);
1109 }
1110 }
1111
1112 // Wrap in explicit
1113 if (state.explicit !== null)
1114 result = this._encodeComposite(state.explicit, false, 'context', result);
1115
1116 return result;
1117};
1118
1119Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
1120 var state = this._baseState;
1121
1122 var node = state.choice[data.type];
1123 if (!node) {
1124 assert(
1125 false,
1126 data.type + ' not found in ' +
1127 JSON.stringify(Object.keys(state.choice)));
1128 }
1129 return node._encode(data.value, reporter);
1130};
1131
1132Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
1133 var state = this._baseState;
1134
1135 if (/str$/.test(tag))
1136 return this._encodeStr(data, tag);
1137 else if (tag === 'objid' && state.args)
1138 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
1139 else if (tag === 'objid')
1140 return this._encodeObjid(data, null, null);
1141 else if (tag === 'gentime' || tag === 'utctime')
1142 return this._encodeTime(data, tag);
1143 else if (tag === 'null_')
1144 return this._encodeNull();
1145 else if (tag === 'int' || tag === 'enum')
1146 return this._encodeInt(data, state.args && state.reverseArgs[0]);
1147 else if (tag === 'bool')
1148 return this._encodeBool(data);
1149 else if (tag === 'objDesc')
1150 return this._encodeStr(data, tag);
1151 else
1152 throw new Error('Unsupported tag: ' + tag);
1153};
1154
1155Node.prototype._isNumstr = function isNumstr(str) {
1156 return /^[0-9 ]*$/.test(str);
1157};
1158
1159Node.prototype._isPrintstr = function isPrintstr(str) {
1160 return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
1161};
1162
1163},{"../base":6,"minimalistic-assert":120}],8:[function(require,module,exports){
1164var inherits = require('inherits');
1165
1166function Reporter(options) {
1167 this._reporterState = {
1168 obj: null,
1169 path: [],
1170 options: options || {},
1171 errors: []
1172 };
1173}
1174exports.Reporter = Reporter;
1175
1176Reporter.prototype.isError = function isError(obj) {
1177 return obj instanceof ReporterError;
1178};
1179
1180Reporter.prototype.save = function save() {
1181 var state = this._reporterState;
1182
1183 return { obj: state.obj, pathLen: state.path.length };
1184};
1185
1186Reporter.prototype.restore = function restore(data) {
1187 var state = this._reporterState;
1188
1189 state.obj = data.obj;
1190 state.path = state.path.slice(0, data.pathLen);
1191};
1192
1193Reporter.prototype.enterKey = function enterKey(key) {
1194 return this._reporterState.path.push(key);
1195};
1196
1197Reporter.prototype.exitKey = function exitKey(index) {
1198 var state = this._reporterState;
1199
1200 state.path = state.path.slice(0, index - 1);
1201};
1202
1203Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
1204 var state = this._reporterState;
1205
1206 this.exitKey(index);
1207 if (state.obj !== null)
1208 state.obj[key] = value;
1209};
1210
1211Reporter.prototype.path = function path() {
1212 return this._reporterState.path.join('/');
1213};
1214
1215Reporter.prototype.enterObject = function enterObject() {
1216 var state = this._reporterState;
1217
1218 var prev = state.obj;
1219 state.obj = {};
1220 return prev;
1221};
1222
1223Reporter.prototype.leaveObject = function leaveObject(prev) {
1224 var state = this._reporterState;
1225
1226 var now = state.obj;
1227 state.obj = prev;
1228 return now;
1229};
1230
1231Reporter.prototype.error = function error(msg) {
1232 var err;
1233 var state = this._reporterState;
1234
1235 var inherited = msg instanceof ReporterError;
1236 if (inherited) {
1237 err = msg;
1238 } else {
1239 err = new ReporterError(state.path.map(function(elem) {
1240 return '[' + JSON.stringify(elem) + ']';
1241 }).join(''), msg.message || msg, msg.stack);
1242 }
1243
1244 if (!state.options.partial)
1245 throw err;
1246
1247 if (!inherited)
1248 state.errors.push(err);
1249
1250 return err;
1251};
1252
1253Reporter.prototype.wrapResult = function wrapResult(result) {
1254 var state = this._reporterState;
1255 if (!state.options.partial)
1256 return result;
1257
1258 return {
1259 result: this.isError(result) ? null : result,
1260 errors: state.errors
1261 };
1262};
1263
1264function ReporterError(path, msg) {
1265 this.path = path;
1266 this.rethrow(msg);
1267};
1268inherits(ReporterError, Error);
1269
1270ReporterError.prototype.rethrow = function rethrow(msg) {
1271 this.message = msg + ' at: ' + (this.path || '(shallow)');
1272 if (Error.captureStackTrace)
1273 Error.captureStackTrace(this, ReporterError);
1274
1275 if (!this.stack) {
1276 try {
1277 // IE only adds stack when thrown
1278 throw new Error(this.message);
1279 } catch (e) {
1280 this.stack = e.stack;
1281 }
1282 }
1283 return this;
1284};
1285
1286},{"inherits":107}],9:[function(require,module,exports){
1287var constants = require('../constants');
1288
1289exports.tagClass = {
1290 0: 'universal',
1291 1: 'application',
1292 2: 'context',
1293 3: 'private'
1294};
1295exports.tagClassByName = constants._reverse(exports.tagClass);
1296
1297exports.tag = {
1298 0x00: 'end',
1299 0x01: 'bool',
1300 0x02: 'int',
1301 0x03: 'bitstr',
1302 0x04: 'octstr',
1303 0x05: 'null_',
1304 0x06: 'objid',
1305 0x07: 'objDesc',
1306 0x08: 'external',
1307 0x09: 'real',
1308 0x0a: 'enum',
1309 0x0b: 'embed',
1310 0x0c: 'utf8str',
1311 0x0d: 'relativeOid',
1312 0x10: 'seq',
1313 0x11: 'set',
1314 0x12: 'numstr',
1315 0x13: 'printstr',
1316 0x14: 't61str',
1317 0x15: 'videostr',
1318 0x16: 'ia5str',
1319 0x17: 'utctime',
1320 0x18: 'gentime',
1321 0x19: 'graphstr',
1322 0x1a: 'iso646str',
1323 0x1b: 'genstr',
1324 0x1c: 'unistr',
1325 0x1d: 'charstr',
1326 0x1e: 'bmpstr'
1327};
1328exports.tagByName = constants._reverse(exports.tag);
1329
1330},{"../constants":10}],10:[function(require,module,exports){
1331var constants = exports;
1332
1333// Helper
1334constants._reverse = function reverse(map) {
1335 var res = {};
1336
1337 Object.keys(map).forEach(function(key) {
1338 // Convert key to integer if it is stringified
1339 if ((key | 0) == key)
1340 key = key | 0;
1341
1342 var value = map[key];
1343 res[value] = key;
1344 });
1345
1346 return res;
1347};
1348
1349constants.der = require('./der');
1350
1351},{"./der":9}],11:[function(require,module,exports){
1352var inherits = require('inherits');
1353
1354var asn1 = require('../../asn1');
1355var base = asn1.base;
1356var bignum = asn1.bignum;
1357
1358// Import DER constants
1359var der = asn1.constants.der;
1360
1361function DERDecoder(entity) {
1362 this.enc = 'der';
1363 this.name = entity.name;
1364 this.entity = entity;
1365
1366 // Construct base tree
1367 this.tree = new DERNode();
1368 this.tree._init(entity.body);
1369};
1370module.exports = DERDecoder;
1371
1372DERDecoder.prototype.decode = function decode(data, options) {
1373 if (!(data instanceof base.DecoderBuffer))
1374 data = new base.DecoderBuffer(data, options);
1375
1376 return this.tree._decode(data, options);
1377};
1378
1379// Tree methods
1380
1381function DERNode(parent) {
1382 base.Node.call(this, 'der', parent);
1383}
1384inherits(DERNode, base.Node);
1385
1386DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
1387 if (buffer.isEmpty())
1388 return false;
1389
1390 var state = buffer.save();
1391 var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
1392 if (buffer.isError(decodedTag))
1393 return decodedTag;
1394
1395 buffer.restore(state);
1396
1397 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
1398 (decodedTag.tagStr + 'of') === tag || any;
1399};
1400
1401DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
1402 var decodedTag = derDecodeTag(buffer,
1403 'Failed to decode tag of "' + tag + '"');
1404 if (buffer.isError(decodedTag))
1405 return decodedTag;
1406
1407 var len = derDecodeLen(buffer,
1408 decodedTag.primitive,
1409 'Failed to get length of "' + tag + '"');
1410
1411 // Failure
1412 if (buffer.isError(len))
1413 return len;
1414
1415 if (!any &&
1416 decodedTag.tag !== tag &&
1417 decodedTag.tagStr !== tag &&
1418 decodedTag.tagStr + 'of' !== tag) {
1419 return buffer.error('Failed to match tag: "' + tag + '"');
1420 }
1421
1422 if (decodedTag.primitive || len !== null)
1423 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
1424
1425 // Indefinite length... find END tag
1426 var state = buffer.save();
1427 var res = this._skipUntilEnd(
1428 buffer,
1429 'Failed to skip indefinite length body: "' + this.tag + '"');
1430 if (buffer.isError(res))
1431 return res;
1432
1433 len = buffer.offset - state.offset;
1434 buffer.restore(state);
1435 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
1436};
1437
1438DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
1439 while (true) {
1440 var tag = derDecodeTag(buffer, fail);
1441 if (buffer.isError(tag))
1442 return tag;
1443 var len = derDecodeLen(buffer, tag.primitive, fail);
1444 if (buffer.isError(len))
1445 return len;
1446
1447 var res;
1448 if (tag.primitive || len !== null)
1449 res = buffer.skip(len)
1450 else
1451 res = this._skipUntilEnd(buffer, fail);
1452
1453 // Failure
1454 if (buffer.isError(res))
1455 return res;
1456
1457 if (tag.tagStr === 'end')
1458 break;
1459 }
1460};
1461
1462DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
1463 options) {
1464 var result = [];
1465 while (!buffer.isEmpty()) {
1466 var possibleEnd = this._peekTag(buffer, 'end');
1467 if (buffer.isError(possibleEnd))
1468 return possibleEnd;
1469
1470 var res = decoder.decode(buffer, 'der', options);
1471 if (buffer.isError(res) && possibleEnd)
1472 break;
1473 result.push(res);
1474 }
1475 return result;
1476};
1477
1478DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
1479 if (tag === 'bitstr') {
1480 var unused = buffer.readUInt8();
1481 if (buffer.isError(unused))
1482 return unused;
1483 return { unused: unused, data: buffer.raw() };
1484 } else if (tag === 'bmpstr') {
1485 var raw = buffer.raw();
1486 if (raw.length % 2 === 1)
1487 return buffer.error('Decoding of string type: bmpstr length mismatch');
1488
1489 var str = '';
1490 for (var i = 0; i < raw.length / 2; i++) {
1491 str += String.fromCharCode(raw.readUInt16BE(i * 2));
1492 }
1493 return str;
1494 } else if (tag === 'numstr') {
1495 var numstr = buffer.raw().toString('ascii');
1496 if (!this._isNumstr(numstr)) {
1497 return buffer.error('Decoding of string type: ' +
1498 'numstr unsupported characters');
1499 }
1500 return numstr;
1501 } else if (tag === 'octstr') {
1502 return buffer.raw();
1503 } else if (tag === 'objDesc') {
1504 return buffer.raw();
1505 } else if (tag === 'printstr') {
1506 var printstr = buffer.raw().toString('ascii');
1507 if (!this._isPrintstr(printstr)) {
1508 return buffer.error('Decoding of string type: ' +
1509 'printstr unsupported characters');
1510 }
1511 return printstr;
1512 } else if (/str$/.test(tag)) {
1513 return buffer.raw().toString();
1514 } else {
1515 return buffer.error('Decoding of string type: ' + tag + ' unsupported');
1516 }
1517};
1518
1519DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
1520 var result;
1521 var identifiers = [];
1522 var ident = 0;
1523 while (!buffer.isEmpty()) {
1524 var subident = buffer.readUInt8();
1525 ident <<= 7;
1526 ident |= subident & 0x7f;
1527 if ((subident & 0x80) === 0) {
1528 identifiers.push(ident);
1529 ident = 0;
1530 }
1531 }
1532 if (subident & 0x80)
1533 identifiers.push(ident);
1534
1535 var first = (identifiers[0] / 40) | 0;
1536 var second = identifiers[0] % 40;
1537
1538 if (relative)
1539 result = identifiers;
1540 else
1541 result = [first, second].concat(identifiers.slice(1));
1542
1543 if (values) {
1544 var tmp = values[result.join(' ')];
1545 if (tmp === undefined)
1546 tmp = values[result.join('.')];
1547 if (tmp !== undefined)
1548 result = tmp;
1549 }
1550
1551 return result;
1552};
1553
1554DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
1555 var str = buffer.raw().toString();
1556 if (tag === 'gentime') {
1557 var year = str.slice(0, 4) | 0;
1558 var mon = str.slice(4, 6) | 0;
1559 var day = str.slice(6, 8) | 0;
1560 var hour = str.slice(8, 10) | 0;
1561 var min = str.slice(10, 12) | 0;
1562 var sec = str.slice(12, 14) | 0;
1563 } else if (tag === 'utctime') {
1564 var year = str.slice(0, 2) | 0;
1565 var mon = str.slice(2, 4) | 0;
1566 var day = str.slice(4, 6) | 0;
1567 var hour = str.slice(6, 8) | 0;
1568 var min = str.slice(8, 10) | 0;
1569 var sec = str.slice(10, 12) | 0;
1570 if (year < 70)
1571 year = 2000 + year;
1572 else
1573 year = 1900 + year;
1574 } else {
1575 return buffer.error('Decoding ' + tag + ' time is not supported yet');
1576 }
1577
1578 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
1579};
1580
1581DERNode.prototype._decodeNull = function decodeNull(buffer) {
1582 return null;
1583};
1584
1585DERNode.prototype._decodeBool = function decodeBool(buffer) {
1586 var res = buffer.readUInt8();
1587 if (buffer.isError(res))
1588 return res;
1589 else
1590 return res !== 0;
1591};
1592
1593DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
1594 // Bigint, return as it is (assume big endian)
1595 var raw = buffer.raw();
1596 var res = new bignum(raw);
1597
1598 if (values)
1599 res = values[res.toString(10)] || res;
1600
1601 return res;
1602};
1603
1604DERNode.prototype._use = function use(entity, obj) {
1605 if (typeof entity === 'function')
1606 entity = entity(obj);
1607 return entity._getDecoder('der').tree;
1608};
1609
1610// Utility methods
1611
1612function derDecodeTag(buf, fail) {
1613 var tag = buf.readUInt8(fail);
1614 if (buf.isError(tag))
1615 return tag;
1616
1617 var cls = der.tagClass[tag >> 6];
1618 var primitive = (tag & 0x20) === 0;
1619
1620 // Multi-octet tag - load
1621 if ((tag & 0x1f) === 0x1f) {
1622 var oct = tag;
1623 tag = 0;
1624 while ((oct & 0x80) === 0x80) {
1625 oct = buf.readUInt8(fail);
1626 if (buf.isError(oct))
1627 return oct;
1628
1629 tag <<= 7;
1630 tag |= oct & 0x7f;
1631 }
1632 } else {
1633 tag &= 0x1f;
1634 }
1635 var tagStr = der.tag[tag];
1636
1637 return {
1638 cls: cls,
1639 primitive: primitive,
1640 tag: tag,
1641 tagStr: tagStr
1642 };
1643}
1644
1645function derDecodeLen(buf, primitive, fail) {
1646 var len = buf.readUInt8(fail);
1647 if (buf.isError(len))
1648 return len;
1649
1650 // Indefinite form
1651 if (!primitive && len === 0x80)
1652 return null;
1653
1654 // Definite form
1655 if ((len & 0x80) === 0) {
1656 // Short form
1657 return len;
1658 }
1659
1660 // Long form
1661 var num = len & 0x7f;
1662 if (num > 4)
1663 return buf.error('length octect is too long');
1664
1665 len = 0;
1666 for (var i = 0; i < num; i++) {
1667 len <<= 8;
1668 var j = buf.readUInt8(fail);
1669 if (buf.isError(j))
1670 return j;
1671 len |= j;
1672 }
1673
1674 return len;
1675}
1676
1677},{"../../asn1":3,"inherits":107}],12:[function(require,module,exports){
1678var decoders = exports;
1679
1680decoders.der = require('./der');
1681decoders.pem = require('./pem');
1682
1683},{"./der":11,"./pem":13}],13:[function(require,module,exports){
1684var inherits = require('inherits');
1685var Buffer = require('buffer').Buffer;
1686
1687var DERDecoder = require('./der');
1688
1689function PEMDecoder(entity) {
1690 DERDecoder.call(this, entity);
1691 this.enc = 'pem';
1692};
1693inherits(PEMDecoder, DERDecoder);
1694module.exports = PEMDecoder;
1695
1696PEMDecoder.prototype.decode = function decode(data, options) {
1697 var lines = data.toString().split(/[\r\n]+/g);
1698
1699 var label = options.label.toUpperCase();
1700
1701 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
1702 var start = -1;
1703 var end = -1;
1704 for (var i = 0; i < lines.length; i++) {
1705 var match = lines[i].match(re);
1706 if (match === null)
1707 continue;
1708
1709 if (match[2] !== label)
1710 continue;
1711
1712 if (start === -1) {
1713 if (match[1] !== 'BEGIN')
1714 break;
1715 start = i;
1716 } else {
1717 if (match[1] !== 'END')
1718 break;
1719 end = i;
1720 break;
1721 }
1722 }
1723 if (start === -1 || end === -1)
1724 throw new Error('PEM section not found for: ' + label);
1725
1726 var base64 = lines.slice(start + 1, end).join('');
1727 // Remove excessive symbols
1728 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
1729
1730 var input = new Buffer(base64, 'base64');
1731 return DERDecoder.prototype.decode.call(this, input, options);
1732};
1733
1734},{"./der":11,"buffer":53,"inherits":107}],14:[function(require,module,exports){
1735var inherits = require('inherits');
1736var Buffer = require('buffer').Buffer;
1737
1738var asn1 = require('../../asn1');
1739var base = asn1.base;
1740
1741// Import DER constants
1742var der = asn1.constants.der;
1743
1744function DEREncoder(entity) {
1745 this.enc = 'der';
1746 this.name = entity.name;
1747 this.entity = entity;
1748
1749 // Construct base tree
1750 this.tree = new DERNode();
1751 this.tree._init(entity.body);
1752};
1753module.exports = DEREncoder;
1754
1755DEREncoder.prototype.encode = function encode(data, reporter) {
1756 return this.tree._encode(data, reporter).join();
1757};
1758
1759// Tree methods
1760
1761function DERNode(parent) {
1762 base.Node.call(this, 'der', parent);
1763}
1764inherits(DERNode, base.Node);
1765
1766DERNode.prototype._encodeComposite = function encodeComposite(tag,
1767 primitive,
1768 cls,
1769 content) {
1770 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
1771
1772 // Short form
1773 if (content.length < 0x80) {
1774 var header = new Buffer(2);
1775 header[0] = encodedTag;
1776 header[1] = content.length;
1777 return this._createEncoderBuffer([ header, content ]);
1778 }
1779
1780 // Long form
1781 // Count octets required to store length
1782 var lenOctets = 1;
1783 for (var i = content.length; i >= 0x100; i >>= 8)
1784 lenOctets++;
1785
1786 var header = new Buffer(1 + 1 + lenOctets);
1787 header[0] = encodedTag;
1788 header[1] = 0x80 | lenOctets;
1789
1790 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
1791 header[i] = j & 0xff;
1792
1793 return this._createEncoderBuffer([ header, content ]);
1794};
1795
1796DERNode.prototype._encodeStr = function encodeStr(str, tag) {
1797 if (tag === 'bitstr') {
1798 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
1799 } else if (tag === 'bmpstr') {
1800 var buf = new Buffer(str.length * 2);
1801 for (var i = 0; i < str.length; i++) {
1802 buf.writeUInt16BE(str.charCodeAt(i), i * 2);
1803 }
1804 return this._createEncoderBuffer(buf);
1805 } else if (tag === 'numstr') {
1806 if (!this._isNumstr(str)) {
1807 return this.reporter.error('Encoding of string type: numstr supports ' +
1808 'only digits and space');
1809 }
1810 return this._createEncoderBuffer(str);
1811 } else if (tag === 'printstr') {
1812 if (!this._isPrintstr(str)) {
1813 return this.reporter.error('Encoding of string type: printstr supports ' +
1814 'only latin upper and lower case letters, ' +
1815 'digits, space, apostrophe, left and rigth ' +
1816 'parenthesis, plus sign, comma, hyphen, ' +
1817 'dot, slash, colon, equal sign, ' +
1818 'question mark');
1819 }
1820 return this._createEncoderBuffer(str);
1821 } else if (/str$/.test(tag)) {
1822 return this._createEncoderBuffer(str);
1823 } else if (tag === 'objDesc') {
1824 return this._createEncoderBuffer(str);
1825 } else {
1826 return this.reporter.error('Encoding of string type: ' + tag +
1827 ' unsupported');
1828 }
1829};
1830
1831DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
1832 if (typeof id === 'string') {
1833 if (!values)
1834 return this.reporter.error('string objid given, but no values map found');
1835 if (!values.hasOwnProperty(id))
1836 return this.reporter.error('objid not found in values map');
1837 id = values[id].split(/[\s\.]+/g);
1838 for (var i = 0; i < id.length; i++)
1839 id[i] |= 0;
1840 } else if (Array.isArray(id)) {
1841 id = id.slice();
1842 for (var i = 0; i < id.length; i++)
1843 id[i] |= 0;
1844 }
1845
1846 if (!Array.isArray(id)) {
1847 return this.reporter.error('objid() should be either array or string, ' +
1848 'got: ' + JSON.stringify(id));
1849 }
1850
1851 if (!relative) {
1852 if (id[1] >= 40)
1853 return this.reporter.error('Second objid identifier OOB');
1854 id.splice(0, 2, id[0] * 40 + id[1]);
1855 }
1856
1857 // Count number of octets
1858 var size = 0;
1859 for (var i = 0; i < id.length; i++) {
1860 var ident = id[i];
1861 for (size++; ident >= 0x80; ident >>= 7)
1862 size++;
1863 }
1864
1865 var objid = new Buffer(size);
1866 var offset = objid.length - 1;
1867 for (var i = id.length - 1; i >= 0; i--) {
1868 var ident = id[i];
1869 objid[offset--] = ident & 0x7f;
1870 while ((ident >>= 7) > 0)
1871 objid[offset--] = 0x80 | (ident & 0x7f);
1872 }
1873
1874 return this._createEncoderBuffer(objid);
1875};
1876
1877function two(num) {
1878 if (num < 10)
1879 return '0' + num;
1880 else
1881 return num;
1882}
1883
1884DERNode.prototype._encodeTime = function encodeTime(time, tag) {
1885 var str;
1886 var date = new Date(time);
1887
1888 if (tag === 'gentime') {
1889 str = [
1890 two(date.getFullYear()),
1891 two(date.getUTCMonth() + 1),
1892 two(date.getUTCDate()),
1893 two(date.getUTCHours()),
1894 two(date.getUTCMinutes()),
1895 two(date.getUTCSeconds()),
1896 'Z'
1897 ].join('');
1898 } else if (tag === 'utctime') {
1899 str = [
1900 two(date.getFullYear() % 100),
1901 two(date.getUTCMonth() + 1),
1902 two(date.getUTCDate()),
1903 two(date.getUTCHours()),
1904 two(date.getUTCMinutes()),
1905 two(date.getUTCSeconds()),
1906 'Z'
1907 ].join('');
1908 } else {
1909 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
1910 }
1911
1912 return this._encodeStr(str, 'octstr');
1913};
1914
1915DERNode.prototype._encodeNull = function encodeNull() {
1916 return this._createEncoderBuffer('');
1917};
1918
1919DERNode.prototype._encodeInt = function encodeInt(num, values) {
1920 if (typeof num === 'string') {
1921 if (!values)
1922 return this.reporter.error('String int or enum given, but no values map');
1923 if (!values.hasOwnProperty(num)) {
1924 return this.reporter.error('Values map doesn\'t contain: ' +
1925 JSON.stringify(num));
1926 }
1927 num = values[num];
1928 }
1929
1930 // Bignum, assume big endian
1931 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
1932 var numArray = num.toArray();
1933 if (!num.sign && numArray[0] & 0x80) {
1934 numArray.unshift(0);
1935 }
1936 num = new Buffer(numArray);
1937 }
1938
1939 if (Buffer.isBuffer(num)) {
1940 var size = num.length;
1941 if (num.length === 0)
1942 size++;
1943
1944 var out = new Buffer(size);
1945 num.copy(out);
1946 if (num.length === 0)
1947 out[0] = 0
1948 return this._createEncoderBuffer(out);
1949 }
1950
1951 if (num < 0x80)
1952 return this._createEncoderBuffer(num);
1953
1954 if (num < 0x100)
1955 return this._createEncoderBuffer([0, num]);
1956
1957 var size = 1;
1958 for (var i = num; i >= 0x100; i >>= 8)
1959 size++;
1960
1961 var out = new Array(size);
1962 for (var i = out.length - 1; i >= 0; i--) {
1963 out[i] = num & 0xff;
1964 num >>= 8;
1965 }
1966 if(out[0] & 0x80) {
1967 out.unshift(0);
1968 }
1969
1970 return this._createEncoderBuffer(new Buffer(out));
1971};
1972
1973DERNode.prototype._encodeBool = function encodeBool(value) {
1974 return this._createEncoderBuffer(value ? 0xff : 0);
1975};
1976
1977DERNode.prototype._use = function use(entity, obj) {
1978 if (typeof entity === 'function')
1979 entity = entity(obj);
1980 return entity._getEncoder('der').tree;
1981};
1982
1983DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
1984 var state = this._baseState;
1985 var i;
1986 if (state['default'] === null)
1987 return false;
1988
1989 var data = dataBuffer.join();
1990 if (state.defaultBuffer === undefined)
1991 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
1992
1993 if (data.length !== state.defaultBuffer.length)
1994 return false;
1995
1996 for (i=0; i < data.length; i++)
1997 if (data[i] !== state.defaultBuffer[i])
1998 return false;
1999
2000 return true;
2001};
2002
2003// Utility methods
2004
2005function encodeTag(tag, primitive, cls, reporter) {
2006 var res;
2007
2008 if (tag === 'seqof')
2009 tag = 'seq';
2010 else if (tag === 'setof')
2011 tag = 'set';
2012
2013 if (der.tagByName.hasOwnProperty(tag))
2014 res = der.tagByName[tag];
2015 else if (typeof tag === 'number' && (tag | 0) === tag)
2016 res = tag;
2017 else
2018 return reporter.error('Unknown tag: ' + tag);
2019
2020 if (res >= 0x1f)
2021 return reporter.error('Multi-octet tag encoding unsupported');
2022
2023 if (!primitive)
2024 res |= 0x20;
2025
2026 res |= (der.tagClassByName[cls || 'universal'] << 6);
2027
2028 return res;
2029}
2030
2031},{"../../asn1":3,"buffer":53,"inherits":107}],15:[function(require,module,exports){
2032var encoders = exports;
2033
2034encoders.der = require('./der');
2035encoders.pem = require('./pem');
2036
2037},{"./der":14,"./pem":16}],16:[function(require,module,exports){
2038var inherits = require('inherits');
2039
2040var DEREncoder = require('./der');
2041
2042function PEMEncoder(entity) {
2043 DEREncoder.call(this, entity);
2044 this.enc = 'pem';
2045};
2046inherits(PEMEncoder, DEREncoder);
2047module.exports = PEMEncoder;
2048
2049PEMEncoder.prototype.encode = function encode(data, options) {
2050 var buf = DEREncoder.prototype.encode.call(this, data);
2051
2052 var p = buf.toString('base64');
2053 var out = [ '-----BEGIN ' + options.label + '-----' ];
2054 for (var i = 0; i < p.length; i += 64)
2055 out.push(p.slice(i, i + 64));
2056 out.push('-----END ' + options.label + '-----');
2057 return out.join('\n');
2058};
2059
2060},{"./der":14,"inherits":107}],17:[function(require,module,exports){
2061// base-x encoding
2062// Forked from https://github.com/cryptocoinjs/bs58
2063// Originally written by Mike Hearn for BitcoinJ
2064// Copyright (c) 2011 Google Inc
2065// Ported to JavaScript by Stefan Thomas
2066// Merged Buffer refactorings from base58-native by Stephen Pair
2067// Copyright (c) 2013 BitPay Inc
2068
2069var Buffer = require('safe-buffer').Buffer
2070
2071module.exports = function base (ALPHABET) {
2072 var ALPHABET_MAP = {}
2073 var BASE = ALPHABET.length
2074 var LEADER = ALPHABET.charAt(0)
2075
2076 // pre-compute lookup table
2077 for (var z = 0; z < ALPHABET.length; z++) {
2078 var x = ALPHABET.charAt(z)
2079
2080 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
2081 ALPHABET_MAP[x] = z
2082 }
2083
2084 function encode (source) {
2085 if (source.length === 0) return ''
2086
2087 var digits = [0]
2088 for (var i = 0; i < source.length; ++i) {
2089 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
2090 carry += digits[j] << 8
2091 digits[j] = carry % BASE
2092 carry = (carry / BASE) | 0
2093 }
2094
2095 while (carry > 0) {
2096 digits.push(carry % BASE)
2097 carry = (carry / BASE) | 0
2098 }
2099 }
2100
2101 var string = ''
2102
2103 // deal with leading zeros
2104 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
2105 // convert digits to a string
2106 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
2107
2108 return string
2109 }
2110
2111 function decodeUnsafe (string) {
2112 if (typeof string !== 'string') throw new TypeError('Expected String')
2113 if (string.length === 0) return Buffer.allocUnsafe(0)
2114
2115 var bytes = [0]
2116 for (var i = 0; i < string.length; i++) {
2117 var value = ALPHABET_MAP[string[i]]
2118 if (value === undefined) return
2119
2120 for (var j = 0, carry = value; j < bytes.length; ++j) {
2121 carry += bytes[j] * BASE
2122 bytes[j] = carry & 0xff
2123 carry >>= 8
2124 }
2125
2126 while (carry > 0) {
2127 bytes.push(carry & 0xff)
2128 carry >>= 8
2129 }
2130 }
2131
2132 // deal with leading zeros
2133 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
2134 bytes.push(0)
2135 }
2136
2137 return Buffer.from(bytes.reverse())
2138 }
2139
2140 function decode (string) {
2141 var buffer = decodeUnsafe(string)
2142 if (buffer) return buffer
2143
2144 throw new Error('Non-base' + BASE + ' character')
2145 }
2146
2147 return {
2148 encode: encode,
2149 decodeUnsafe: decodeUnsafe,
2150 decode: decode
2151 }
2152}
2153
2154},{"safe-buffer":156}],18:[function(require,module,exports){
2155'use strict'
2156
2157exports.byteLength = byteLength
2158exports.toByteArray = toByteArray
2159exports.fromByteArray = fromByteArray
2160
2161var lookup = []
2162var revLookup = []
2163var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
2164
2165var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
2166for (var i = 0, len = code.length; i < len; ++i) {
2167 lookup[i] = code[i]
2168 revLookup[code.charCodeAt(i)] = i
2169}
2170
2171revLookup['-'.charCodeAt(0)] = 62
2172revLookup['_'.charCodeAt(0)] = 63
2173
2174function placeHoldersCount (b64) {
2175 var len = b64.length
2176 if (len % 4 > 0) {
2177 throw new Error('Invalid string. Length must be a multiple of 4')
2178 }
2179
2180 // the number of equal signs (place holders)
2181 // if there are two placeholders, than the two characters before it
2182 // represent one byte
2183 // if there is only one, then the three characters before it represent 2 bytes
2184 // this is just a cheap hack to not do indexOf twice
2185 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
2186}
2187
2188function byteLength (b64) {
2189 // base64 is 4/3 + up to two characters of the original data
2190 return (b64.length * 3 / 4) - placeHoldersCount(b64)
2191}
2192
2193function toByteArray (b64) {
2194 var i, l, tmp, placeHolders, arr
2195 var len = b64.length
2196 placeHolders = placeHoldersCount(b64)
2197
2198 arr = new Arr((len * 3 / 4) - placeHolders)
2199
2200 // if there are placeholders, only get up to the last complete 4 chars
2201 l = placeHolders > 0 ? len - 4 : len
2202
2203 var L = 0
2204
2205 for (i = 0; i < l; i += 4) {
2206 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
2207 arr[L++] = (tmp >> 16) & 0xFF
2208 arr[L++] = (tmp >> 8) & 0xFF
2209 arr[L++] = tmp & 0xFF
2210 }
2211
2212 if (placeHolders === 2) {
2213 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
2214 arr[L++] = tmp & 0xFF
2215 } else if (placeHolders === 1) {
2216 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
2217 arr[L++] = (tmp >> 8) & 0xFF
2218 arr[L++] = tmp & 0xFF
2219 }
2220
2221 return arr
2222}
2223
2224function tripletToBase64 (num) {
2225 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
2226}
2227
2228function encodeChunk (uint8, start, end) {
2229 var tmp
2230 var output = []
2231 for (var i = start; i < end; i += 3) {
2232 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
2233 output.push(tripletToBase64(tmp))
2234 }
2235 return output.join('')
2236}
2237
2238function fromByteArray (uint8) {
2239 var tmp
2240 var len = uint8.length
2241 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
2242 var output = ''
2243 var parts = []
2244 var maxChunkLength = 16383 // must be multiple of 3
2245
2246 // go through the array every three bytes, we'll deal with trailing stuff later
2247 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
2248 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
2249 }
2250
2251 // pad the end with zeros, but make sure to not forget the extra bytes
2252 if (extraBytes === 1) {
2253 tmp = uint8[len - 1]
2254 output += lookup[tmp >> 2]
2255 output += lookup[(tmp << 4) & 0x3F]
2256 output += '=='
2257 } else if (extraBytes === 2) {
2258 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
2259 output += lookup[tmp >> 10]
2260 output += lookup[(tmp >> 4) & 0x3F]
2261 output += lookup[(tmp << 2) & 0x3F]
2262 output += '='
2263 }
2264
2265 parts.push(output)
2266
2267 return parts.join('')
2268}
2269
2270},{}],19:[function(require,module,exports){
2271/*! bignumber.js v5.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
2272
2273;(function (globalObj) {
2274 'use strict';
2275
2276 /*
2277 bignumber.js v5.0.0
2278 A JavaScript library for arbitrary-precision arithmetic.
2279 https://github.com/MikeMcl/bignumber.js
2280 Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
2281 MIT Expat Licence
2282 */
2283
2284
2285 var BigNumber,
2286 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
2287 mathceil = Math.ceil,
2288 mathfloor = Math.floor,
2289 notBool = ' not a boolean or binary digit',
2290 roundingMode = 'rounding mode',
2291 tooManyDigits = 'number type has more than 15 significant digits',
2292 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
2293 BASE = 1e14,
2294 LOG_BASE = 14,
2295 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
2296 // MAX_INT32 = 0x7fffffff, // 2^31 - 1
2297 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
2298 SQRT_BASE = 1e7,
2299
2300 /*
2301 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
2302 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
2303 * exception is thrown (if ERRORS is true).
2304 */
2305 MAX = 1E9; // 0 to MAX_INT32
2306
2307
2308 /*
2309 * Create and return a BigNumber constructor.
2310 */
2311 function constructorFactory(config) {
2312 var div, parseNumeric,
2313
2314 // id tracks the caller function, so its name can be included in error messages.
2315 id = 0,
2316 P = BigNumber.prototype,
2317 ONE = new BigNumber(1),
2318
2319
2320 /********************************* EDITABLE DEFAULTS **********************************/
2321
2322
2323 /*
2324 * The default values below must be integers within the inclusive ranges stated.
2325 * The values can also be changed at run-time using BigNumber.config.
2326 */
2327
2328 // The maximum number of decimal places for operations involving division.
2329 DECIMAL_PLACES = 20, // 0 to MAX
2330
2331 /*
2332 * The rounding mode used when rounding to the above decimal places, and when using
2333 * toExponential, toFixed, toFormat and toPrecision, and round (default value).
2334 * UP 0 Away from zero.
2335 * DOWN 1 Towards zero.
2336 * CEIL 2 Towards +Infinity.
2337 * FLOOR 3 Towards -Infinity.
2338 * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
2339 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
2340 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
2341 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
2342 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
2343 */
2344 ROUNDING_MODE = 4, // 0 to 8
2345
2346 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
2347
2348 // The exponent value at and beneath which toString returns exponential notation.
2349 // Number type: -7
2350 TO_EXP_NEG = -7, // 0 to -MAX
2351
2352 // The exponent value at and above which toString returns exponential notation.
2353 // Number type: 21
2354 TO_EXP_POS = 21, // 0 to MAX
2355
2356 // RANGE : [MIN_EXP, MAX_EXP]
2357
2358 // The minimum exponent value, beneath which underflow to zero occurs.
2359 // Number type: -324 (5e-324)
2360 MIN_EXP = -1e7, // -1 to -MAX
2361
2362 // The maximum exponent value, above which overflow to Infinity occurs.
2363 // Number type: 308 (1.7976931348623157e+308)
2364 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
2365 MAX_EXP = 1e7, // 1 to MAX
2366
2367 // Whether BigNumber Errors are ever thrown.
2368 ERRORS = true, // true or false
2369
2370 // Change to intValidatorNoErrors if ERRORS is false.
2371 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
2372
2373 // Whether to use cryptographically-secure random number generation, if available.
2374 CRYPTO = false, // true or false
2375
2376 /*
2377 * The modulo mode used when calculating the modulus: a mod n.
2378 * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
2379 * The remainder (r) is calculated as: r = a - n * q.
2380 *
2381 * UP 0 The remainder is positive if the dividend is negative, else is negative.
2382 * DOWN 1 The remainder has the same sign as the dividend.
2383 * This modulo mode is commonly known as 'truncated division' and is
2384 * equivalent to (a % n) in JavaScript.
2385 * FLOOR 3 The remainder has the same sign as the divisor (Python %).
2386 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
2387 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
2388 * The remainder is always positive.
2389 *
2390 * The truncated division, floored division, Euclidian division and IEEE 754 remainder
2391 * modes are commonly used for the modulus operation.
2392 * Although the other rounding modes can also be used, they may not give useful results.
2393 */
2394 MODULO_MODE = 1, // 0 to 9
2395
2396 // The maximum number of significant digits of the result of the toPower operation.
2397 // If POW_PRECISION is 0, there will be unlimited significant digits.
2398 POW_PRECISION = 0, // 0 to MAX
2399
2400 // The format specification used by the BigNumber.prototype.toFormat method.
2401 FORMAT = {
2402 decimalSeparator: '.',
2403 groupSeparator: ',',
2404 groupSize: 3,
2405 secondaryGroupSize: 0,
2406 fractionGroupSeparator: '\xA0', // non-breaking space
2407 fractionGroupSize: 0
2408 };
2409
2410
2411 /******************************************************************************************/
2412
2413
2414 // CONSTRUCTOR
2415
2416
2417 /*
2418 * The BigNumber constructor and exported function.
2419 * Create and return a new instance of a BigNumber object.
2420 *
2421 * n {number|string|BigNumber} A numeric value.
2422 * [b] {number} The base of n. Integer, 2 to 64 inclusive.
2423 */
2424 function BigNumber( n, b ) {
2425 var c, e, i, num, len, str,
2426 x = this;
2427
2428 // Enable constructor usage without new.
2429 if ( !( x instanceof BigNumber ) ) {
2430
2431 // 'BigNumber() constructor call without new: {n}'
2432 // See GitHub issue: #81.
2433 //if (ERRORS) raise( 26, 'constructor call without new', n );
2434 return new BigNumber( n, b );
2435 }
2436
2437 // 'new BigNumber() base not an integer: {b}'
2438 // 'new BigNumber() base out of range: {b}'
2439 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
2440
2441 // Duplicate.
2442 if ( n instanceof BigNumber ) {
2443 x.s = n.s;
2444 x.e = n.e;
2445 x.c = ( n = n.c ) ? n.slice() : n;
2446 id = 0;
2447 return;
2448 }
2449
2450 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
2451 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
2452
2453 // Fast path for integers.
2454 if ( n === ~~n ) {
2455 for ( e = 0, i = n; i >= 10; i /= 10, e++ );
2456 x.e = e;
2457 x.c = [n];
2458 id = 0;
2459 return;
2460 }
2461
2462 str = n + '';
2463 } else {
2464 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
2465 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
2466 }
2467 } else {
2468 b = b | 0;
2469 str = n + '';
2470
2471 // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
2472 // Allow exponential notation to be used with base 10 argument.
2473 if ( b == 10 ) {
2474 x = new BigNumber( n instanceof BigNumber ? n : str );
2475 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
2476 }
2477
2478 // Avoid potential interpretation of Infinity and NaN as base 44+ values.
2479 // Any number in exponential form will fail due to the [Ee][+-].
2480 if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
2481 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
2482 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
2483 return parseNumeric( x, str, num, b );
2484 }
2485
2486 if (num) {
2487 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
2488
2489 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
2490
2491 // 'new BigNumber() number type has more than 15 significant digits: {n}'
2492 raise( id, tooManyDigits, n );
2493 }
2494
2495 // Prevent later check for length on converted number.
2496 num = false;
2497 } else {
2498 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
2499 }
2500
2501 str = convertBase( str, 10, b, x.s );
2502 }
2503
2504 // Decimal point?
2505 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
2506
2507 // Exponential form?
2508 if ( ( i = str.search( /e/i ) ) > 0 ) {
2509
2510 // Determine exponent.
2511 if ( e < 0 ) e = i;
2512 e += +str.slice( i + 1 );
2513 str = str.substring( 0, i );
2514 } else if ( e < 0 ) {
2515
2516 // Integer.
2517 e = str.length;
2518 }
2519
2520 // Determine leading zeros.
2521 for ( i = 0; str.charCodeAt(i) === 48; i++ );
2522
2523 // Determine trailing zeros.
2524 for ( len = str.length; str.charCodeAt(--len) === 48; );
2525 str = str.slice( i, len + 1 );
2526
2527 if (str) {
2528 len = str.length;
2529
2530 // Disallow numbers with over 15 significant digits if number type.
2531 // 'new BigNumber() number type has more than 15 significant digits: {n}'
2532 if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
2533 raise( id, tooManyDigits, x.s * n );
2534 }
2535
2536 e = e - i - 1;
2537
2538 // Overflow?
2539 if ( e > MAX_EXP ) {
2540
2541 // Infinity.
2542 x.c = x.e = null;
2543
2544 // Underflow?
2545 } else if ( e < MIN_EXP ) {
2546
2547 // Zero.
2548 x.c = [ x.e = 0 ];
2549 } else {
2550 x.e = e;
2551 x.c = [];
2552
2553 // Transform base
2554
2555 // e is the base 10 exponent.
2556 // i is where to slice str to get the first element of the coefficient array.
2557 i = ( e + 1 ) % LOG_BASE;
2558 if ( e < 0 ) i += LOG_BASE;
2559
2560 if ( i < len ) {
2561 if (i) x.c.push( +str.slice( 0, i ) );
2562
2563 for ( len -= LOG_BASE; i < len; ) {
2564 x.c.push( +str.slice( i, i += LOG_BASE ) );
2565 }
2566
2567 str = str.slice(i);
2568 i = LOG_BASE - str.length;
2569 } else {
2570 i -= len;
2571 }
2572
2573 for ( ; i--; str += '0' );
2574 x.c.push( +str );
2575 }
2576 } else {
2577
2578 // Zero.
2579 x.c = [ x.e = 0 ];
2580 }
2581
2582 id = 0;
2583 }
2584
2585
2586 // CONSTRUCTOR PROPERTIES
2587
2588
2589 BigNumber.another = constructorFactory;
2590
2591 BigNumber.ROUND_UP = 0;
2592 BigNumber.ROUND_DOWN = 1;
2593 BigNumber.ROUND_CEIL = 2;
2594 BigNumber.ROUND_FLOOR = 3;
2595 BigNumber.ROUND_HALF_UP = 4;
2596 BigNumber.ROUND_HALF_DOWN = 5;
2597 BigNumber.ROUND_HALF_EVEN = 6;
2598 BigNumber.ROUND_HALF_CEIL = 7;
2599 BigNumber.ROUND_HALF_FLOOR = 8;
2600 BigNumber.EUCLID = 9;
2601
2602
2603 /*
2604 * Configure infrequently-changing library-wide settings.
2605 *
2606 * Accept an object or an argument list, with one or many of the following properties or
2607 * parameters respectively:
2608 *
2609 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
2610 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
2611 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
2612 * [integer -MAX to 0 incl., 0 to MAX incl.]
2613 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
2614 * [integer -MAX to -1 incl., integer 1 to MAX incl.]
2615 * ERRORS {boolean|number} true, false, 1 or 0
2616 * CRYPTO {boolean|number} true, false, 1 or 0
2617 * MODULO_MODE {number} 0 to 9 inclusive
2618 * POW_PRECISION {number} 0 to MAX inclusive
2619 * FORMAT {object} See BigNumber.prototype.toFormat
2620 * decimalSeparator {string}
2621 * groupSeparator {string}
2622 * groupSize {number}
2623 * secondaryGroupSize {number}
2624 * fractionGroupSeparator {string}
2625 * fractionGroupSize {number}
2626 *
2627 * (The values assigned to the above FORMAT object properties are not checked for validity.)
2628 *
2629 * E.g.
2630 * BigNumber.config(20, 4) is equivalent to
2631 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
2632 *
2633 * Ignore properties/parameters set to null or undefined.
2634 * Return an object with the properties current values.
2635 */
2636 BigNumber.config = BigNumber.set = function () {
2637 var v, p,
2638 i = 0,
2639 r = {},
2640 a = arguments,
2641 o = a[0],
2642 has = o && typeof o == 'object'
2643 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
2644 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
2645
2646 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
2647 // 'config() DECIMAL_PLACES not an integer: {v}'
2648 // 'config() DECIMAL_PLACES out of range: {v}'
2649 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
2650 DECIMAL_PLACES = v | 0;
2651 }
2652 r[p] = DECIMAL_PLACES;
2653
2654 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
2655 // 'config() ROUNDING_MODE not an integer: {v}'
2656 // 'config() ROUNDING_MODE out of range: {v}'
2657 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
2658 ROUNDING_MODE = v | 0;
2659 }
2660 r[p] = ROUNDING_MODE;
2661
2662 // EXPONENTIAL_AT {number|number[]}
2663 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
2664 // 'config() EXPONENTIAL_AT not an integer: {v}'
2665 // 'config() EXPONENTIAL_AT out of range: {v}'
2666 if ( has( p = 'EXPONENTIAL_AT' ) ) {
2667
2668 if ( isArray(v) ) {
2669 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
2670 TO_EXP_NEG = v[0] | 0;
2671 TO_EXP_POS = v[1] | 0;
2672 }
2673 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
2674 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
2675 }
2676 }
2677 r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
2678
2679 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
2680 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
2681 // 'config() RANGE not an integer: {v}'
2682 // 'config() RANGE cannot be zero: {v}'
2683 // 'config() RANGE out of range: {v}'
2684 if ( has( p = 'RANGE' ) ) {
2685
2686 if ( isArray(v) ) {
2687 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
2688 MIN_EXP = v[0] | 0;
2689 MAX_EXP = v[1] | 0;
2690 }
2691 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
2692 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
2693 else if (ERRORS) raise( 2, p + ' cannot be zero', v );
2694 }
2695 }
2696 r[p] = [ MIN_EXP, MAX_EXP ];
2697
2698 // ERRORS {boolean|number} true, false, 1 or 0.
2699 // 'config() ERRORS not a boolean or binary digit: {v}'
2700 if ( has( p = 'ERRORS' ) ) {
2701
2702 if ( v === !!v || v === 1 || v === 0 ) {
2703 id = 0;
2704 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
2705 } else if (ERRORS) {
2706 raise( 2, p + notBool, v );
2707 }
2708 }
2709 r[p] = ERRORS;
2710
2711 // CRYPTO {boolean|number} true, false, 1 or 0.
2712 // 'config() CRYPTO not a boolean or binary digit: {v}'
2713 // 'config() crypto unavailable: {crypto}'
2714 if ( has( p = 'CRYPTO' ) ) {
2715
2716 if ( v === true || v === false || v === 1 || v === 0 ) {
2717 if (v) {
2718 v = typeof crypto == 'undefined';
2719 if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
2720 CRYPTO = true;
2721 } else if (ERRORS) {
2722 raise( 2, 'crypto unavailable', v ? void 0 : crypto );
2723 } else {
2724 CRYPTO = false;
2725 }
2726 } else {
2727 CRYPTO = false;
2728 }
2729 } else if (ERRORS) {
2730 raise( 2, p + notBool, v );
2731 }
2732 }
2733 r[p] = CRYPTO;
2734
2735 // MODULO_MODE {number} Integer, 0 to 9 inclusive.
2736 // 'config() MODULO_MODE not an integer: {v}'
2737 // 'config() MODULO_MODE out of range: {v}'
2738 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
2739 MODULO_MODE = v | 0;
2740 }
2741 r[p] = MODULO_MODE;
2742
2743 // POW_PRECISION {number} Integer, 0 to MAX inclusive.
2744 // 'config() POW_PRECISION not an integer: {v}'
2745 // 'config() POW_PRECISION out of range: {v}'
2746 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
2747 POW_PRECISION = v | 0;
2748 }
2749 r[p] = POW_PRECISION;
2750
2751 // FORMAT {object}
2752 // 'config() FORMAT not an object: {v}'
2753 if ( has( p = 'FORMAT' ) ) {
2754
2755 if ( typeof v == 'object' ) {
2756 FORMAT = v;
2757 } else if (ERRORS) {
2758 raise( 2, p + ' not an object', v );
2759 }
2760 }
2761 r[p] = FORMAT;
2762
2763 return r;
2764 };
2765
2766
2767 /*
2768 * Return a new BigNumber whose value is the maximum of the arguments.
2769 *
2770 * arguments {number|string|BigNumber}
2771 */
2772 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
2773
2774
2775 /*
2776 * Return a new BigNumber whose value is the minimum of the arguments.
2777 *
2778 * arguments {number|string|BigNumber}
2779 */
2780 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
2781
2782
2783 /*
2784 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
2785 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
2786 * zeros are produced).
2787 *
2788 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
2789 *
2790 * 'random() decimal places not an integer: {dp}'
2791 * 'random() decimal places out of range: {dp}'
2792 * 'random() crypto unavailable: {crypto}'
2793 */
2794 BigNumber.random = (function () {
2795 var pow2_53 = 0x20000000000000;
2796
2797 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
2798 // Check if Math.random() produces more than 32 bits of randomness.
2799 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
2800 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
2801 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
2802 ? function () { return mathfloor( Math.random() * pow2_53 ); }
2803 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
2804 (Math.random() * 0x800000 | 0); };
2805
2806 return function (dp) {
2807 var a, b, e, k, v,
2808 i = 0,
2809 c = [],
2810 rand = new BigNumber(ONE);
2811
2812 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
2813 k = mathceil( dp / LOG_BASE );
2814
2815 if (CRYPTO) {
2816
2817 // Browsers supporting crypto.getRandomValues.
2818 if (crypto.getRandomValues) {
2819
2820 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
2821
2822 for ( ; i < k; ) {
2823
2824 // 53 bits:
2825 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
2826 // 11111 11111111 11111111 11111111 11100000 00000000 00000000
2827 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
2828 // 11111 11111111 11111111
2829 // 0x20000 is 2^21.
2830 v = a[i] * 0x20000 + (a[i + 1] >>> 11);
2831
2832 // Rejection sampling:
2833 // 0 <= v < 9007199254740992
2834 // Probability that v >= 9e15, is
2835 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
2836 if ( v >= 9e15 ) {
2837 b = crypto.getRandomValues( new Uint32Array(2) );
2838 a[i] = b[0];
2839 a[i + 1] = b[1];
2840 } else {
2841
2842 // 0 <= v <= 8999999999999999
2843 // 0 <= (v % 1e14) <= 99999999999999
2844 c.push( v % 1e14 );
2845 i += 2;
2846 }
2847 }
2848 i = k / 2;
2849
2850 // Node.js supporting crypto.randomBytes.
2851 } else if (crypto.randomBytes) {
2852
2853 // buffer
2854 a = crypto.randomBytes( k *= 7 );
2855
2856 for ( ; i < k; ) {
2857
2858 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
2859 // 0x100000000 is 2^32, 0x1000000 is 2^24
2860 // 11111 11111111 11111111 11111111 11111111 11111111 11111111
2861 // 0 <= v < 9007199254740992
2862 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
2863 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
2864 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
2865
2866 if ( v >= 9e15 ) {
2867 crypto.randomBytes(7).copy( a, i );
2868 } else {
2869
2870 // 0 <= (v % 1e14) <= 99999999999999
2871 c.push( v % 1e14 );
2872 i += 7;
2873 }
2874 }
2875 i = k / 7;
2876 } else {
2877 CRYPTO = false;
2878 if (ERRORS) raise( 14, 'crypto unavailable', crypto );
2879 }
2880 }
2881
2882 // Use Math.random.
2883 if (!CRYPTO) {
2884
2885 for ( ; i < k; ) {
2886 v = random53bitInt();
2887 if ( v < 9e15 ) c[i++] = v % 1e14;
2888 }
2889 }
2890
2891 k = c[--i];
2892 dp %= LOG_BASE;
2893
2894 // Convert trailing digits to zeros according to dp.
2895 if ( k && dp ) {
2896 v = POWS_TEN[LOG_BASE - dp];
2897 c[i] = mathfloor( k / v ) * v;
2898 }
2899
2900 // Remove trailing elements which are zero.
2901 for ( ; c[i] === 0; c.pop(), i-- );
2902
2903 // Zero?
2904 if ( i < 0 ) {
2905 c = [ e = 0 ];
2906 } else {
2907
2908 // Remove leading elements which are zero and adjust exponent accordingly.
2909 for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
2910
2911 // Count the digits of the first element of c to determine leading zeros, and...
2912 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
2913
2914 // adjust the exponent accordingly.
2915 if ( i < LOG_BASE ) e -= LOG_BASE - i;
2916 }
2917
2918 rand.e = e;
2919 rand.c = c;
2920 return rand;
2921 };
2922 })();
2923
2924
2925 // PRIVATE FUNCTIONS
2926
2927
2928 // Convert a numeric string of baseIn to a numeric string of baseOut.
2929 function convertBase( str, baseOut, baseIn, sign ) {
2930 var d, e, k, r, x, xc, y,
2931 i = str.indexOf( '.' ),
2932 dp = DECIMAL_PLACES,
2933 rm = ROUNDING_MODE;
2934
2935 if ( baseIn < 37 ) str = str.toLowerCase();
2936
2937 // Non-integer.
2938 if ( i >= 0 ) {
2939 k = POW_PRECISION;
2940
2941 // Unlimited precision.
2942 POW_PRECISION = 0;
2943 str = str.replace( '.', '' );
2944 y = new BigNumber(baseIn);
2945 x = y.pow( str.length - i );
2946 POW_PRECISION = k;
2947
2948 // Convert str as if an integer, then restore the fraction part by dividing the
2949 // result by its base raised to a power.
2950 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
2951 y.e = y.c.length;
2952 }
2953
2954 // Convert the number as integer.
2955 xc = toBaseOut( str, baseIn, baseOut );
2956 e = k = xc.length;
2957
2958 // Remove trailing zeros.
2959 for ( ; xc[--k] == 0; xc.pop() );
2960 if ( !xc[0] ) return '0';
2961
2962 if ( i < 0 ) {
2963 --e;
2964 } else {
2965 x.c = xc;
2966 x.e = e;
2967
2968 // sign is needed for correct rounding.
2969 x.s = sign;
2970 x = div( x, y, dp, rm, baseOut );
2971 xc = x.c;
2972 r = x.r;
2973 e = x.e;
2974 }
2975
2976 d = e + dp + 1;
2977
2978 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
2979 i = xc[d];
2980 k = baseOut / 2;
2981 r = r || d < 0 || xc[d + 1] != null;
2982
2983 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
2984 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
2985 rm == ( x.s < 0 ? 8 : 7 ) );
2986
2987 if ( d < 1 || !xc[0] ) {
2988
2989 // 1^-dp or 0.
2990 str = r ? toFixedPoint( '1', -dp ) : '0';
2991 } else {
2992 xc.length = d;
2993
2994 if (r) {
2995
2996 // Rounding up may mean the previous digit has to be rounded up and so on.
2997 for ( --baseOut; ++xc[--d] > baseOut; ) {
2998 xc[d] = 0;
2999
3000 if ( !d ) {
3001 ++e;
3002 xc = [1].concat(xc);
3003 }
3004 }
3005 }
3006
3007 // Determine trailing zeros.
3008 for ( k = xc.length; !xc[--k]; );
3009
3010 // E.g. [4, 11, 15] becomes 4bf.
3011 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
3012 str = toFixedPoint( str, e );
3013 }
3014
3015 // The caller will add the sign.
3016 return str;
3017 }
3018
3019
3020 // Perform division in the specified base. Called by div and convertBase.
3021 div = (function () {
3022
3023 // Assume non-zero x and k.
3024 function multiply( x, k, base ) {
3025 var m, temp, xlo, xhi,
3026 carry = 0,
3027 i = x.length,
3028 klo = k % SQRT_BASE,
3029 khi = k / SQRT_BASE | 0;
3030
3031 for ( x = x.slice(); i--; ) {
3032 xlo = x[i] % SQRT_BASE;
3033 xhi = x[i] / SQRT_BASE | 0;
3034 m = khi * xlo + xhi * klo;
3035 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
3036 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
3037 x[i] = temp % base;
3038 }
3039
3040 if (carry) x = [carry].concat(x);
3041
3042 return x;
3043 }
3044
3045 function compare( a, b, aL, bL ) {
3046 var i, cmp;
3047
3048 if ( aL != bL ) {
3049 cmp = aL > bL ? 1 : -1;
3050 } else {
3051
3052 for ( i = cmp = 0; i < aL; i++ ) {
3053
3054 if ( a[i] != b[i] ) {
3055 cmp = a[i] > b[i] ? 1 : -1;
3056 break;
3057 }
3058 }
3059 }
3060 return cmp;
3061 }
3062
3063 function subtract( a, b, aL, base ) {
3064 var i = 0;
3065
3066 // Subtract b from a.
3067 for ( ; aL--; ) {
3068 a[aL] -= i;
3069 i = a[aL] < b[aL] ? 1 : 0;
3070 a[aL] = i * base + a[aL] - b[aL];
3071 }
3072
3073 // Remove leading zeros.
3074 for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
3075 }
3076
3077 // x: dividend, y: divisor.
3078 return function ( x, y, dp, rm, base ) {
3079 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
3080 yL, yz,
3081 s = x.s == y.s ? 1 : -1,
3082 xc = x.c,
3083 yc = y.c;
3084
3085 // Either NaN, Infinity or 0?
3086 if ( !xc || !xc[0] || !yc || !yc[0] ) {
3087
3088 return new BigNumber(
3089
3090 // Return NaN if either NaN, or both Infinity or 0.
3091 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
3092
3093 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
3094 xc && xc[0] == 0 || !yc ? s * 0 : s / 0
3095 );
3096 }
3097
3098 q = new BigNumber(s);
3099 qc = q.c = [];
3100 e = x.e - y.e;
3101 s = dp + e + 1;
3102
3103 if ( !base ) {
3104 base = BASE;
3105 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
3106 s = s / LOG_BASE | 0;
3107 }
3108
3109 // Result exponent may be one less then the current value of e.
3110 // The coefficients of the BigNumbers from convertBase may have trailing zeros.
3111 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
3112 if ( yc[i] > ( xc[i] || 0 ) ) e--;
3113
3114 if ( s < 0 ) {
3115 qc.push(1);
3116 more = true;
3117 } else {
3118 xL = xc.length;
3119 yL = yc.length;
3120 i = 0;
3121 s += 2;
3122
3123 // Normalise xc and yc so highest order digit of yc is >= base / 2.
3124
3125 n = mathfloor( base / ( yc[0] + 1 ) );
3126
3127 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
3128 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
3129 if ( n > 1 ) {
3130 yc = multiply( yc, n, base );
3131 xc = multiply( xc, n, base );
3132 yL = yc.length;
3133 xL = xc.length;
3134 }
3135
3136 xi = yL;
3137 rem = xc.slice( 0, yL );
3138 remL = rem.length;
3139
3140 // Add zeros to make remainder as long as divisor.
3141 for ( ; remL < yL; rem[remL++] = 0 );
3142 yz = yc.slice();
3143 yz = [0].concat(yz);
3144 yc0 = yc[0];
3145 if ( yc[1] >= base / 2 ) yc0++;
3146 // Not necessary, but to prevent trial digit n > base, when using base 3.
3147 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
3148
3149 do {
3150 n = 0;
3151
3152 // Compare divisor and remainder.
3153 cmp = compare( yc, rem, yL, remL );
3154
3155 // If divisor < remainder.
3156 if ( cmp < 0 ) {
3157
3158 // Calculate trial digit, n.
3159
3160 rem0 = rem[0];
3161 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
3162
3163 // n is how many times the divisor goes into the current remainder.
3164 n = mathfloor( rem0 / yc0 );
3165
3166 // Algorithm:
3167 // 1. product = divisor * trial digit (n)
3168 // 2. if product > remainder: product -= divisor, n--
3169 // 3. remainder -= product
3170 // 4. if product was < remainder at 2:
3171 // 5. compare new remainder and divisor
3172 // 6. If remainder > divisor: remainder -= divisor, n++
3173
3174 if ( n > 1 ) {
3175
3176 // n may be > base only when base is 3.
3177 if (n >= base) n = base - 1;
3178
3179 // product = divisor * trial digit.
3180 prod = multiply( yc, n, base );
3181 prodL = prod.length;
3182 remL = rem.length;
3183
3184 // Compare product and remainder.
3185 // If product > remainder.
3186 // Trial digit n too high.
3187 // n is 1 too high about 5% of the time, and is not known to have
3188 // ever been more than 1 too high.
3189 while ( compare( prod, rem, prodL, remL ) == 1 ) {
3190 n--;
3191
3192 // Subtract divisor from product.
3193 subtract( prod, yL < prodL ? yz : yc, prodL, base );
3194 prodL = prod.length;
3195 cmp = 1;
3196 }
3197 } else {
3198
3199 // n is 0 or 1, cmp is -1.
3200 // If n is 0, there is no need to compare yc and rem again below,
3201 // so change cmp to 1 to avoid it.
3202 // If n is 1, leave cmp as -1, so yc and rem are compared again.
3203 if ( n == 0 ) {
3204
3205 // divisor < remainder, so n must be at least 1.
3206 cmp = n = 1;
3207 }
3208
3209 // product = divisor
3210 prod = yc.slice();
3211 prodL = prod.length;
3212 }
3213
3214 if ( prodL < remL ) prod = [0].concat(prod);
3215
3216 // Subtract product from remainder.
3217 subtract( rem, prod, remL, base );
3218 remL = rem.length;
3219
3220 // If product was < remainder.
3221 if ( cmp == -1 ) {
3222
3223 // Compare divisor and new remainder.
3224 // If divisor < new remainder, subtract divisor from remainder.
3225 // Trial digit n too low.
3226 // n is 1 too low about 5% of the time, and very rarely 2 too low.
3227 while ( compare( yc, rem, yL, remL ) < 1 ) {
3228 n++;
3229
3230 // Subtract divisor from remainder.
3231 subtract( rem, yL < remL ? yz : yc, remL, base );
3232 remL = rem.length;
3233 }
3234 }
3235 } else if ( cmp === 0 ) {
3236 n++;
3237 rem = [0];
3238 } // else cmp === 1 and n will be 0
3239
3240 // Add the next digit, n, to the result array.
3241 qc[i++] = n;
3242
3243 // Update the remainder.
3244 if ( rem[0] ) {
3245 rem[remL++] = xc[xi] || 0;
3246 } else {
3247 rem = [ xc[xi] ];
3248 remL = 1;
3249 }
3250 } while ( ( xi++ < xL || rem[0] != null ) && s-- );
3251
3252 more = rem[0] != null;
3253
3254 // Leading zero?
3255 if ( !qc[0] ) qc.splice(0, 1);
3256 }
3257
3258 if ( base == BASE ) {
3259
3260 // To calculate q.e, first get the number of digits of qc[0].
3261 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
3262 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
3263
3264 // Caller is convertBase.
3265 } else {
3266 q.e = e;
3267 q.r = +more;
3268 }
3269
3270 return q;
3271 };
3272 })();
3273
3274
3275 /*
3276 * Return a string representing the value of BigNumber n in fixed-point or exponential
3277 * notation rounded to the specified decimal places or significant digits.
3278 *
3279 * n is a BigNumber.
3280 * i is the index of the last digit required (i.e. the digit that may be rounded up).
3281 * rm is the rounding mode.
3282 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
3283 */
3284 function format( n, i, rm, caller ) {
3285 var c0, e, ne, len, str;
3286
3287 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
3288 ? rm | 0 : ROUNDING_MODE;
3289
3290 if ( !n.c ) return n.toString();
3291 c0 = n.c[0];
3292 ne = n.e;
3293
3294 if ( i == null ) {
3295 str = coeffToString( n.c );
3296 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
3297 ? toExponential( str, ne )
3298 : toFixedPoint( str, ne );
3299 } else {
3300 n = round( new BigNumber(n), i, rm );
3301
3302 // n.e may have changed if the value was rounded up.
3303 e = n.e;
3304
3305 str = coeffToString( n.c );
3306 len = str.length;
3307
3308 // toPrecision returns exponential notation if the number of significant digits
3309 // specified is less than the number of digits necessary to represent the integer
3310 // part of the value in fixed-point notation.
3311
3312 // Exponential notation.
3313 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
3314
3315 // Append zeros?
3316 for ( ; len < i; str += '0', len++ );
3317 str = toExponential( str, e );
3318
3319 // Fixed-point notation.
3320 } else {
3321 i -= ne;
3322 str = toFixedPoint( str, e );
3323
3324 // Append zeros?
3325 if ( e + 1 > len ) {
3326 if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
3327 } else {
3328 i += e - len;
3329 if ( i > 0 ) {
3330 if ( e + 1 == len ) str += '.';
3331 for ( ; i--; str += '0' );
3332 }
3333 }
3334 }
3335 }
3336
3337 return n.s < 0 && c0 ? '-' + str : str;
3338 }
3339
3340
3341 // Handle BigNumber.max and BigNumber.min.
3342 function maxOrMin( args, method ) {
3343 var m, n,
3344 i = 0;
3345
3346 if ( isArray( args[0] ) ) args = args[0];
3347 m = new BigNumber( args[0] );
3348
3349 for ( ; ++i < args.length; ) {
3350 n = new BigNumber( args[i] );
3351
3352 // If any number is NaN, return NaN.
3353 if ( !n.s ) {
3354 m = n;
3355 break;
3356 } else if ( method.call( m, n ) ) {
3357 m = n;
3358 }
3359 }
3360
3361 return m;
3362 }
3363
3364
3365 /*
3366 * Return true if n is an integer in range, otherwise throw.
3367 * Use for argument validation when ERRORS is true.
3368 */
3369 function intValidatorWithErrors( n, min, max, caller, name ) {
3370 if ( n < min || n > max || n != truncate(n) ) {
3371 raise( caller, ( name || 'decimal places' ) +
3372 ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
3373 }
3374
3375 return true;
3376 }
3377
3378
3379 /*
3380 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
3381 * Called by minus, plus and times.
3382 */
3383 function normalise( n, c, e ) {
3384 var i = 1,
3385 j = c.length;
3386
3387 // Remove trailing zeros.
3388 for ( ; !c[--j]; c.pop() );
3389
3390 // Calculate the base 10 exponent. First get the number of digits of c[0].
3391 for ( j = c[0]; j >= 10; j /= 10, i++ );
3392
3393 // Overflow?
3394 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
3395
3396 // Infinity.
3397 n.c = n.e = null;
3398
3399 // Underflow?
3400 } else if ( e < MIN_EXP ) {
3401
3402 // Zero.
3403 n.c = [ n.e = 0 ];
3404 } else {
3405 n.e = e;
3406 n.c = c;
3407 }
3408
3409 return n;
3410 }
3411
3412
3413 // Handle values that fail the validity test in BigNumber.
3414 parseNumeric = (function () {
3415 var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
3416 dotAfter = /^([^.]+)\.$/,
3417 dotBefore = /^\.([^.]+)$/,
3418 isInfinityOrNaN = /^-?(Infinity|NaN)$/,
3419 whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
3420
3421 return function ( x, str, num, b ) {
3422 var base,
3423 s = num ? str : str.replace( whitespaceOrPlus, '' );
3424
3425 // No exception on ±Infinity or NaN.
3426 if ( isInfinityOrNaN.test(s) ) {
3427 x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
3428 } else {
3429 if ( !num ) {
3430
3431 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
3432 s = s.replace( basePrefix, function ( m, p1, p2 ) {
3433 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
3434 return !b || b == base ? p1 : m;
3435 });
3436
3437 if (b) {
3438 base = b;
3439
3440 // E.g. '1.' to '1', '.1' to '0.1'
3441 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
3442 }
3443
3444 if ( str != s ) return new BigNumber( s, base );
3445 }
3446
3447 // 'new BigNumber() not a number: {n}'
3448 // 'new BigNumber() not a base {b} number: {n}'
3449 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
3450 x.s = null;
3451 }
3452
3453 x.c = x.e = null;
3454 id = 0;
3455 }
3456 })();
3457
3458
3459 // Throw a BigNumber Error.
3460 function raise( caller, msg, val ) {
3461 var error = new Error( [
3462 'new BigNumber', // 0
3463 'cmp', // 1
3464 'config', // 2
3465 'div', // 3
3466 'divToInt', // 4
3467 'eq', // 5
3468 'gt', // 6
3469 'gte', // 7
3470 'lt', // 8
3471 'lte', // 9
3472 'minus', // 10
3473 'mod', // 11
3474 'plus', // 12
3475 'precision', // 13
3476 'random', // 14
3477 'round', // 15
3478 'shift', // 16
3479 'times', // 17
3480 'toDigits', // 18
3481 'toExponential', // 19
3482 'toFixed', // 20
3483 'toFormat', // 21
3484 'toFraction', // 22
3485 'pow', // 23
3486 'toPrecision', // 24
3487 'toString', // 25
3488 'BigNumber' // 26
3489 ][caller] + '() ' + msg + ': ' + val );
3490
3491 error.name = 'BigNumber Error';
3492 id = 0;
3493 throw error;
3494 }
3495
3496
3497 /*
3498 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
3499 * If r is truthy, it is known that there are more digits after the rounding digit.
3500 */
3501 function round( x, sd, rm, r ) {
3502 var d, i, j, k, n, ni, rd,
3503 xc = x.c,
3504 pows10 = POWS_TEN;
3505
3506 // if x is not Infinity or NaN...
3507 if (xc) {
3508
3509 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
3510 // n is a base 1e14 number, the value of the element of array x.c containing rd.
3511 // ni is the index of n within x.c.
3512 // d is the number of digits of n.
3513 // i is the index of rd within n including leading zeros.
3514 // j is the actual index of rd within n (if < 0, rd is a leading zero).
3515 out: {
3516
3517 // Get the number of digits of the first element of xc.
3518 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
3519 i = sd - d;
3520
3521 // If the rounding digit is in the first element of xc...
3522 if ( i < 0 ) {
3523 i += LOG_BASE;
3524 j = sd;
3525 n = xc[ ni = 0 ];
3526
3527 // Get the rounding digit at index j of n.
3528 rd = n / pows10[ d - j - 1 ] % 10 | 0;
3529 } else {
3530 ni = mathceil( ( i + 1 ) / LOG_BASE );
3531
3532 if ( ni >= xc.length ) {
3533
3534 if (r) {
3535
3536 // Needed by sqrt.
3537 for ( ; xc.length <= ni; xc.push(0) );
3538 n = rd = 0;
3539 d = 1;
3540 i %= LOG_BASE;
3541 j = i - LOG_BASE + 1;
3542 } else {
3543 break out;
3544 }
3545 } else {
3546 n = k = xc[ni];
3547
3548 // Get the number of digits of n.
3549 for ( d = 1; k >= 10; k /= 10, d++ );
3550
3551 // Get the index of rd within n.
3552 i %= LOG_BASE;
3553
3554 // Get the index of rd within n, adjusted for leading zeros.
3555 // The number of leading zeros of n is given by LOG_BASE - d.
3556 j = i - LOG_BASE + d;
3557
3558 // Get the rounding digit at index j of n.
3559 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
3560 }
3561 }
3562
3563 r = r || sd < 0 ||
3564
3565 // Are there any non-zero digits after the rounding digit?
3566 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
3567 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
3568 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
3569
3570 r = rm < 4
3571 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
3572 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
3573
3574 // Check whether the digit to the left of the rounding digit is odd.
3575 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
3576 rm == ( x.s < 0 ? 8 : 7 ) );
3577
3578 if ( sd < 1 || !xc[0] ) {
3579 xc.length = 0;
3580
3581 if (r) {
3582
3583 // Convert sd to decimal places.
3584 sd -= x.e + 1;
3585
3586 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
3587 xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
3588 x.e = -sd || 0;
3589 } else {
3590
3591 // Zero.
3592 xc[0] = x.e = 0;
3593 }
3594
3595 return x;
3596 }
3597
3598 // Remove excess digits.
3599 if ( i == 0 ) {
3600 xc.length = ni;
3601 k = 1;
3602 ni--;
3603 } else {
3604 xc.length = ni + 1;
3605 k = pows10[ LOG_BASE - i ];
3606
3607 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
3608 // j > 0 means i > number of leading zeros of n.
3609 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
3610 }
3611
3612 // Round up?
3613 if (r) {
3614
3615 for ( ; ; ) {
3616
3617 // If the digit to be rounded up is in the first element of xc...
3618 if ( ni == 0 ) {
3619
3620 // i will be the length of xc[0] before k is added.
3621 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
3622 j = xc[0] += k;
3623 for ( k = 1; j >= 10; j /= 10, k++ );
3624
3625 // if i != k the length has increased.
3626 if ( i != k ) {
3627 x.e++;
3628 if ( xc[0] == BASE ) xc[0] = 1;
3629 }
3630
3631 break;
3632 } else {
3633 xc[ni] += k;
3634 if ( xc[ni] != BASE ) break;
3635 xc[ni--] = 0;
3636 k = 1;
3637 }
3638 }
3639 }
3640
3641 // Remove trailing zeros.
3642 for ( i = xc.length; xc[--i] === 0; xc.pop() );
3643 }
3644
3645 // Overflow? Infinity.
3646 if ( x.e > MAX_EXP ) {
3647 x.c = x.e = null;
3648
3649 // Underflow? Zero.
3650 } else if ( x.e < MIN_EXP ) {
3651 x.c = [ x.e = 0 ];
3652 }
3653 }
3654
3655 return x;
3656 }
3657
3658
3659 // PROTOTYPE/INSTANCE METHODS
3660
3661
3662 /*
3663 * Return a new BigNumber whose value is the absolute value of this BigNumber.
3664 */
3665 P.absoluteValue = P.abs = function () {
3666 var x = new BigNumber(this);
3667 if ( x.s < 0 ) x.s = 1;
3668 return x;
3669 };
3670
3671
3672 /*
3673 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
3674 * number in the direction of Infinity.
3675 */
3676 P.ceil = function () {
3677 return round( new BigNumber(this), this.e + 1, 2 );
3678 };
3679
3680
3681 /*
3682 * Return
3683 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
3684 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
3685 * 0 if they have the same value,
3686 * or null if the value of either is NaN.
3687 */
3688 P.comparedTo = P.cmp = function ( y, b ) {
3689 id = 1;
3690 return compare( this, new BigNumber( y, b ) );
3691 };
3692
3693
3694 /*
3695 * Return the number of decimal places of the value of this BigNumber, or null if the value
3696 * of this BigNumber is ±Infinity or NaN.
3697 */
3698 P.decimalPlaces = P.dp = function () {
3699 var n, v,
3700 c = this.c;
3701
3702 if ( !c ) return null;
3703 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
3704
3705 // Subtract the number of trailing zeros of the last number.
3706 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
3707 if ( n < 0 ) n = 0;
3708
3709 return n;
3710 };
3711
3712
3713 /*
3714 * n / 0 = I
3715 * n / N = N
3716 * n / I = 0
3717 * 0 / n = 0
3718 * 0 / 0 = N
3719 * 0 / N = N
3720 * 0 / I = 0
3721 * N / n = N
3722 * N / 0 = N
3723 * N / N = N
3724 * N / I = N
3725 * I / n = I
3726 * I / 0 = I
3727 * I / N = N
3728 * I / I = N
3729 *
3730 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
3731 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
3732 */
3733 P.dividedBy = P.div = function ( y, b ) {
3734 id = 3;
3735 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
3736 };
3737
3738
3739 /*
3740 * Return a new BigNumber whose value is the integer part of dividing the value of this
3741 * BigNumber by the value of BigNumber(y, b).
3742 */
3743 P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
3744 id = 4;
3745 return div( this, new BigNumber( y, b ), 0, 1 );
3746 };
3747
3748
3749 /*
3750 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
3751 * otherwise returns false.
3752 */
3753 P.equals = P.eq = function ( y, b ) {
3754 id = 5;
3755 return compare( this, new BigNumber( y, b ) ) === 0;
3756 };
3757
3758
3759 /*
3760 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
3761 * number in the direction of -Infinity.
3762 */
3763 P.floor = function () {
3764 return round( new BigNumber(this), this.e + 1, 3 );
3765 };
3766
3767
3768 /*
3769 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
3770 * otherwise returns false.
3771 */
3772 P.greaterThan = P.gt = function ( y, b ) {
3773 id = 6;
3774 return compare( this, new BigNumber( y, b ) ) > 0;
3775 };
3776
3777
3778 /*
3779 * Return true if the value of this BigNumber is greater than or equal to the value of
3780 * BigNumber(y, b), otherwise returns false.
3781 */
3782 P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
3783 id = 7;
3784 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
3785
3786 };
3787
3788
3789 /*
3790 * Return true if the value of this BigNumber is a finite number, otherwise returns false.
3791 */
3792 P.isFinite = function () {
3793 return !!this.c;
3794 };
3795
3796
3797 /*
3798 * Return true if the value of this BigNumber is an integer, otherwise return false.
3799 */
3800 P.isInteger = P.isInt = function () {
3801 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
3802 };
3803
3804
3805 /*
3806 * Return true if the value of this BigNumber is NaN, otherwise returns false.
3807 */
3808 P.isNaN = function () {
3809 return !this.s;
3810 };
3811
3812
3813 /*
3814 * Return true if the value of this BigNumber is negative, otherwise returns false.
3815 */
3816 P.isNegative = P.isNeg = function () {
3817 return this.s < 0;
3818 };
3819
3820
3821 /*
3822 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
3823 */
3824 P.isZero = function () {
3825 return !!this.c && this.c[0] == 0;
3826 };
3827
3828
3829 /*
3830 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
3831 * otherwise returns false.
3832 */
3833 P.lessThan = P.lt = function ( y, b ) {
3834 id = 8;
3835 return compare( this, new BigNumber( y, b ) ) < 0;
3836 };
3837
3838
3839 /*
3840 * Return true if the value of this BigNumber is less than or equal to the value of
3841 * BigNumber(y, b), otherwise returns false.
3842 */
3843 P.lessThanOrEqualTo = P.lte = function ( y, b ) {
3844 id = 9;
3845 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
3846 };
3847
3848
3849 /*
3850 * n - 0 = n
3851 * n - N = N
3852 * n - I = -I
3853 * 0 - n = -n
3854 * 0 - 0 = 0
3855 * 0 - N = N
3856 * 0 - I = -I
3857 * N - n = N
3858 * N - 0 = N
3859 * N - N = N
3860 * N - I = N
3861 * I - n = I
3862 * I - 0 = I
3863 * I - N = N
3864 * I - I = N
3865 *
3866 * Return a new BigNumber whose value is the value of this BigNumber minus the value of
3867 * BigNumber(y, b).
3868 */
3869 P.minus = P.sub = function ( y, b ) {
3870 var i, j, t, xLTy,
3871 x = this,
3872 a = x.s;
3873
3874 id = 10;
3875 y = new BigNumber( y, b );
3876 b = y.s;
3877
3878 // Either NaN?
3879 if ( !a || !b ) return new BigNumber(NaN);
3880
3881 // Signs differ?
3882 if ( a != b ) {
3883 y.s = -b;
3884 return x.plus(y);
3885 }
3886
3887 var xe = x.e / LOG_BASE,
3888 ye = y.e / LOG_BASE,
3889 xc = x.c,
3890 yc = y.c;
3891
3892 if ( !xe || !ye ) {
3893
3894 // Either Infinity?
3895 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
3896
3897 // Either zero?
3898 if ( !xc[0] || !yc[0] ) {
3899
3900 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
3901 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
3902
3903 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
3904 ROUNDING_MODE == 3 ? -0 : 0 );
3905 }
3906 }
3907
3908 xe = bitFloor(xe);
3909 ye = bitFloor(ye);
3910 xc = xc.slice();
3911
3912 // Determine which is the bigger number.
3913 if ( a = xe - ye ) {
3914
3915 if ( xLTy = a < 0 ) {
3916 a = -a;
3917 t = xc;
3918 } else {
3919 ye = xe;
3920 t = yc;
3921 }
3922
3923 t.reverse();
3924
3925 // Prepend zeros to equalise exponents.
3926 for ( b = a; b--; t.push(0) );
3927 t.reverse();
3928 } else {
3929
3930 // Exponents equal. Check digit by digit.
3931 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
3932
3933 for ( a = b = 0; b < j; b++ ) {
3934
3935 if ( xc[b] != yc[b] ) {
3936 xLTy = xc[b] < yc[b];
3937 break;
3938 }
3939 }
3940 }
3941
3942 // x < y? Point xc to the array of the bigger number.
3943 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
3944
3945 b = ( j = yc.length ) - ( i = xc.length );
3946
3947 // Append zeros to xc if shorter.
3948 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
3949 if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
3950 b = BASE - 1;
3951
3952 // Subtract yc from xc.
3953 for ( ; j > a; ) {
3954
3955 if ( xc[--j] < yc[j] ) {
3956 for ( i = j; i && !xc[--i]; xc[i] = b );
3957 --xc[i];
3958 xc[j] += BASE;
3959 }
3960
3961 xc[j] -= yc[j];
3962 }
3963
3964 // Remove leading zeros and adjust exponent accordingly.
3965 for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
3966
3967 // Zero?
3968 if ( !xc[0] ) {
3969
3970 // Following IEEE 754 (2008) 6.3,
3971 // n - n = +0 but n - n = -0 when rounding towards -Infinity.
3972 y.s = ROUNDING_MODE == 3 ? -1 : 1;
3973 y.c = [ y.e = 0 ];
3974 return y;
3975 }
3976
3977 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
3978 // for finite x and y.
3979 return normalise( y, xc, ye );
3980 };
3981
3982
3983 /*
3984 * n % 0 = N
3985 * n % N = N
3986 * n % I = n
3987 * 0 % n = 0
3988 * -0 % n = -0
3989 * 0 % 0 = N
3990 * 0 % N = N
3991 * 0 % I = 0
3992 * N % n = N
3993 * N % 0 = N
3994 * N % N = N
3995 * N % I = N
3996 * I % n = N
3997 * I % 0 = N
3998 * I % N = N
3999 * I % I = N
4000 *
4001 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
4002 * BigNumber(y, b). The result depends on the value of MODULO_MODE.
4003 */
4004 P.modulo = P.mod = function ( y, b ) {
4005 var q, s,
4006 x = this;
4007
4008 id = 11;
4009 y = new BigNumber( y, b );
4010
4011 // Return NaN if x is Infinity or NaN, or y is NaN or zero.
4012 if ( !x.c || !y.s || y.c && !y.c[0] ) {
4013 return new BigNumber(NaN);
4014
4015 // Return x if y is Infinity or x is zero.
4016 } else if ( !y.c || x.c && !x.c[0] ) {
4017 return new BigNumber(x);
4018 }
4019
4020 if ( MODULO_MODE == 9 ) {
4021
4022 // Euclidian division: q = sign(y) * floor(x / abs(y))
4023 // r = x - qy where 0 <= r < abs(y)
4024 s = y.s;
4025 y.s = 1;
4026 q = div( x, y, 0, 3 );
4027 y.s = s;
4028 q.s *= s;
4029 } else {
4030 q = div( x, y, 0, MODULO_MODE );
4031 }
4032
4033 return x.minus( q.times(y) );
4034 };
4035
4036
4037 /*
4038 * Return a new BigNumber whose value is the value of this BigNumber negated,
4039 * i.e. multiplied by -1.
4040 */
4041 P.negated = P.neg = function () {
4042 var x = new BigNumber(this);
4043 x.s = -x.s || null;
4044 return x;
4045 };
4046
4047
4048 /*
4049 * n + 0 = n
4050 * n + N = N
4051 * n + I = I
4052 * 0 + n = n
4053 * 0 + 0 = 0
4054 * 0 + N = N
4055 * 0 + I = I
4056 * N + n = N
4057 * N + 0 = N
4058 * N + N = N
4059 * N + I = N
4060 * I + n = I
4061 * I + 0 = I
4062 * I + N = N
4063 * I + I = I
4064 *
4065 * Return a new BigNumber whose value is the value of this BigNumber plus the value of
4066 * BigNumber(y, b).
4067 */
4068 P.plus = P.add = function ( y, b ) {
4069 var t,
4070 x = this,
4071 a = x.s;
4072
4073 id = 12;
4074 y = new BigNumber( y, b );
4075 b = y.s;
4076
4077 // Either NaN?
4078 if ( !a || !b ) return new BigNumber(NaN);
4079
4080 // Signs differ?
4081 if ( a != b ) {
4082 y.s = -b;
4083 return x.minus(y);
4084 }
4085
4086 var xe = x.e / LOG_BASE,
4087 ye = y.e / LOG_BASE,
4088 xc = x.c,
4089 yc = y.c;
4090
4091 if ( !xe || !ye ) {
4092
4093 // Return ±Infinity if either ±Infinity.
4094 if ( !xc || !yc ) return new BigNumber( a / 0 );
4095
4096 // Either zero?
4097 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
4098 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
4099 }
4100
4101 xe = bitFloor(xe);
4102 ye = bitFloor(ye);
4103 xc = xc.slice();
4104
4105 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
4106 if ( a = xe - ye ) {
4107 if ( a > 0 ) {
4108 ye = xe;
4109 t = yc;
4110 } else {
4111 a = -a;
4112 t = xc;
4113 }
4114
4115 t.reverse();
4116 for ( ; a--; t.push(0) );
4117 t.reverse();
4118 }
4119
4120 a = xc.length;
4121 b = yc.length;
4122
4123 // Point xc to the longer array, and b to the shorter length.
4124 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
4125
4126 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
4127 for ( a = 0; b; ) {
4128 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
4129 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
4130 }
4131
4132 if (a) {
4133 xc = [a].concat(xc);
4134 ++ye;
4135 }
4136
4137 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
4138 // ye = MAX_EXP + 1 possible
4139 return normalise( y, xc, ye );
4140 };
4141
4142
4143 /*
4144 * Return the number of significant digits of the value of this BigNumber.
4145 *
4146 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
4147 */
4148 P.precision = P.sd = function (z) {
4149 var n, v,
4150 x = this,
4151 c = x.c;
4152
4153 // 'precision() argument not a boolean or binary digit: {z}'
4154 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
4155 if (ERRORS) raise( 13, 'argument' + notBool, z );
4156 if ( z != !!z ) z = null;
4157 }
4158
4159 if ( !c ) return null;
4160 v = c.length - 1;
4161 n = v * LOG_BASE + 1;
4162
4163 if ( v = c[v] ) {
4164
4165 // Subtract the number of trailing zeros of the last element.
4166 for ( ; v % 10 == 0; v /= 10, n-- );
4167
4168 // Add the number of digits of the first element.
4169 for ( v = c[0]; v >= 10; v /= 10, n++ );
4170 }
4171
4172 if ( z && x.e + 1 > n ) n = x.e + 1;
4173
4174 return n;
4175 };
4176
4177
4178 /*
4179 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
4180 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
4181 * omitted.
4182 *
4183 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4184 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4185 *
4186 * 'round() decimal places out of range: {dp}'
4187 * 'round() decimal places not an integer: {dp}'
4188 * 'round() rounding mode not an integer: {rm}'
4189 * 'round() rounding mode out of range: {rm}'
4190 */
4191 P.round = function ( dp, rm ) {
4192 var n = new BigNumber(this);
4193
4194 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
4195 round( n, ~~dp + this.e + 1, rm == null ||
4196 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
4197 }
4198
4199 return n;
4200 };
4201
4202
4203 /*
4204 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
4205 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
4206 *
4207 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
4208 *
4209 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
4210 * otherwise.
4211 *
4212 * 'shift() argument not an integer: {k}'
4213 * 'shift() argument out of range: {k}'
4214 */
4215 P.shift = function (k) {
4216 var n = this;
4217 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
4218
4219 // k < 1e+21, or truncate(k) will produce exponential notation.
4220 ? n.times( '1e' + truncate(k) )
4221 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
4222 ? n.s * ( k < 0 ? 0 : 1 / 0 )
4223 : n );
4224 };
4225
4226
4227 /*
4228 * sqrt(-n) = N
4229 * sqrt( N) = N
4230 * sqrt(-I) = N
4231 * sqrt( I) = I
4232 * sqrt( 0) = 0
4233 * sqrt(-0) = -0
4234 *
4235 * Return a new BigNumber whose value is the square root of the value of this BigNumber,
4236 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
4237 */
4238 P.squareRoot = P.sqrt = function () {
4239 var m, n, r, rep, t,
4240 x = this,
4241 c = x.c,
4242 s = x.s,
4243 e = x.e,
4244 dp = DECIMAL_PLACES + 4,
4245 half = new BigNumber('0.5');
4246
4247 // Negative/NaN/Infinity/zero?
4248 if ( s !== 1 || !c || !c[0] ) {
4249 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
4250 }
4251
4252 // Initial estimate.
4253 s = Math.sqrt( +x );
4254
4255 // Math.sqrt underflow/overflow?
4256 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
4257 if ( s == 0 || s == 1 / 0 ) {
4258 n = coeffToString(c);
4259 if ( ( n.length + e ) % 2 == 0 ) n += '0';
4260 s = Math.sqrt(n);
4261 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
4262
4263 if ( s == 1 / 0 ) {
4264 n = '1e' + e;
4265 } else {
4266 n = s.toExponential();
4267 n = n.slice( 0, n.indexOf('e') + 1 ) + e;
4268 }
4269
4270 r = new BigNumber(n);
4271 } else {
4272 r = new BigNumber( s + '' );
4273 }
4274
4275 // Check for zero.
4276 // r could be zero if MIN_EXP is changed after the this value was created.
4277 // This would cause a division by zero (x/t) and hence Infinity below, which would cause
4278 // coeffToString to throw.
4279 if ( r.c[0] ) {
4280 e = r.e;
4281 s = e + dp;
4282 if ( s < 3 ) s = 0;
4283
4284 // Newton-Raphson iteration.
4285 for ( ; ; ) {
4286 t = r;
4287 r = half.times( t.plus( div( x, t, dp, 1 ) ) );
4288
4289 if ( coeffToString( t.c ).slice( 0, s ) === ( n =
4290 coeffToString( r.c ) ).slice( 0, s ) ) {
4291
4292 // The exponent of r may here be one less than the final result exponent,
4293 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
4294 // are indexed correctly.
4295 if ( r.e < e ) --s;
4296 n = n.slice( s - 3, s + 1 );
4297
4298 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
4299 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
4300 // iteration.
4301 if ( n == '9999' || !rep && n == '4999' ) {
4302
4303 // On the first iteration only, check to see if rounding up gives the
4304 // exact result as the nines may infinitely repeat.
4305 if ( !rep ) {
4306 round( t, t.e + DECIMAL_PLACES + 2, 0 );
4307
4308 if ( t.times(t).eq(x) ) {
4309 r = t;
4310 break;
4311 }
4312 }
4313
4314 dp += 4;
4315 s += 4;
4316 rep = 1;
4317 } else {
4318
4319 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
4320 // result. If not, then there are further digits and m will be truthy.
4321 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
4322
4323 // Truncate to the first rounding digit.
4324 round( r, r.e + DECIMAL_PLACES + 2, 1 );
4325 m = !r.times(r).eq(x);
4326 }
4327
4328 break;
4329 }
4330 }
4331 }
4332 }
4333
4334 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
4335 };
4336
4337
4338 /*
4339 * n * 0 = 0
4340 * n * N = N
4341 * n * I = I
4342 * 0 * n = 0
4343 * 0 * 0 = 0
4344 * 0 * N = N
4345 * 0 * I = N
4346 * N * n = N
4347 * N * 0 = N
4348 * N * N = N
4349 * N * I = N
4350 * I * n = I
4351 * I * 0 = N
4352 * I * N = N
4353 * I * I = I
4354 *
4355 * Return a new BigNumber whose value is the value of this BigNumber times the value of
4356 * BigNumber(y, b).
4357 */
4358 P.times = P.mul = function ( y, b ) {
4359 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
4360 base, sqrtBase,
4361 x = this,
4362 xc = x.c,
4363 yc = ( id = 17, y = new BigNumber( y, b ) ).c;
4364
4365 // Either NaN, ±Infinity or ±0?
4366 if ( !xc || !yc || !xc[0] || !yc[0] ) {
4367
4368 // Return NaN if either is NaN, or one is 0 and the other is Infinity.
4369 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
4370 y.c = y.e = y.s = null;
4371 } else {
4372 y.s *= x.s;
4373
4374 // Return ±Infinity if either is ±Infinity.
4375 if ( !xc || !yc ) {
4376 y.c = y.e = null;
4377
4378 // Return ±0 if either is ±0.
4379 } else {
4380 y.c = [0];
4381 y.e = 0;
4382 }
4383 }
4384
4385 return y;
4386 }
4387
4388 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
4389 y.s *= x.s;
4390 xcL = xc.length;
4391 ycL = yc.length;
4392
4393 // Ensure xc points to longer array and xcL to its length.
4394 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
4395
4396 // Initialise the result array with zeros.
4397 for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
4398
4399 base = BASE;
4400 sqrtBase = SQRT_BASE;
4401
4402 for ( i = ycL; --i >= 0; ) {
4403 c = 0;
4404 ylo = yc[i] % sqrtBase;
4405 yhi = yc[i] / sqrtBase | 0;
4406
4407 for ( k = xcL, j = i + k; j > i; ) {
4408 xlo = xc[--k] % sqrtBase;
4409 xhi = xc[k] / sqrtBase | 0;
4410 m = yhi * xlo + xhi * ylo;
4411 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
4412 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
4413 zc[j--] = xlo % base;
4414 }
4415
4416 zc[j] = c;
4417 }
4418
4419 if (c) {
4420 ++e;
4421 } else {
4422 zc.splice(0, 1);
4423 }
4424
4425 return normalise( y, zc, e );
4426 };
4427
4428
4429 /*
4430 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
4431 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
4432 *
4433 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
4434 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4435 *
4436 * 'toDigits() precision out of range: {sd}'
4437 * 'toDigits() precision not an integer: {sd}'
4438 * 'toDigits() rounding mode not an integer: {rm}'
4439 * 'toDigits() rounding mode out of range: {rm}'
4440 */
4441 P.toDigits = function ( sd, rm ) {
4442 var n = new BigNumber(this);
4443 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
4444 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
4445 return sd ? round( n, sd, rm ) : n;
4446 };
4447
4448
4449 /*
4450 * Return a string representing the value of this BigNumber in exponential notation and
4451 * rounded using ROUNDING_MODE to dp fixed decimal places.
4452 *
4453 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4454 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4455 *
4456 * 'toExponential() decimal places not an integer: {dp}'
4457 * 'toExponential() decimal places out of range: {dp}'
4458 * 'toExponential() rounding mode not an integer: {rm}'
4459 * 'toExponential() rounding mode out of range: {rm}'
4460 */
4461 P.toExponential = function ( dp, rm ) {
4462 return format( this,
4463 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
4464 };
4465
4466
4467 /*
4468 * Return a string representing the value of this BigNumber in fixed-point notation rounding
4469 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
4470 *
4471 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
4472 * but e.g. (-0.00001).toFixed(0) is '-0'.
4473 *
4474 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4475 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4476 *
4477 * 'toFixed() decimal places not an integer: {dp}'
4478 * 'toFixed() decimal places out of range: {dp}'
4479 * 'toFixed() rounding mode not an integer: {rm}'
4480 * 'toFixed() rounding mode out of range: {rm}'
4481 */
4482 P.toFixed = function ( dp, rm ) {
4483 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
4484 ? ~~dp + this.e + 1 : null, rm, 20 );
4485 };
4486
4487
4488 /*
4489 * Return a string representing the value of this BigNumber in fixed-point notation rounded
4490 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
4491 * of the FORMAT object (see BigNumber.config).
4492 *
4493 * FORMAT = {
4494 * decimalSeparator : '.',
4495 * groupSeparator : ',',
4496 * groupSize : 3,
4497 * secondaryGroupSize : 0,
4498 * fractionGroupSeparator : '\xA0', // non-breaking space
4499 * fractionGroupSize : 0
4500 * };
4501 *
4502 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4503 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4504 *
4505 * 'toFormat() decimal places not an integer: {dp}'
4506 * 'toFormat() decimal places out of range: {dp}'
4507 * 'toFormat() rounding mode not an integer: {rm}'
4508 * 'toFormat() rounding mode out of range: {rm}'
4509 */
4510 P.toFormat = function ( dp, rm ) {
4511 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
4512 ? ~~dp + this.e + 1 : null, rm, 21 );
4513
4514 if ( this.c ) {
4515 var i,
4516 arr = str.split('.'),
4517 g1 = +FORMAT.groupSize,
4518 g2 = +FORMAT.secondaryGroupSize,
4519 groupSeparator = FORMAT.groupSeparator,
4520 intPart = arr[0],
4521 fractionPart = arr[1],
4522 isNeg = this.s < 0,
4523 intDigits = isNeg ? intPart.slice(1) : intPart,
4524 len = intDigits.length;
4525
4526 if (g2) i = g1, g1 = g2, g2 = i, len -= i;
4527
4528 if ( g1 > 0 && len > 0 ) {
4529 i = len % g1 || g1;
4530 intPart = intDigits.substr( 0, i );
4531
4532 for ( ; i < len; i += g1 ) {
4533 intPart += groupSeparator + intDigits.substr( i, g1 );
4534 }
4535
4536 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
4537 if (isNeg) intPart = '-' + intPart;
4538 }
4539
4540 str = fractionPart
4541 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
4542 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
4543 '$&' + FORMAT.fractionGroupSeparator )
4544 : fractionPart )
4545 : intPart;
4546 }
4547
4548 return str;
4549 };
4550
4551
4552 /*
4553 * Return a string array representing the value of this BigNumber as a simple fraction with
4554 * an integer numerator and an integer denominator. The denominator will be a positive
4555 * non-zero value less than or equal to the specified maximum denominator. If a maximum
4556 * denominator is not specified, the denominator will be the lowest value necessary to
4557 * represent the number exactly.
4558 *
4559 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
4560 *
4561 * 'toFraction() max denominator not an integer: {md}'
4562 * 'toFraction() max denominator out of range: {md}'
4563 */
4564 P.toFraction = function (md) {
4565 var arr, d0, d2, e, exp, n, n0, q, s,
4566 k = ERRORS,
4567 x = this,
4568 xc = x.c,
4569 d = new BigNumber(ONE),
4570 n1 = d0 = new BigNumber(ONE),
4571 d1 = n0 = new BigNumber(ONE);
4572
4573 if ( md != null ) {
4574 ERRORS = false;
4575 n = new BigNumber(md);
4576 ERRORS = k;
4577
4578 if ( !( k = n.isInt() ) || n.lt(ONE) ) {
4579
4580 if (ERRORS) {
4581 raise( 22,
4582 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
4583 }
4584
4585 // ERRORS is false:
4586 // If md is a finite non-integer >= 1, round it to an integer and use it.
4587 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
4588 }
4589 }
4590
4591 if ( !xc ) return x.toString();
4592 s = coeffToString(xc);
4593
4594 // Determine initial denominator.
4595 // d is a power of 10 and the minimum max denominator that specifies the value exactly.
4596 e = d.e = s.length - x.e - 1;
4597 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
4598 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
4599
4600 exp = MAX_EXP;
4601 MAX_EXP = 1 / 0;
4602 n = new BigNumber(s);
4603
4604 // n0 = d1 = 0
4605 n0.c[0] = 0;
4606
4607 for ( ; ; ) {
4608 q = div( n, d, 0, 1 );
4609 d2 = d0.plus( q.times(d1) );
4610 if ( d2.cmp(md) == 1 ) break;
4611 d0 = d1;
4612 d1 = d2;
4613 n1 = n0.plus( q.times( d2 = n1 ) );
4614 n0 = d2;
4615 d = n.minus( q.times( d2 = d ) );
4616 n = d2;
4617 }
4618
4619 d2 = div( md.minus(d0), d1, 0, 1 );
4620 n0 = n0.plus( d2.times(n1) );
4621 d0 = d0.plus( d2.times(d1) );
4622 n0.s = n1.s = x.s;
4623 e *= 2;
4624
4625 // Determine which fraction is closer to x, n0/d0 or n1/d1
4626 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
4627 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
4628 ? [ n1.toString(), d1.toString() ]
4629 : [ n0.toString(), d0.toString() ];
4630
4631 MAX_EXP = exp;
4632 return arr;
4633 };
4634
4635
4636 /*
4637 * Return the value of this BigNumber converted to a number primitive.
4638 */
4639 P.toNumber = function () {
4640 return +this;
4641 };
4642
4643
4644 /*
4645 * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
4646 * If m is present, return the result modulo m.
4647 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
4648 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
4649 * ROUNDING_MODE.
4650 *
4651 * The modular power operation works efficiently when x, n, and m are positive integers,
4652 * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
4653 *
4654 * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
4655 * [m] {number|string|BigNumber} The modulus.
4656 *
4657 * 'pow() exponent not an integer: {n}'
4658 * 'pow() exponent out of range: {n}'
4659 *
4660 * Performs 54 loop iterations for n of 9007199254740991.
4661 */
4662 P.toPower = P.pow = function ( n, m ) {
4663 var k, y, z,
4664 i = mathfloor( n < 0 ? -n : +n ),
4665 x = this;
4666
4667 if ( m != null ) {
4668 id = 23;
4669 m = new BigNumber(m);
4670 }
4671
4672 // Pass ±Infinity to Math.pow if exponent is out of range.
4673 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
4674 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
4675 parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
4676 k = Math.pow( +x, n );
4677 return new BigNumber( m ? k % m : k );
4678 }
4679
4680 if (m) {
4681 if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
4682 x = x.mod(m);
4683 } else {
4684 z = m;
4685
4686 // Nullify m so only a single mod operation is performed at the end.
4687 m = null;
4688 }
4689 } else if (POW_PRECISION) {
4690
4691 // Truncating each coefficient array to a length of k after each multiplication
4692 // equates to truncating significant digits to POW_PRECISION + [28, 41],
4693 // i.e. there will be a minimum of 28 guard digits retained.
4694 // (Using + 1.5 would give [9, 21] guard digits.)
4695 k = mathceil( POW_PRECISION / LOG_BASE + 2 );
4696 }
4697
4698 y = new BigNumber(ONE);
4699
4700 for ( ; ; ) {
4701 if ( i % 2 ) {
4702 y = y.times(x);
4703 if ( !y.c ) break;
4704 if (k) {
4705 if ( y.c.length > k ) y.c.length = k;
4706 } else if (m) {
4707 y = y.mod(m);
4708 }
4709 }
4710
4711 i = mathfloor( i / 2 );
4712 if ( !i ) break;
4713 x = x.times(x);
4714 if (k) {
4715 if ( x.c && x.c.length > k ) x.c.length = k;
4716 } else if (m) {
4717 x = x.mod(m);
4718 }
4719 }
4720
4721 if (m) return y;
4722 if ( n < 0 ) y = ONE.div(y);
4723
4724 return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
4725 };
4726
4727
4728 /*
4729 * Return a string representing the value of this BigNumber rounded to sd significant digits
4730 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
4731 * necessary to represent the integer part of the value in fixed-point notation, then use
4732 * exponential notation.
4733 *
4734 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
4735 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4736 *
4737 * 'toPrecision() precision not an integer: {sd}'
4738 * 'toPrecision() precision out of range: {sd}'
4739 * 'toPrecision() rounding mode not an integer: {rm}'
4740 * 'toPrecision() rounding mode out of range: {rm}'
4741 */
4742 P.toPrecision = function ( sd, rm ) {
4743 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
4744 ? sd | 0 : null, rm, 24 );
4745 };
4746
4747
4748 /*
4749 * Return a string representing the value of this BigNumber in base b, or base 10 if b is
4750 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
4751 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
4752 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
4753 * TO_EXP_NEG, return exponential notation.
4754 *
4755 * [b] {number} Integer, 2 to 64 inclusive.
4756 *
4757 * 'toString() base not an integer: {b}'
4758 * 'toString() base out of range: {b}'
4759 */
4760 P.toString = function (b) {
4761 var str,
4762 n = this,
4763 s = n.s,
4764 e = n.e;
4765
4766 // Infinity or NaN?
4767 if ( e === null ) {
4768
4769 if (s) {
4770 str = 'Infinity';
4771 if ( s < 0 ) str = '-' + str;
4772 } else {
4773 str = 'NaN';
4774 }
4775 } else {
4776 str = coeffToString( n.c );
4777
4778 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
4779 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
4780 ? toExponential( str, e )
4781 : toFixedPoint( str, e );
4782 } else {
4783 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
4784 }
4785
4786 if ( s < 0 && n.c[0] ) str = '-' + str;
4787 }
4788
4789 return str;
4790 };
4791
4792
4793 /*
4794 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
4795 * number.
4796 */
4797 P.truncated = P.trunc = function () {
4798 return round( new BigNumber(this), this.e + 1, 1 );
4799 };
4800
4801
4802 /*
4803 * Return as toString, but do not accept a base argument, and include the minus sign for
4804 * negative zero.
4805 */
4806 P.valueOf = P.toJSON = function () {
4807 var str,
4808 n = this,
4809 e = n.e;
4810
4811 if ( e === null ) return n.toString();
4812
4813 str = coeffToString( n.c );
4814
4815 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
4816 ? toExponential( str, e )
4817 : toFixedPoint( str, e );
4818
4819 return n.s < 0 ? '-' + str : str;
4820 };
4821
4822
4823 P.isBigNumber = true;
4824
4825 if ( config != null ) BigNumber.config(config);
4826
4827 return BigNumber;
4828 }
4829
4830
4831 // PRIVATE HELPER FUNCTIONS
4832
4833
4834 function bitFloor(n) {
4835 var i = n | 0;
4836 return n > 0 || n === i ? i : i - 1;
4837 }
4838
4839
4840 // Return a coefficient array as a string of base 10 digits.
4841 function coeffToString(a) {
4842 var s, z,
4843 i = 1,
4844 j = a.length,
4845 r = a[0] + '';
4846
4847 for ( ; i < j; ) {
4848 s = a[i++] + '';
4849 z = LOG_BASE - s.length;
4850 for ( ; z--; s = '0' + s );
4851 r += s;
4852 }
4853
4854 // Determine trailing zeros.
4855 for ( j = r.length; r.charCodeAt(--j) === 48; );
4856 return r.slice( 0, j + 1 || 1 );
4857 }
4858
4859
4860 // Compare the value of BigNumbers x and y.
4861 function compare( x, y ) {
4862 var a, b,
4863 xc = x.c,
4864 yc = y.c,
4865 i = x.s,
4866 j = y.s,
4867 k = x.e,
4868 l = y.e;
4869
4870 // Either NaN?
4871 if ( !i || !j ) return null;
4872
4873 a = xc && !xc[0];
4874 b = yc && !yc[0];
4875
4876 // Either zero?
4877 if ( a || b ) return a ? b ? 0 : -j : i;
4878
4879 // Signs differ?
4880 if ( i != j ) return i;
4881
4882 a = i < 0;
4883 b = k == l;
4884
4885 // Either Infinity?
4886 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
4887
4888 // Compare exponents.
4889 if ( !b ) return k > l ^ a ? 1 : -1;
4890
4891 j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
4892
4893 // Compare digit by digit.
4894 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
4895
4896 // Compare lengths.
4897 return k == l ? 0 : k > l ^ a ? 1 : -1;
4898 }
4899
4900
4901 /*
4902 * Return true if n is a valid number in range, otherwise false.
4903 * Use for argument validation when ERRORS is false.
4904 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
4905 */
4906 function intValidatorNoErrors( n, min, max ) {
4907 return ( n = truncate(n) ) >= min && n <= max;
4908 }
4909
4910
4911 function isArray(obj) {
4912 return Object.prototype.toString.call(obj) == '[object Array]';
4913 }
4914
4915
4916 /*
4917 * Convert string of baseIn to an array of numbers of baseOut.
4918 * Eg. convertBase('255', 10, 16) returns [15, 15].
4919 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
4920 */
4921 function toBaseOut( str, baseIn, baseOut ) {
4922 var j,
4923 arr = [0],
4924 arrL,
4925 i = 0,
4926 len = str.length;
4927
4928 for ( ; i < len; ) {
4929 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
4930 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
4931
4932 for ( ; j < arr.length; j++ ) {
4933
4934 if ( arr[j] > baseOut - 1 ) {
4935 if ( arr[j + 1] == null ) arr[j + 1] = 0;
4936 arr[j + 1] += arr[j] / baseOut | 0;
4937 arr[j] %= baseOut;
4938 }
4939 }
4940 }
4941
4942 return arr.reverse();
4943 }
4944
4945
4946 function toExponential( str, e ) {
4947 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
4948 ( e < 0 ? 'e' : 'e+' ) + e;
4949 }
4950
4951
4952 function toFixedPoint( str, e ) {
4953 var len, z;
4954
4955 // Negative exponent?
4956 if ( e < 0 ) {
4957
4958 // Prepend zeros.
4959 for ( z = '0.'; ++e; z += '0' );
4960 str = z + str;
4961
4962 // Positive exponent
4963 } else {
4964 len = str.length;
4965
4966 // Append zeros.
4967 if ( ++e > len ) {
4968 for ( z = '0', e -= len; --e; z += '0' );
4969 str += z;
4970 } else if ( e < len ) {
4971 str = str.slice( 0, e ) + '.' + str.slice(e);
4972 }
4973 }
4974
4975 return str;
4976 }
4977
4978
4979 function truncate(n) {
4980 n = parseFloat(n);
4981 return n < 0 ? mathceil(n) : mathfloor(n);
4982 }
4983
4984
4985 // EXPORT
4986
4987
4988 BigNumber = constructorFactory();
4989 BigNumber['default'] = BigNumber.BigNumber = BigNumber;
4990
4991
4992 // AMD.
4993 if ( typeof define == 'function' && define.amd ) {
4994 define( function () { return BigNumber; } );
4995
4996 // Node.js and other environments that support module.exports.
4997 } else if ( typeof module != 'undefined' && module.exports ) {
4998 module.exports = BigNumber;
4999
5000 // Browser.
5001 } else {
5002 if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
5003 globalObj.BigNumber = BigNumber;
5004 }
5005})(this);
5006
5007},{}],20:[function(require,module,exports){
5008// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
5009// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
5010// NOTE: SIGHASH byte ignored AND restricted, truncate before use
5011
5012var Buffer = require('safe-buffer').Buffer
5013
5014function check (buffer) {
5015 if (buffer.length < 8) return false
5016 if (buffer.length > 72) return false
5017 if (buffer[0] !== 0x30) return false
5018 if (buffer[1] !== buffer.length - 2) return false
5019 if (buffer[2] !== 0x02) return false
5020
5021 var lenR = buffer[3]
5022 if (lenR === 0) return false
5023 if (5 + lenR >= buffer.length) return false
5024 if (buffer[4 + lenR] !== 0x02) return false
5025
5026 var lenS = buffer[5 + lenR]
5027 if (lenS === 0) return false
5028 if ((6 + lenR + lenS) !== buffer.length) return false
5029
5030 if (buffer[4] & 0x80) return false
5031 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false
5032
5033 if (buffer[lenR + 6] & 0x80) return false
5034 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false
5035 return true
5036}
5037
5038function decode (buffer) {
5039 if (buffer.length < 8) throw new Error('DER sequence length is too short')
5040 if (buffer.length > 72) throw new Error('DER sequence length is too long')
5041 if (buffer[0] !== 0x30) throw new Error('Expected DER sequence')
5042 if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid')
5043 if (buffer[2] !== 0x02) throw new Error('Expected DER integer')
5044
5045 var lenR = buffer[3]
5046 if (lenR === 0) throw new Error('R length is zero')
5047 if (5 + lenR >= buffer.length) throw new Error('R length is too long')
5048 if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)')
5049
5050 var lenS = buffer[5 + lenR]
5051 if (lenS === 0) throw new Error('S length is zero')
5052 if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid')
5053
5054 if (buffer[4] & 0x80) throw new Error('R value is negative')
5055 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded')
5056
5057 if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative')
5058 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded')
5059
5060 // non-BIP66 - extract R, S values
5061 return {
5062 r: buffer.slice(4, 4 + lenR),
5063 s: buffer.slice(6 + lenR)
5064 }
5065}
5066
5067/*
5068 * Expects r and s to be positive DER integers.
5069 *
5070 * The DER format uses the most significant bit as a sign bit (& 0x80).
5071 * If the significant bit is set AND the integer is positive, a 0x00 is prepended.
5072 *
5073 * Examples:
5074 *
5075 * 0 => 0x00
5076 * 1 => 0x01
5077 * -1 => 0xff
5078 * 127 => 0x7f
5079 * -127 => 0x81
5080 * 128 => 0x0080
5081 * -128 => 0x80
5082 * 255 => 0x00ff
5083 * -255 => 0xff01
5084 * 16300 => 0x3fac
5085 * -16300 => 0xc054
5086 * 62300 => 0x00f35c
5087 * -62300 => 0xff0ca4
5088*/
5089function encode (r, s) {
5090 var lenR = r.length
5091 var lenS = s.length
5092 if (lenR === 0) throw new Error('R length is zero')
5093 if (lenS === 0) throw new Error('S length is zero')
5094 if (lenR > 33) throw new Error('R length is too long')
5095 if (lenS > 33) throw new Error('S length is too long')
5096 if (r[0] & 0x80) throw new Error('R value is negative')
5097 if (s[0] & 0x80) throw new Error('S value is negative')
5098 if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded')
5099 if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded')
5100
5101 var signature = Buffer.allocUnsafe(6 + lenR + lenS)
5102
5103 // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
5104 signature[0] = 0x30
5105 signature[1] = signature.length - 2
5106 signature[2] = 0x02
5107 signature[3] = r.length
5108 r.copy(signature, 4)
5109 signature[4 + lenR] = 0x02
5110 signature[5 + lenR] = s.length
5111 s.copy(signature, 6 + lenR)
5112
5113 return signature
5114}
5115
5116module.exports = {
5117 check: check,
5118 decode: decode,
5119 encode: encode
5120}
5121
5122},{"safe-buffer":156}],21:[function(require,module,exports){
5123(function (module, exports) {
5124 'use strict';
5125
5126 // Utils
5127 function assert (val, msg) {
5128 if (!val) throw new Error(msg || 'Assertion failed');
5129 }
5130
5131 // Could use `inherits` module, but don't want to move from single file
5132 // architecture yet.
5133 function inherits (ctor, superCtor) {
5134 ctor.super_ = superCtor;
5135 var TempCtor = function () {};
5136 TempCtor.prototype = superCtor.prototype;
5137 ctor.prototype = new TempCtor();
5138 ctor.prototype.constructor = ctor;
5139 }
5140
5141 // BN
5142
5143 function BN (number, base, endian) {
5144 if (BN.isBN(number)) {
5145 return number;
5146 }
5147
5148 this.negative = 0;
5149 this.words = null;
5150 this.length = 0;
5151
5152 // Reduction context
5153 this.red = null;
5154
5155 if (number !== null) {
5156 if (base === 'le' || base === 'be') {
5157 endian = base;
5158 base = 10;
5159 }
5160
5161 this._init(number || 0, base || 10, endian || 'be');
5162 }
5163 }
5164 if (typeof module === 'object') {
5165 module.exports = BN;
5166 } else {
5167 exports.BN = BN;
5168 }
5169
5170 BN.BN = BN;
5171 BN.wordSize = 26;
5172
5173 var Buffer;
5174 try {
5175 Buffer = require('buffer').Buffer;
5176 } catch (e) {
5177 }
5178
5179 BN.isBN = function isBN (num) {
5180 if (num instanceof BN) {
5181 return true;
5182 }
5183
5184 return num !== null && typeof num === 'object' &&
5185 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
5186 };
5187
5188 BN.max = function max (left, right) {
5189 if (left.cmp(right) > 0) return left;
5190 return right;
5191 };
5192
5193 BN.min = function min (left, right) {
5194 if (left.cmp(right) < 0) return left;
5195 return right;
5196 };
5197
5198 BN.prototype._init = function init (number, base, endian) {
5199 if (typeof number === 'number') {
5200 return this._initNumber(number, base, endian);
5201 }
5202
5203 if (typeof number === 'object') {
5204 return this._initArray(number, base, endian);
5205 }
5206
5207 if (base === 'hex') {
5208 base = 16;
5209 }
5210 assert(base === (base | 0) && base >= 2 && base <= 36);
5211
5212 number = number.toString().replace(/\s+/g, '');
5213 var start = 0;
5214 if (number[0] === '-') {
5215 start++;
5216 }
5217
5218 if (base === 16) {
5219 this._parseHex(number, start);
5220 } else {
5221 this._parseBase(number, base, start);
5222 }
5223
5224 if (number[0] === '-') {
5225 this.negative = 1;
5226 }
5227
5228 this.strip();
5229
5230 if (endian !== 'le') return;
5231
5232 this._initArray(this.toArray(), base, endian);
5233 };
5234
5235 BN.prototype._initNumber = function _initNumber (number, base, endian) {
5236 if (number < 0) {
5237 this.negative = 1;
5238 number = -number;
5239 }
5240 if (number < 0x4000000) {
5241 this.words = [ number & 0x3ffffff ];
5242 this.length = 1;
5243 } else if (number < 0x10000000000000) {
5244 this.words = [
5245 number & 0x3ffffff,
5246 (number / 0x4000000) & 0x3ffffff
5247 ];
5248 this.length = 2;
5249 } else {
5250 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
5251 this.words = [
5252 number & 0x3ffffff,
5253 (number / 0x4000000) & 0x3ffffff,
5254 1
5255 ];
5256 this.length = 3;
5257 }
5258
5259 if (endian !== 'le') return;
5260
5261 // Reverse the bytes
5262 this._initArray(this.toArray(), base, endian);
5263 };
5264
5265 BN.prototype._initArray = function _initArray (number, base, endian) {
5266 // Perhaps a Uint8Array
5267 assert(typeof number.length === 'number');
5268 if (number.length <= 0) {
5269 this.words = [ 0 ];
5270 this.length = 1;
5271 return this;
5272 }
5273
5274 this.length = Math.ceil(number.length / 3);
5275 this.words = new Array(this.length);
5276 for (var i = 0; i < this.length; i++) {
5277 this.words[i] = 0;
5278 }
5279
5280 var j, w;
5281 var off = 0;
5282 if (endian === 'be') {
5283 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
5284 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
5285 this.words[j] |= (w << off) & 0x3ffffff;
5286 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
5287 off += 24;
5288 if (off >= 26) {
5289 off -= 26;
5290 j++;
5291 }
5292 }
5293 } else if (endian === 'le') {
5294 for (i = 0, j = 0; i < number.length; i += 3) {
5295 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
5296 this.words[j] |= (w << off) & 0x3ffffff;
5297 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
5298 off += 24;
5299 if (off >= 26) {
5300 off -= 26;
5301 j++;
5302 }
5303 }
5304 }
5305 return this.strip();
5306 };
5307
5308 function parseHex (str, start, end) {
5309 var r = 0;
5310 var len = Math.min(str.length, end);
5311 for (var i = start; i < len; i++) {
5312 var c = str.charCodeAt(i) - 48;
5313
5314 r <<= 4;
5315
5316 // 'a' - 'f'
5317 if (c >= 49 && c <= 54) {
5318 r |= c - 49 + 0xa;
5319
5320 // 'A' - 'F'
5321 } else if (c >= 17 && c <= 22) {
5322 r |= c - 17 + 0xa;
5323
5324 // '0' - '9'
5325 } else {
5326 r |= c & 0xf;
5327 }
5328 }
5329 return r;
5330 }
5331
5332 BN.prototype._parseHex = function _parseHex (number, start) {
5333 // Create possibly bigger array to ensure that it fits the number
5334 this.length = Math.ceil((number.length - start) / 6);
5335 this.words = new Array(this.length);
5336 for (var i = 0; i < this.length; i++) {
5337 this.words[i] = 0;
5338 }
5339
5340 var j, w;
5341 // Scan 24-bit chunks and add them to the number
5342 var off = 0;
5343 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
5344 w = parseHex(number, i, i + 6);
5345 this.words[j] |= (w << off) & 0x3ffffff;
5346 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
5347 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
5348 off += 24;
5349 if (off >= 26) {
5350 off -= 26;
5351 j++;
5352 }
5353 }
5354 if (i + 6 !== start) {
5355 w = parseHex(number, start, i + 6);
5356 this.words[j] |= (w << off) & 0x3ffffff;
5357 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
5358 }
5359 this.strip();
5360 };
5361
5362 function parseBase (str, start, end, mul) {
5363 var r = 0;
5364 var len = Math.min(str.length, end);
5365 for (var i = start; i < len; i++) {
5366 var c = str.charCodeAt(i) - 48;
5367
5368 r *= mul;
5369
5370 // 'a'
5371 if (c >= 49) {
5372 r += c - 49 + 0xa;
5373
5374 // 'A'
5375 } else if (c >= 17) {
5376 r += c - 17 + 0xa;
5377
5378 // '0' - '9'
5379 } else {
5380 r += c;
5381 }
5382 }
5383 return r;
5384 }
5385
5386 BN.prototype._parseBase = function _parseBase (number, base, start) {
5387 // Initialize as zero
5388 this.words = [ 0 ];
5389 this.length = 1;
5390
5391 // Find length of limb in base
5392 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
5393 limbLen++;
5394 }
5395 limbLen--;
5396 limbPow = (limbPow / base) | 0;
5397
5398 var total = number.length - start;
5399 var mod = total % limbLen;
5400 var end = Math.min(total, total - mod) + start;
5401
5402 var word = 0;
5403 for (var i = start; i < end; i += limbLen) {
5404 word = parseBase(number, i, i + limbLen, base);
5405
5406 this.imuln(limbPow);
5407 if (this.words[0] + word < 0x4000000) {
5408 this.words[0] += word;
5409 } else {
5410 this._iaddn(word);
5411 }
5412 }
5413
5414 if (mod !== 0) {
5415 var pow = 1;
5416 word = parseBase(number, i, number.length, base);
5417
5418 for (i = 0; i < mod; i++) {
5419 pow *= base;
5420 }
5421
5422 this.imuln(pow);
5423 if (this.words[0] + word < 0x4000000) {
5424 this.words[0] += word;
5425 } else {
5426 this._iaddn(word);
5427 }
5428 }
5429 };
5430
5431 BN.prototype.copy = function copy (dest) {
5432 dest.words = new Array(this.length);
5433 for (var i = 0; i < this.length; i++) {
5434 dest.words[i] = this.words[i];
5435 }
5436 dest.length = this.length;
5437 dest.negative = this.negative;
5438 dest.red = this.red;
5439 };
5440
5441 BN.prototype.clone = function clone () {
5442 var r = new BN(null);
5443 this.copy(r);
5444 return r;
5445 };
5446
5447 BN.prototype._expand = function _expand (size) {
5448 while (this.length < size) {
5449 this.words[this.length++] = 0;
5450 }
5451 return this;
5452 };
5453
5454 // Remove leading `0` from `this`
5455 BN.prototype.strip = function strip () {
5456 while (this.length > 1 && this.words[this.length - 1] === 0) {
5457 this.length--;
5458 }
5459 return this._normSign();
5460 };
5461
5462 BN.prototype._normSign = function _normSign () {
5463 // -0 = 0
5464 if (this.length === 1 && this.words[0] === 0) {
5465 this.negative = 0;
5466 }
5467 return this;
5468 };
5469
5470 BN.prototype.inspect = function inspect () {
5471 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
5472 };
5473
5474 /*
5475
5476 var zeros = [];
5477 var groupSizes = [];
5478 var groupBases = [];
5479
5480 var s = '';
5481 var i = -1;
5482 while (++i < BN.wordSize) {
5483 zeros[i] = s;
5484 s += '0';
5485 }
5486 groupSizes[0] = 0;
5487 groupSizes[1] = 0;
5488 groupBases[0] = 0;
5489 groupBases[1] = 0;
5490 var base = 2 - 1;
5491 while (++base < 36 + 1) {
5492 var groupSize = 0;
5493 var groupBase = 1;
5494 while (groupBase < (1 << BN.wordSize) / base) {
5495 groupBase *= base;
5496 groupSize += 1;
5497 }
5498 groupSizes[base] = groupSize;
5499 groupBases[base] = groupBase;
5500 }
5501
5502 */
5503
5504 var zeros = [
5505 '',
5506 '0',
5507 '00',
5508 '000',
5509 '0000',
5510 '00000',
5511 '000000',
5512 '0000000',
5513 '00000000',
5514 '000000000',
5515 '0000000000',
5516 '00000000000',
5517 '000000000000',
5518 '0000000000000',
5519 '00000000000000',
5520 '000000000000000',
5521 '0000000000000000',
5522 '00000000000000000',
5523 '000000000000000000',
5524 '0000000000000000000',
5525 '00000000000000000000',
5526 '000000000000000000000',
5527 '0000000000000000000000',
5528 '00000000000000000000000',
5529 '000000000000000000000000',
5530 '0000000000000000000000000'
5531 ];
5532
5533 var groupSizes = [
5534 0, 0,
5535 25, 16, 12, 11, 10, 9, 8,
5536 8, 7, 7, 7, 7, 6, 6,
5537 6, 6, 6, 6, 6, 5, 5,
5538 5, 5, 5, 5, 5, 5, 5,
5539 5, 5, 5, 5, 5, 5, 5
5540 ];
5541
5542 var groupBases = [
5543 0, 0,
5544 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
5545 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
5546 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
5547 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
5548 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
5549 ];
5550
5551 BN.prototype.toString = function toString (base, padding) {
5552 base = base || 10;
5553 padding = padding | 0 || 1;
5554
5555 var out;
5556 if (base === 16 || base === 'hex') {
5557 out = '';
5558 var off = 0;
5559 var carry = 0;
5560 for (var i = 0; i < this.length; i++) {
5561 var w = this.words[i];
5562 var word = (((w << off) | carry) & 0xffffff).toString(16);
5563 carry = (w >>> (24 - off)) & 0xffffff;
5564 if (carry !== 0 || i !== this.length - 1) {
5565 out = zeros[6 - word.length] + word + out;
5566 } else {
5567 out = word + out;
5568 }
5569 off += 2;
5570 if (off >= 26) {
5571 off -= 26;
5572 i--;
5573 }
5574 }
5575 if (carry !== 0) {
5576 out = carry.toString(16) + out;
5577 }
5578 while (out.length % padding !== 0) {
5579 out = '0' + out;
5580 }
5581 if (this.negative !== 0) {
5582 out = '-' + out;
5583 }
5584 return out;
5585 }
5586
5587 if (base === (base | 0) && base >= 2 && base <= 36) {
5588 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
5589 var groupSize = groupSizes[base];
5590 // var groupBase = Math.pow(base, groupSize);
5591 var groupBase = groupBases[base];
5592 out = '';
5593 var c = this.clone();
5594 c.negative = 0;
5595 while (!c.isZero()) {
5596 var r = c.modn(groupBase).toString(base);
5597 c = c.idivn(groupBase);
5598
5599 if (!c.isZero()) {
5600 out = zeros[groupSize - r.length] + r + out;
5601 } else {
5602 out = r + out;
5603 }
5604 }
5605 if (this.isZero()) {
5606 out = '0' + out;
5607 }
5608 while (out.length % padding !== 0) {
5609 out = '0' + out;
5610 }
5611 if (this.negative !== 0) {
5612 out = '-' + out;
5613 }
5614 return out;
5615 }
5616
5617 assert(false, 'Base should be between 2 and 36');
5618 };
5619
5620 BN.prototype.toNumber = function toNumber () {
5621 var ret = this.words[0];
5622 if (this.length === 2) {
5623 ret += this.words[1] * 0x4000000;
5624 } else if (this.length === 3 && this.words[2] === 0x01) {
5625 // NOTE: at this stage it is known that the top bit is set
5626 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
5627 } else if (this.length > 2) {
5628 assert(false, 'Number can only safely store up to 53 bits');
5629 }
5630 return (this.negative !== 0) ? -ret : ret;
5631 };
5632
5633 BN.prototype.toJSON = function toJSON () {
5634 return this.toString(16);
5635 };
5636
5637 BN.prototype.toBuffer = function toBuffer (endian, length) {
5638 assert(typeof Buffer !== 'undefined');
5639 return this.toArrayLike(Buffer, endian, length);
5640 };
5641
5642 BN.prototype.toArray = function toArray (endian, length) {
5643 return this.toArrayLike(Array, endian, length);
5644 };
5645
5646 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
5647 var byteLength = this.byteLength();
5648 var reqLength = length || Math.max(1, byteLength);
5649 assert(byteLength <= reqLength, 'byte array longer than desired length');
5650 assert(reqLength > 0, 'Requested array length <= 0');
5651
5652 this.strip();
5653 var littleEndian = endian === 'le';
5654 var res = new ArrayType(reqLength);
5655
5656 var b, i;
5657 var q = this.clone();
5658 if (!littleEndian) {
5659 // Assume big-endian
5660 for (i = 0; i < reqLength - byteLength; i++) {
5661 res[i] = 0;
5662 }
5663
5664 for (i = 0; !q.isZero(); i++) {
5665 b = q.andln(0xff);
5666 q.iushrn(8);
5667
5668 res[reqLength - i - 1] = b;
5669 }
5670 } else {
5671 for (i = 0; !q.isZero(); i++) {
5672 b = q.andln(0xff);
5673 q.iushrn(8);
5674
5675 res[i] = b;
5676 }
5677
5678 for (; i < reqLength; i++) {
5679 res[i] = 0;
5680 }
5681 }
5682
5683 return res;
5684 };
5685
5686 if (Math.clz32) {
5687 BN.prototype._countBits = function _countBits (w) {
5688 return 32 - Math.clz32(w);
5689 };
5690 } else {
5691 BN.prototype._countBits = function _countBits (w) {
5692 var t = w;
5693 var r = 0;
5694 if (t >= 0x1000) {
5695 r += 13;
5696 t >>>= 13;
5697 }
5698 if (t >= 0x40) {
5699 r += 7;
5700 t >>>= 7;
5701 }
5702 if (t >= 0x8) {
5703 r += 4;
5704 t >>>= 4;
5705 }
5706 if (t >= 0x02) {
5707 r += 2;
5708 t >>>= 2;
5709 }
5710 return r + t;
5711 };
5712 }
5713
5714 BN.prototype._zeroBits = function _zeroBits (w) {
5715 // Short-cut
5716 if (w === 0) return 26;
5717
5718 var t = w;
5719 var r = 0;
5720 if ((t & 0x1fff) === 0) {
5721 r += 13;
5722 t >>>= 13;
5723 }
5724 if ((t & 0x7f) === 0) {
5725 r += 7;
5726 t >>>= 7;
5727 }
5728 if ((t & 0xf) === 0) {
5729 r += 4;
5730 t >>>= 4;
5731 }
5732 if ((t & 0x3) === 0) {
5733 r += 2;
5734 t >>>= 2;
5735 }
5736 if ((t & 0x1) === 0) {
5737 r++;
5738 }
5739 return r;
5740 };
5741
5742 // Return number of used bits in a BN
5743 BN.prototype.bitLength = function bitLength () {
5744 var w = this.words[this.length - 1];
5745 var hi = this._countBits(w);
5746 return (this.length - 1) * 26 + hi;
5747 };
5748
5749 function toBitArray (num) {
5750 var w = new Array(num.bitLength());
5751
5752 for (var bit = 0; bit < w.length; bit++) {
5753 var off = (bit / 26) | 0;
5754 var wbit = bit % 26;
5755
5756 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
5757 }
5758
5759 return w;
5760 }
5761
5762 // Number of trailing zero bits
5763 BN.prototype.zeroBits = function zeroBits () {
5764 if (this.isZero()) return 0;
5765
5766 var r = 0;
5767 for (var i = 0; i < this.length; i++) {
5768 var b = this._zeroBits(this.words[i]);
5769 r += b;
5770 if (b !== 26) break;
5771 }
5772 return r;
5773 };
5774
5775 BN.prototype.byteLength = function byteLength () {
5776 return Math.ceil(this.bitLength() / 8);
5777 };
5778
5779 BN.prototype.toTwos = function toTwos (width) {
5780 if (this.negative !== 0) {
5781 return this.abs().inotn(width).iaddn(1);
5782 }
5783 return this.clone();
5784 };
5785
5786 BN.prototype.fromTwos = function fromTwos (width) {
5787 if (this.testn(width - 1)) {
5788 return this.notn(width).iaddn(1).ineg();
5789 }
5790 return this.clone();
5791 };
5792
5793 BN.prototype.isNeg = function isNeg () {
5794 return this.negative !== 0;
5795 };
5796
5797 // Return negative clone of `this`
5798 BN.prototype.neg = function neg () {
5799 return this.clone().ineg();
5800 };
5801
5802 BN.prototype.ineg = function ineg () {
5803 if (!this.isZero()) {
5804 this.negative ^= 1;
5805 }
5806
5807 return this;
5808 };
5809
5810 // Or `num` with `this` in-place
5811 BN.prototype.iuor = function iuor (num) {
5812 while (this.length < num.length) {
5813 this.words[this.length++] = 0;
5814 }
5815
5816 for (var i = 0; i < num.length; i++) {
5817 this.words[i] = this.words[i] | num.words[i];
5818 }
5819
5820 return this.strip();
5821 };
5822
5823 BN.prototype.ior = function ior (num) {
5824 assert((this.negative | num.negative) === 0);
5825 return this.iuor(num);
5826 };
5827
5828 // Or `num` with `this`
5829 BN.prototype.or = function or (num) {
5830 if (this.length > num.length) return this.clone().ior(num);
5831 return num.clone().ior(this);
5832 };
5833
5834 BN.prototype.uor = function uor (num) {
5835 if (this.length > num.length) return this.clone().iuor(num);
5836 return num.clone().iuor(this);
5837 };
5838
5839 // And `num` with `this` in-place
5840 BN.prototype.iuand = function iuand (num) {
5841 // b = min-length(num, this)
5842 var b;
5843 if (this.length > num.length) {
5844 b = num;
5845 } else {
5846 b = this;
5847 }
5848
5849 for (var i = 0; i < b.length; i++) {
5850 this.words[i] = this.words[i] & num.words[i];
5851 }
5852
5853 this.length = b.length;
5854
5855 return this.strip();
5856 };
5857
5858 BN.prototype.iand = function iand (num) {
5859 assert((this.negative | num.negative) === 0);
5860 return this.iuand(num);
5861 };
5862
5863 // And `num` with `this`
5864 BN.prototype.and = function and (num) {
5865 if (this.length > num.length) return this.clone().iand(num);
5866 return num.clone().iand(this);
5867 };
5868
5869 BN.prototype.uand = function uand (num) {
5870 if (this.length > num.length) return this.clone().iuand(num);
5871 return num.clone().iuand(this);
5872 };
5873
5874 // Xor `num` with `this` in-place
5875 BN.prototype.iuxor = function iuxor (num) {
5876 // a.length > b.length
5877 var a;
5878 var b;
5879 if (this.length > num.length) {
5880 a = this;
5881 b = num;
5882 } else {
5883 a = num;
5884 b = this;
5885 }
5886
5887 for (var i = 0; i < b.length; i++) {
5888 this.words[i] = a.words[i] ^ b.words[i];
5889 }
5890
5891 if (this !== a) {
5892 for (; i < a.length; i++) {
5893 this.words[i] = a.words[i];
5894 }
5895 }
5896
5897 this.length = a.length;
5898
5899 return this.strip();
5900 };
5901
5902 BN.prototype.ixor = function ixor (num) {
5903 assert((this.negative | num.negative) === 0);
5904 return this.iuxor(num);
5905 };
5906
5907 // Xor `num` with `this`
5908 BN.prototype.xor = function xor (num) {
5909 if (this.length > num.length) return this.clone().ixor(num);
5910 return num.clone().ixor(this);
5911 };
5912
5913 BN.prototype.uxor = function uxor (num) {
5914 if (this.length > num.length) return this.clone().iuxor(num);
5915 return num.clone().iuxor(this);
5916 };
5917
5918 // Not ``this`` with ``width`` bitwidth
5919 BN.prototype.inotn = function inotn (width) {
5920 assert(typeof width === 'number' && width >= 0);
5921
5922 var bytesNeeded = Math.ceil(width / 26) | 0;
5923 var bitsLeft = width % 26;
5924
5925 // Extend the buffer with leading zeroes
5926 this._expand(bytesNeeded);
5927
5928 if (bitsLeft > 0) {
5929 bytesNeeded--;
5930 }
5931
5932 // Handle complete words
5933 for (var i = 0; i < bytesNeeded; i++) {
5934 this.words[i] = ~this.words[i] & 0x3ffffff;
5935 }
5936
5937 // Handle the residue
5938 if (bitsLeft > 0) {
5939 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
5940 }
5941
5942 // And remove leading zeroes
5943 return this.strip();
5944 };
5945
5946 BN.prototype.notn = function notn (width) {
5947 return this.clone().inotn(width);
5948 };
5949
5950 // Set `bit` of `this`
5951 BN.prototype.setn = function setn (bit, val) {
5952 assert(typeof bit === 'number' && bit >= 0);
5953
5954 var off = (bit / 26) | 0;
5955 var wbit = bit % 26;
5956
5957 this._expand(off + 1);
5958
5959 if (val) {
5960 this.words[off] = this.words[off] | (1 << wbit);
5961 } else {
5962 this.words[off] = this.words[off] & ~(1 << wbit);
5963 }
5964
5965 return this.strip();
5966 };
5967
5968 // Add `num` to `this` in-place
5969 BN.prototype.iadd = function iadd (num) {
5970 var r;
5971
5972 // negative + positive
5973 if (this.negative !== 0 && num.negative === 0) {
5974 this.negative = 0;
5975 r = this.isub(num);
5976 this.negative ^= 1;
5977 return this._normSign();
5978
5979 // positive + negative
5980 } else if (this.negative === 0 && num.negative !== 0) {
5981 num.negative = 0;
5982 r = this.isub(num);
5983 num.negative = 1;
5984 return r._normSign();
5985 }
5986
5987 // a.length > b.length
5988 var a, b;
5989 if (this.length > num.length) {
5990 a = this;
5991 b = num;
5992 } else {
5993 a = num;
5994 b = this;
5995 }
5996
5997 var carry = 0;
5998 for (var i = 0; i < b.length; i++) {
5999 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
6000 this.words[i] = r & 0x3ffffff;
6001 carry = r >>> 26;
6002 }
6003 for (; carry !== 0 && i < a.length; i++) {
6004 r = (a.words[i] | 0) + carry;
6005 this.words[i] = r & 0x3ffffff;
6006 carry = r >>> 26;
6007 }
6008
6009 this.length = a.length;
6010 if (carry !== 0) {
6011 this.words[this.length] = carry;
6012 this.length++;
6013 // Copy the rest of the words
6014 } else if (a !== this) {
6015 for (; i < a.length; i++) {
6016 this.words[i] = a.words[i];
6017 }
6018 }
6019
6020 return this;
6021 };
6022
6023 // Add `num` to `this`
6024 BN.prototype.add = function add (num) {
6025 var res;
6026 if (num.negative !== 0 && this.negative === 0) {
6027 num.negative = 0;
6028 res = this.sub(num);
6029 num.negative ^= 1;
6030 return res;
6031 } else if (num.negative === 0 && this.negative !== 0) {
6032 this.negative = 0;
6033 res = num.sub(this);
6034 this.negative = 1;
6035 return res;
6036 }
6037
6038 if (this.length > num.length) return this.clone().iadd(num);
6039
6040 return num.clone().iadd(this);
6041 };
6042
6043 // Subtract `num` from `this` in-place
6044 BN.prototype.isub = function isub (num) {
6045 // this - (-num) = this + num
6046 if (num.negative !== 0) {
6047 num.negative = 0;
6048 var r = this.iadd(num);
6049 num.negative = 1;
6050 return r._normSign();
6051
6052 // -this - num = -(this + num)
6053 } else if (this.negative !== 0) {
6054 this.negative = 0;
6055 this.iadd(num);
6056 this.negative = 1;
6057 return this._normSign();
6058 }
6059
6060 // At this point both numbers are positive
6061 var cmp = this.cmp(num);
6062
6063 // Optimization - zeroify
6064 if (cmp === 0) {
6065 this.negative = 0;
6066 this.length = 1;
6067 this.words[0] = 0;
6068 return this;
6069 }
6070
6071 // a > b
6072 var a, b;
6073 if (cmp > 0) {
6074 a = this;
6075 b = num;
6076 } else {
6077 a = num;
6078 b = this;
6079 }
6080
6081 var carry = 0;
6082 for (var i = 0; i < b.length; i++) {
6083 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
6084 carry = r >> 26;
6085 this.words[i] = r & 0x3ffffff;
6086 }
6087 for (; carry !== 0 && i < a.length; i++) {
6088 r = (a.words[i] | 0) + carry;
6089 carry = r >> 26;
6090 this.words[i] = r & 0x3ffffff;
6091 }
6092
6093 // Copy rest of the words
6094 if (carry === 0 && i < a.length && a !== this) {
6095 for (; i < a.length; i++) {
6096 this.words[i] = a.words[i];
6097 }
6098 }
6099
6100 this.length = Math.max(this.length, i);
6101
6102 if (a !== this) {
6103 this.negative = 1;
6104 }
6105
6106 return this.strip();
6107 };
6108
6109 // Subtract `num` from `this`
6110 BN.prototype.sub = function sub (num) {
6111 return this.clone().isub(num);
6112 };
6113
6114 function smallMulTo (self, num, out) {
6115 out.negative = num.negative ^ self.negative;
6116 var len = (self.length + num.length) | 0;
6117 out.length = len;
6118 len = (len - 1) | 0;
6119
6120 // Peel one iteration (compiler can't do it, because of code complexity)
6121 var a = self.words[0] | 0;
6122 var b = num.words[0] | 0;
6123 var r = a * b;
6124
6125 var lo = r & 0x3ffffff;
6126 var carry = (r / 0x4000000) | 0;
6127 out.words[0] = lo;
6128
6129 for (var k = 1; k < len; k++) {
6130 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
6131 // note that ncarry could be >= 0x3ffffff
6132 var ncarry = carry >>> 26;
6133 var rword = carry & 0x3ffffff;
6134 var maxJ = Math.min(k, num.length - 1);
6135 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
6136 var i = (k - j) | 0;
6137 a = self.words[i] | 0;
6138 b = num.words[j] | 0;
6139 r = a * b + rword;
6140 ncarry += (r / 0x4000000) | 0;
6141 rword = r & 0x3ffffff;
6142 }
6143 out.words[k] = rword | 0;
6144 carry = ncarry | 0;
6145 }
6146 if (carry !== 0) {
6147 out.words[k] = carry | 0;
6148 } else {
6149 out.length--;
6150 }
6151
6152 return out.strip();
6153 }
6154
6155 // TODO(indutny): it may be reasonable to omit it for users who don't need
6156 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
6157 // multiplication (like elliptic secp256k1).
6158 var comb10MulTo = function comb10MulTo (self, num, out) {
6159 var a = self.words;
6160 var b = num.words;
6161 var o = out.words;
6162 var c = 0;
6163 var lo;
6164 var mid;
6165 var hi;
6166 var a0 = a[0] | 0;
6167 var al0 = a0 & 0x1fff;
6168 var ah0 = a0 >>> 13;
6169 var a1 = a[1] | 0;
6170 var al1 = a1 & 0x1fff;
6171 var ah1 = a1 >>> 13;
6172 var a2 = a[2] | 0;
6173 var al2 = a2 & 0x1fff;
6174 var ah2 = a2 >>> 13;
6175 var a3 = a[3] | 0;
6176 var al3 = a3 & 0x1fff;
6177 var ah3 = a3 >>> 13;
6178 var a4 = a[4] | 0;
6179 var al4 = a4 & 0x1fff;
6180 var ah4 = a4 >>> 13;
6181 var a5 = a[5] | 0;
6182 var al5 = a5 & 0x1fff;
6183 var ah5 = a5 >>> 13;
6184 var a6 = a[6] | 0;
6185 var al6 = a6 & 0x1fff;
6186 var ah6 = a6 >>> 13;
6187 var a7 = a[7] | 0;
6188 var al7 = a7 & 0x1fff;
6189 var ah7 = a7 >>> 13;
6190 var a8 = a[8] | 0;
6191 var al8 = a8 & 0x1fff;
6192 var ah8 = a8 >>> 13;
6193 var a9 = a[9] | 0;
6194 var al9 = a9 & 0x1fff;
6195 var ah9 = a9 >>> 13;
6196 var b0 = b[0] | 0;
6197 var bl0 = b0 & 0x1fff;
6198 var bh0 = b0 >>> 13;
6199 var b1 = b[1] | 0;
6200 var bl1 = b1 & 0x1fff;
6201 var bh1 = b1 >>> 13;
6202 var b2 = b[2] | 0;
6203 var bl2 = b2 & 0x1fff;
6204 var bh2 = b2 >>> 13;
6205 var b3 = b[3] | 0;
6206 var bl3 = b3 & 0x1fff;
6207 var bh3 = b3 >>> 13;
6208 var b4 = b[4] | 0;
6209 var bl4 = b4 & 0x1fff;
6210 var bh4 = b4 >>> 13;
6211 var b5 = b[5] | 0;
6212 var bl5 = b5 & 0x1fff;
6213 var bh5 = b5 >>> 13;
6214 var b6 = b[6] | 0;
6215 var bl6 = b6 & 0x1fff;
6216 var bh6 = b6 >>> 13;
6217 var b7 = b[7] | 0;
6218 var bl7 = b7 & 0x1fff;
6219 var bh7 = b7 >>> 13;
6220 var b8 = b[8] | 0;
6221 var bl8 = b8 & 0x1fff;
6222 var bh8 = b8 >>> 13;
6223 var b9 = b[9] | 0;
6224 var bl9 = b9 & 0x1fff;
6225 var bh9 = b9 >>> 13;
6226
6227 out.negative = self.negative ^ num.negative;
6228 out.length = 19;
6229 /* k = 0 */
6230 lo = Math.imul(al0, bl0);
6231 mid = Math.imul(al0, bh0);
6232 mid = (mid + Math.imul(ah0, bl0)) | 0;
6233 hi = Math.imul(ah0, bh0);
6234 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6235 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
6236 w0 &= 0x3ffffff;
6237 /* k = 1 */
6238 lo = Math.imul(al1, bl0);
6239 mid = Math.imul(al1, bh0);
6240 mid = (mid + Math.imul(ah1, bl0)) | 0;
6241 hi = Math.imul(ah1, bh0);
6242 lo = (lo + Math.imul(al0, bl1)) | 0;
6243 mid = (mid + Math.imul(al0, bh1)) | 0;
6244 mid = (mid + Math.imul(ah0, bl1)) | 0;
6245 hi = (hi + Math.imul(ah0, bh1)) | 0;
6246 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6247 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
6248 w1 &= 0x3ffffff;
6249 /* k = 2 */
6250 lo = Math.imul(al2, bl0);
6251 mid = Math.imul(al2, bh0);
6252 mid = (mid + Math.imul(ah2, bl0)) | 0;
6253 hi = Math.imul(ah2, bh0);
6254 lo = (lo + Math.imul(al1, bl1)) | 0;
6255 mid = (mid + Math.imul(al1, bh1)) | 0;
6256 mid = (mid + Math.imul(ah1, bl1)) | 0;
6257 hi = (hi + Math.imul(ah1, bh1)) | 0;
6258 lo = (lo + Math.imul(al0, bl2)) | 0;
6259 mid = (mid + Math.imul(al0, bh2)) | 0;
6260 mid = (mid + Math.imul(ah0, bl2)) | 0;
6261 hi = (hi + Math.imul(ah0, bh2)) | 0;
6262 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6263 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
6264 w2 &= 0x3ffffff;
6265 /* k = 3 */
6266 lo = Math.imul(al3, bl0);
6267 mid = Math.imul(al3, bh0);
6268 mid = (mid + Math.imul(ah3, bl0)) | 0;
6269 hi = Math.imul(ah3, bh0);
6270 lo = (lo + Math.imul(al2, bl1)) | 0;
6271 mid = (mid + Math.imul(al2, bh1)) | 0;
6272 mid = (mid + Math.imul(ah2, bl1)) | 0;
6273 hi = (hi + Math.imul(ah2, bh1)) | 0;
6274 lo = (lo + Math.imul(al1, bl2)) | 0;
6275 mid = (mid + Math.imul(al1, bh2)) | 0;
6276 mid = (mid + Math.imul(ah1, bl2)) | 0;
6277 hi = (hi + Math.imul(ah1, bh2)) | 0;
6278 lo = (lo + Math.imul(al0, bl3)) | 0;
6279 mid = (mid + Math.imul(al0, bh3)) | 0;
6280 mid = (mid + Math.imul(ah0, bl3)) | 0;
6281 hi = (hi + Math.imul(ah0, bh3)) | 0;
6282 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6283 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
6284 w3 &= 0x3ffffff;
6285 /* k = 4 */
6286 lo = Math.imul(al4, bl0);
6287 mid = Math.imul(al4, bh0);
6288 mid = (mid + Math.imul(ah4, bl0)) | 0;
6289 hi = Math.imul(ah4, bh0);
6290 lo = (lo + Math.imul(al3, bl1)) | 0;
6291 mid = (mid + Math.imul(al3, bh1)) | 0;
6292 mid = (mid + Math.imul(ah3, bl1)) | 0;
6293 hi = (hi + Math.imul(ah3, bh1)) | 0;
6294 lo = (lo + Math.imul(al2, bl2)) | 0;
6295 mid = (mid + Math.imul(al2, bh2)) | 0;
6296 mid = (mid + Math.imul(ah2, bl2)) | 0;
6297 hi = (hi + Math.imul(ah2, bh2)) | 0;
6298 lo = (lo + Math.imul(al1, bl3)) | 0;
6299 mid = (mid + Math.imul(al1, bh3)) | 0;
6300 mid = (mid + Math.imul(ah1, bl3)) | 0;
6301 hi = (hi + Math.imul(ah1, bh3)) | 0;
6302 lo = (lo + Math.imul(al0, bl4)) | 0;
6303 mid = (mid + Math.imul(al0, bh4)) | 0;
6304 mid = (mid + Math.imul(ah0, bl4)) | 0;
6305 hi = (hi + Math.imul(ah0, bh4)) | 0;
6306 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6307 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
6308 w4 &= 0x3ffffff;
6309 /* k = 5 */
6310 lo = Math.imul(al5, bl0);
6311 mid = Math.imul(al5, bh0);
6312 mid = (mid + Math.imul(ah5, bl0)) | 0;
6313 hi = Math.imul(ah5, bh0);
6314 lo = (lo + Math.imul(al4, bl1)) | 0;
6315 mid = (mid + Math.imul(al4, bh1)) | 0;
6316 mid = (mid + Math.imul(ah4, bl1)) | 0;
6317 hi = (hi + Math.imul(ah4, bh1)) | 0;
6318 lo = (lo + Math.imul(al3, bl2)) | 0;
6319 mid = (mid + Math.imul(al3, bh2)) | 0;
6320 mid = (mid + Math.imul(ah3, bl2)) | 0;
6321 hi = (hi + Math.imul(ah3, bh2)) | 0;
6322 lo = (lo + Math.imul(al2, bl3)) | 0;
6323 mid = (mid + Math.imul(al2, bh3)) | 0;
6324 mid = (mid + Math.imul(ah2, bl3)) | 0;
6325 hi = (hi + Math.imul(ah2, bh3)) | 0;
6326 lo = (lo + Math.imul(al1, bl4)) | 0;
6327 mid = (mid + Math.imul(al1, bh4)) | 0;
6328 mid = (mid + Math.imul(ah1, bl4)) | 0;
6329 hi = (hi + Math.imul(ah1, bh4)) | 0;
6330 lo = (lo + Math.imul(al0, bl5)) | 0;
6331 mid = (mid + Math.imul(al0, bh5)) | 0;
6332 mid = (mid + Math.imul(ah0, bl5)) | 0;
6333 hi = (hi + Math.imul(ah0, bh5)) | 0;
6334 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6335 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
6336 w5 &= 0x3ffffff;
6337 /* k = 6 */
6338 lo = Math.imul(al6, bl0);
6339 mid = Math.imul(al6, bh0);
6340 mid = (mid + Math.imul(ah6, bl0)) | 0;
6341 hi = Math.imul(ah6, bh0);
6342 lo = (lo + Math.imul(al5, bl1)) | 0;
6343 mid = (mid + Math.imul(al5, bh1)) | 0;
6344 mid = (mid + Math.imul(ah5, bl1)) | 0;
6345 hi = (hi + Math.imul(ah5, bh1)) | 0;
6346 lo = (lo + Math.imul(al4, bl2)) | 0;
6347 mid = (mid + Math.imul(al4, bh2)) | 0;
6348 mid = (mid + Math.imul(ah4, bl2)) | 0;
6349 hi = (hi + Math.imul(ah4, bh2)) | 0;
6350 lo = (lo + Math.imul(al3, bl3)) | 0;
6351 mid = (mid + Math.imul(al3, bh3)) | 0;
6352 mid = (mid + Math.imul(ah3, bl3)) | 0;
6353 hi = (hi + Math.imul(ah3, bh3)) | 0;
6354 lo = (lo + Math.imul(al2, bl4)) | 0;
6355 mid = (mid + Math.imul(al2, bh4)) | 0;
6356 mid = (mid + Math.imul(ah2, bl4)) | 0;
6357 hi = (hi + Math.imul(ah2, bh4)) | 0;
6358 lo = (lo + Math.imul(al1, bl5)) | 0;
6359 mid = (mid + Math.imul(al1, bh5)) | 0;
6360 mid = (mid + Math.imul(ah1, bl5)) | 0;
6361 hi = (hi + Math.imul(ah1, bh5)) | 0;
6362 lo = (lo + Math.imul(al0, bl6)) | 0;
6363 mid = (mid + Math.imul(al0, bh6)) | 0;
6364 mid = (mid + Math.imul(ah0, bl6)) | 0;
6365 hi = (hi + Math.imul(ah0, bh6)) | 0;
6366 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6367 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
6368 w6 &= 0x3ffffff;
6369 /* k = 7 */
6370 lo = Math.imul(al7, bl0);
6371 mid = Math.imul(al7, bh0);
6372 mid = (mid + Math.imul(ah7, bl0)) | 0;
6373 hi = Math.imul(ah7, bh0);
6374 lo = (lo + Math.imul(al6, bl1)) | 0;
6375 mid = (mid + Math.imul(al6, bh1)) | 0;
6376 mid = (mid + Math.imul(ah6, bl1)) | 0;
6377 hi = (hi + Math.imul(ah6, bh1)) | 0;
6378 lo = (lo + Math.imul(al5, bl2)) | 0;
6379 mid = (mid + Math.imul(al5, bh2)) | 0;
6380 mid = (mid + Math.imul(ah5, bl2)) | 0;
6381 hi = (hi + Math.imul(ah5, bh2)) | 0;
6382 lo = (lo + Math.imul(al4, bl3)) | 0;
6383 mid = (mid + Math.imul(al4, bh3)) | 0;
6384 mid = (mid + Math.imul(ah4, bl3)) | 0;
6385 hi = (hi + Math.imul(ah4, bh3)) | 0;
6386 lo = (lo + Math.imul(al3, bl4)) | 0;
6387 mid = (mid + Math.imul(al3, bh4)) | 0;
6388 mid = (mid + Math.imul(ah3, bl4)) | 0;
6389 hi = (hi + Math.imul(ah3, bh4)) | 0;
6390 lo = (lo + Math.imul(al2, bl5)) | 0;
6391 mid = (mid + Math.imul(al2, bh5)) | 0;
6392 mid = (mid + Math.imul(ah2, bl5)) | 0;
6393 hi = (hi + Math.imul(ah2, bh5)) | 0;
6394 lo = (lo + Math.imul(al1, bl6)) | 0;
6395 mid = (mid + Math.imul(al1, bh6)) | 0;
6396 mid = (mid + Math.imul(ah1, bl6)) | 0;
6397 hi = (hi + Math.imul(ah1, bh6)) | 0;
6398 lo = (lo + Math.imul(al0, bl7)) | 0;
6399 mid = (mid + Math.imul(al0, bh7)) | 0;
6400 mid = (mid + Math.imul(ah0, bl7)) | 0;
6401 hi = (hi + Math.imul(ah0, bh7)) | 0;
6402 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6403 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
6404 w7 &= 0x3ffffff;
6405 /* k = 8 */
6406 lo = Math.imul(al8, bl0);
6407 mid = Math.imul(al8, bh0);
6408 mid = (mid + Math.imul(ah8, bl0)) | 0;
6409 hi = Math.imul(ah8, bh0);
6410 lo = (lo + Math.imul(al7, bl1)) | 0;
6411 mid = (mid + Math.imul(al7, bh1)) | 0;
6412 mid = (mid + Math.imul(ah7, bl1)) | 0;
6413 hi = (hi + Math.imul(ah7, bh1)) | 0;
6414 lo = (lo + Math.imul(al6, bl2)) | 0;
6415 mid = (mid + Math.imul(al6, bh2)) | 0;
6416 mid = (mid + Math.imul(ah6, bl2)) | 0;
6417 hi = (hi + Math.imul(ah6, bh2)) | 0;
6418 lo = (lo + Math.imul(al5, bl3)) | 0;
6419 mid = (mid + Math.imul(al5, bh3)) | 0;
6420 mid = (mid + Math.imul(ah5, bl3)) | 0;
6421 hi = (hi + Math.imul(ah5, bh3)) | 0;
6422 lo = (lo + Math.imul(al4, bl4)) | 0;
6423 mid = (mid + Math.imul(al4, bh4)) | 0;
6424 mid = (mid + Math.imul(ah4, bl4)) | 0;
6425 hi = (hi + Math.imul(ah4, bh4)) | 0;
6426 lo = (lo + Math.imul(al3, bl5)) | 0;
6427 mid = (mid + Math.imul(al3, bh5)) | 0;
6428 mid = (mid + Math.imul(ah3, bl5)) | 0;
6429 hi = (hi + Math.imul(ah3, bh5)) | 0;
6430 lo = (lo + Math.imul(al2, bl6)) | 0;
6431 mid = (mid + Math.imul(al2, bh6)) | 0;
6432 mid = (mid + Math.imul(ah2, bl6)) | 0;
6433 hi = (hi + Math.imul(ah2, bh6)) | 0;
6434 lo = (lo + Math.imul(al1, bl7)) | 0;
6435 mid = (mid + Math.imul(al1, bh7)) | 0;
6436 mid = (mid + Math.imul(ah1, bl7)) | 0;
6437 hi = (hi + Math.imul(ah1, bh7)) | 0;
6438 lo = (lo + Math.imul(al0, bl8)) | 0;
6439 mid = (mid + Math.imul(al0, bh8)) | 0;
6440 mid = (mid + Math.imul(ah0, bl8)) | 0;
6441 hi = (hi + Math.imul(ah0, bh8)) | 0;
6442 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6443 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
6444 w8 &= 0x3ffffff;
6445 /* k = 9 */
6446 lo = Math.imul(al9, bl0);
6447 mid = Math.imul(al9, bh0);
6448 mid = (mid + Math.imul(ah9, bl0)) | 0;
6449 hi = Math.imul(ah9, bh0);
6450 lo = (lo + Math.imul(al8, bl1)) | 0;
6451 mid = (mid + Math.imul(al8, bh1)) | 0;
6452 mid = (mid + Math.imul(ah8, bl1)) | 0;
6453 hi = (hi + Math.imul(ah8, bh1)) | 0;
6454 lo = (lo + Math.imul(al7, bl2)) | 0;
6455 mid = (mid + Math.imul(al7, bh2)) | 0;
6456 mid = (mid + Math.imul(ah7, bl2)) | 0;
6457 hi = (hi + Math.imul(ah7, bh2)) | 0;
6458 lo = (lo + Math.imul(al6, bl3)) | 0;
6459 mid = (mid + Math.imul(al6, bh3)) | 0;
6460 mid = (mid + Math.imul(ah6, bl3)) | 0;
6461 hi = (hi + Math.imul(ah6, bh3)) | 0;
6462 lo = (lo + Math.imul(al5, bl4)) | 0;
6463 mid = (mid + Math.imul(al5, bh4)) | 0;
6464 mid = (mid + Math.imul(ah5, bl4)) | 0;
6465 hi = (hi + Math.imul(ah5, bh4)) | 0;
6466 lo = (lo + Math.imul(al4, bl5)) | 0;
6467 mid = (mid + Math.imul(al4, bh5)) | 0;
6468 mid = (mid + Math.imul(ah4, bl5)) | 0;
6469 hi = (hi + Math.imul(ah4, bh5)) | 0;
6470 lo = (lo + Math.imul(al3, bl6)) | 0;
6471 mid = (mid + Math.imul(al3, bh6)) | 0;
6472 mid = (mid + Math.imul(ah3, bl6)) | 0;
6473 hi = (hi + Math.imul(ah3, bh6)) | 0;
6474 lo = (lo + Math.imul(al2, bl7)) | 0;
6475 mid = (mid + Math.imul(al2, bh7)) | 0;
6476 mid = (mid + Math.imul(ah2, bl7)) | 0;
6477 hi = (hi + Math.imul(ah2, bh7)) | 0;
6478 lo = (lo + Math.imul(al1, bl8)) | 0;
6479 mid = (mid + Math.imul(al1, bh8)) | 0;
6480 mid = (mid + Math.imul(ah1, bl8)) | 0;
6481 hi = (hi + Math.imul(ah1, bh8)) | 0;
6482 lo = (lo + Math.imul(al0, bl9)) | 0;
6483 mid = (mid + Math.imul(al0, bh9)) | 0;
6484 mid = (mid + Math.imul(ah0, bl9)) | 0;
6485 hi = (hi + Math.imul(ah0, bh9)) | 0;
6486 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6487 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
6488 w9 &= 0x3ffffff;
6489 /* k = 10 */
6490 lo = Math.imul(al9, bl1);
6491 mid = Math.imul(al9, bh1);
6492 mid = (mid + Math.imul(ah9, bl1)) | 0;
6493 hi = Math.imul(ah9, bh1);
6494 lo = (lo + Math.imul(al8, bl2)) | 0;
6495 mid = (mid + Math.imul(al8, bh2)) | 0;
6496 mid = (mid + Math.imul(ah8, bl2)) | 0;
6497 hi = (hi + Math.imul(ah8, bh2)) | 0;
6498 lo = (lo + Math.imul(al7, bl3)) | 0;
6499 mid = (mid + Math.imul(al7, bh3)) | 0;
6500 mid = (mid + Math.imul(ah7, bl3)) | 0;
6501 hi = (hi + Math.imul(ah7, bh3)) | 0;
6502 lo = (lo + Math.imul(al6, bl4)) | 0;
6503 mid = (mid + Math.imul(al6, bh4)) | 0;
6504 mid = (mid + Math.imul(ah6, bl4)) | 0;
6505 hi = (hi + Math.imul(ah6, bh4)) | 0;
6506 lo = (lo + Math.imul(al5, bl5)) | 0;
6507 mid = (mid + Math.imul(al5, bh5)) | 0;
6508 mid = (mid + Math.imul(ah5, bl5)) | 0;
6509 hi = (hi + Math.imul(ah5, bh5)) | 0;
6510 lo = (lo + Math.imul(al4, bl6)) | 0;
6511 mid = (mid + Math.imul(al4, bh6)) | 0;
6512 mid = (mid + Math.imul(ah4, bl6)) | 0;
6513 hi = (hi + Math.imul(ah4, bh6)) | 0;
6514 lo = (lo + Math.imul(al3, bl7)) | 0;
6515 mid = (mid + Math.imul(al3, bh7)) | 0;
6516 mid = (mid + Math.imul(ah3, bl7)) | 0;
6517 hi = (hi + Math.imul(ah3, bh7)) | 0;
6518 lo = (lo + Math.imul(al2, bl8)) | 0;
6519 mid = (mid + Math.imul(al2, bh8)) | 0;
6520 mid = (mid + Math.imul(ah2, bl8)) | 0;
6521 hi = (hi + Math.imul(ah2, bh8)) | 0;
6522 lo = (lo + Math.imul(al1, bl9)) | 0;
6523 mid = (mid + Math.imul(al1, bh9)) | 0;
6524 mid = (mid + Math.imul(ah1, bl9)) | 0;
6525 hi = (hi + Math.imul(ah1, bh9)) | 0;
6526 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6527 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
6528 w10 &= 0x3ffffff;
6529 /* k = 11 */
6530 lo = Math.imul(al9, bl2);
6531 mid = Math.imul(al9, bh2);
6532 mid = (mid + Math.imul(ah9, bl2)) | 0;
6533 hi = Math.imul(ah9, bh2);
6534 lo = (lo + Math.imul(al8, bl3)) | 0;
6535 mid = (mid + Math.imul(al8, bh3)) | 0;
6536 mid = (mid + Math.imul(ah8, bl3)) | 0;
6537 hi = (hi + Math.imul(ah8, bh3)) | 0;
6538 lo = (lo + Math.imul(al7, bl4)) | 0;
6539 mid = (mid + Math.imul(al7, bh4)) | 0;
6540 mid = (mid + Math.imul(ah7, bl4)) | 0;
6541 hi = (hi + Math.imul(ah7, bh4)) | 0;
6542 lo = (lo + Math.imul(al6, bl5)) | 0;
6543 mid = (mid + Math.imul(al6, bh5)) | 0;
6544 mid = (mid + Math.imul(ah6, bl5)) | 0;
6545 hi = (hi + Math.imul(ah6, bh5)) | 0;
6546 lo = (lo + Math.imul(al5, bl6)) | 0;
6547 mid = (mid + Math.imul(al5, bh6)) | 0;
6548 mid = (mid + Math.imul(ah5, bl6)) | 0;
6549 hi = (hi + Math.imul(ah5, bh6)) | 0;
6550 lo = (lo + Math.imul(al4, bl7)) | 0;
6551 mid = (mid + Math.imul(al4, bh7)) | 0;
6552 mid = (mid + Math.imul(ah4, bl7)) | 0;
6553 hi = (hi + Math.imul(ah4, bh7)) | 0;
6554 lo = (lo + Math.imul(al3, bl8)) | 0;
6555 mid = (mid + Math.imul(al3, bh8)) | 0;
6556 mid = (mid + Math.imul(ah3, bl8)) | 0;
6557 hi = (hi + Math.imul(ah3, bh8)) | 0;
6558 lo = (lo + Math.imul(al2, bl9)) | 0;
6559 mid = (mid + Math.imul(al2, bh9)) | 0;
6560 mid = (mid + Math.imul(ah2, bl9)) | 0;
6561 hi = (hi + Math.imul(ah2, bh9)) | 0;
6562 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6563 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
6564 w11 &= 0x3ffffff;
6565 /* k = 12 */
6566 lo = Math.imul(al9, bl3);
6567 mid = Math.imul(al9, bh3);
6568 mid = (mid + Math.imul(ah9, bl3)) | 0;
6569 hi = Math.imul(ah9, bh3);
6570 lo = (lo + Math.imul(al8, bl4)) | 0;
6571 mid = (mid + Math.imul(al8, bh4)) | 0;
6572 mid = (mid + Math.imul(ah8, bl4)) | 0;
6573 hi = (hi + Math.imul(ah8, bh4)) | 0;
6574 lo = (lo + Math.imul(al7, bl5)) | 0;
6575 mid = (mid + Math.imul(al7, bh5)) | 0;
6576 mid = (mid + Math.imul(ah7, bl5)) | 0;
6577 hi = (hi + Math.imul(ah7, bh5)) | 0;
6578 lo = (lo + Math.imul(al6, bl6)) | 0;
6579 mid = (mid + Math.imul(al6, bh6)) | 0;
6580 mid = (mid + Math.imul(ah6, bl6)) | 0;
6581 hi = (hi + Math.imul(ah6, bh6)) | 0;
6582 lo = (lo + Math.imul(al5, bl7)) | 0;
6583 mid = (mid + Math.imul(al5, bh7)) | 0;
6584 mid = (mid + Math.imul(ah5, bl7)) | 0;
6585 hi = (hi + Math.imul(ah5, bh7)) | 0;
6586 lo = (lo + Math.imul(al4, bl8)) | 0;
6587 mid = (mid + Math.imul(al4, bh8)) | 0;
6588 mid = (mid + Math.imul(ah4, bl8)) | 0;
6589 hi = (hi + Math.imul(ah4, bh8)) | 0;
6590 lo = (lo + Math.imul(al3, bl9)) | 0;
6591 mid = (mid + Math.imul(al3, bh9)) | 0;
6592 mid = (mid + Math.imul(ah3, bl9)) | 0;
6593 hi = (hi + Math.imul(ah3, bh9)) | 0;
6594 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6595 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
6596 w12 &= 0x3ffffff;
6597 /* k = 13 */
6598 lo = Math.imul(al9, bl4);
6599 mid = Math.imul(al9, bh4);
6600 mid = (mid + Math.imul(ah9, bl4)) | 0;
6601 hi = Math.imul(ah9, bh4);
6602 lo = (lo + Math.imul(al8, bl5)) | 0;
6603 mid = (mid + Math.imul(al8, bh5)) | 0;
6604 mid = (mid + Math.imul(ah8, bl5)) | 0;
6605 hi = (hi + Math.imul(ah8, bh5)) | 0;
6606 lo = (lo + Math.imul(al7, bl6)) | 0;
6607 mid = (mid + Math.imul(al7, bh6)) | 0;
6608 mid = (mid + Math.imul(ah7, bl6)) | 0;
6609 hi = (hi + Math.imul(ah7, bh6)) | 0;
6610 lo = (lo + Math.imul(al6, bl7)) | 0;
6611 mid = (mid + Math.imul(al6, bh7)) | 0;
6612 mid = (mid + Math.imul(ah6, bl7)) | 0;
6613 hi = (hi + Math.imul(ah6, bh7)) | 0;
6614 lo = (lo + Math.imul(al5, bl8)) | 0;
6615 mid = (mid + Math.imul(al5, bh8)) | 0;
6616 mid = (mid + Math.imul(ah5, bl8)) | 0;
6617 hi = (hi + Math.imul(ah5, bh8)) | 0;
6618 lo = (lo + Math.imul(al4, bl9)) | 0;
6619 mid = (mid + Math.imul(al4, bh9)) | 0;
6620 mid = (mid + Math.imul(ah4, bl9)) | 0;
6621 hi = (hi + Math.imul(ah4, bh9)) | 0;
6622 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6623 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
6624 w13 &= 0x3ffffff;
6625 /* k = 14 */
6626 lo = Math.imul(al9, bl5);
6627 mid = Math.imul(al9, bh5);
6628 mid = (mid + Math.imul(ah9, bl5)) | 0;
6629 hi = Math.imul(ah9, bh5);
6630 lo = (lo + Math.imul(al8, bl6)) | 0;
6631 mid = (mid + Math.imul(al8, bh6)) | 0;
6632 mid = (mid + Math.imul(ah8, bl6)) | 0;
6633 hi = (hi + Math.imul(ah8, bh6)) | 0;
6634 lo = (lo + Math.imul(al7, bl7)) | 0;
6635 mid = (mid + Math.imul(al7, bh7)) | 0;
6636 mid = (mid + Math.imul(ah7, bl7)) | 0;
6637 hi = (hi + Math.imul(ah7, bh7)) | 0;
6638 lo = (lo + Math.imul(al6, bl8)) | 0;
6639 mid = (mid + Math.imul(al6, bh8)) | 0;
6640 mid = (mid + Math.imul(ah6, bl8)) | 0;
6641 hi = (hi + Math.imul(ah6, bh8)) | 0;
6642 lo = (lo + Math.imul(al5, bl9)) | 0;
6643 mid = (mid + Math.imul(al5, bh9)) | 0;
6644 mid = (mid + Math.imul(ah5, bl9)) | 0;
6645 hi = (hi + Math.imul(ah5, bh9)) | 0;
6646 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6647 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
6648 w14 &= 0x3ffffff;
6649 /* k = 15 */
6650 lo = Math.imul(al9, bl6);
6651 mid = Math.imul(al9, bh6);
6652 mid = (mid + Math.imul(ah9, bl6)) | 0;
6653 hi = Math.imul(ah9, bh6);
6654 lo = (lo + Math.imul(al8, bl7)) | 0;
6655 mid = (mid + Math.imul(al8, bh7)) | 0;
6656 mid = (mid + Math.imul(ah8, bl7)) | 0;
6657 hi = (hi + Math.imul(ah8, bh7)) | 0;
6658 lo = (lo + Math.imul(al7, bl8)) | 0;
6659 mid = (mid + Math.imul(al7, bh8)) | 0;
6660 mid = (mid + Math.imul(ah7, bl8)) | 0;
6661 hi = (hi + Math.imul(ah7, bh8)) | 0;
6662 lo = (lo + Math.imul(al6, bl9)) | 0;
6663 mid = (mid + Math.imul(al6, bh9)) | 0;
6664 mid = (mid + Math.imul(ah6, bl9)) | 0;
6665 hi = (hi + Math.imul(ah6, bh9)) | 0;
6666 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6667 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
6668 w15 &= 0x3ffffff;
6669 /* k = 16 */
6670 lo = Math.imul(al9, bl7);
6671 mid = Math.imul(al9, bh7);
6672 mid = (mid + Math.imul(ah9, bl7)) | 0;
6673 hi = Math.imul(ah9, bh7);
6674 lo = (lo + Math.imul(al8, bl8)) | 0;
6675 mid = (mid + Math.imul(al8, bh8)) | 0;
6676 mid = (mid + Math.imul(ah8, bl8)) | 0;
6677 hi = (hi + Math.imul(ah8, bh8)) | 0;
6678 lo = (lo + Math.imul(al7, bl9)) | 0;
6679 mid = (mid + Math.imul(al7, bh9)) | 0;
6680 mid = (mid + Math.imul(ah7, bl9)) | 0;
6681 hi = (hi + Math.imul(ah7, bh9)) | 0;
6682 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6683 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
6684 w16 &= 0x3ffffff;
6685 /* k = 17 */
6686 lo = Math.imul(al9, bl8);
6687 mid = Math.imul(al9, bh8);
6688 mid = (mid + Math.imul(ah9, bl8)) | 0;
6689 hi = Math.imul(ah9, bh8);
6690 lo = (lo + Math.imul(al8, bl9)) | 0;
6691 mid = (mid + Math.imul(al8, bh9)) | 0;
6692 mid = (mid + Math.imul(ah8, bl9)) | 0;
6693 hi = (hi + Math.imul(ah8, bh9)) | 0;
6694 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6695 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
6696 w17 &= 0x3ffffff;
6697 /* k = 18 */
6698 lo = Math.imul(al9, bl9);
6699 mid = Math.imul(al9, bh9);
6700 mid = (mid + Math.imul(ah9, bl9)) | 0;
6701 hi = Math.imul(ah9, bh9);
6702 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6703 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
6704 w18 &= 0x3ffffff;
6705 o[0] = w0;
6706 o[1] = w1;
6707 o[2] = w2;
6708 o[3] = w3;
6709 o[4] = w4;
6710 o[5] = w5;
6711 o[6] = w6;
6712 o[7] = w7;
6713 o[8] = w8;
6714 o[9] = w9;
6715 o[10] = w10;
6716 o[11] = w11;
6717 o[12] = w12;
6718 o[13] = w13;
6719 o[14] = w14;
6720 o[15] = w15;
6721 o[16] = w16;
6722 o[17] = w17;
6723 o[18] = w18;
6724 if (c !== 0) {
6725 o[19] = c;
6726 out.length++;
6727 }
6728 return out;
6729 };
6730
6731 // Polyfill comb
6732 if (!Math.imul) {
6733 comb10MulTo = smallMulTo;
6734 }
6735
6736 function bigMulTo (self, num, out) {
6737 out.negative = num.negative ^ self.negative;
6738 out.length = self.length + num.length;
6739
6740 var carry = 0;
6741 var hncarry = 0;
6742 for (var k = 0; k < out.length - 1; k++) {
6743 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
6744 // note that ncarry could be >= 0x3ffffff
6745 var ncarry = hncarry;
6746 hncarry = 0;
6747 var rword = carry & 0x3ffffff;
6748 var maxJ = Math.min(k, num.length - 1);
6749 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
6750 var i = k - j;
6751 var a = self.words[i] | 0;
6752 var b = num.words[j] | 0;
6753 var r = a * b;
6754
6755 var lo = r & 0x3ffffff;
6756 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
6757 lo = (lo + rword) | 0;
6758 rword = lo & 0x3ffffff;
6759 ncarry = (ncarry + (lo >>> 26)) | 0;
6760
6761 hncarry += ncarry >>> 26;
6762 ncarry &= 0x3ffffff;
6763 }
6764 out.words[k] = rword;
6765 carry = ncarry;
6766 ncarry = hncarry;
6767 }
6768 if (carry !== 0) {
6769 out.words[k] = carry;
6770 } else {
6771 out.length--;
6772 }
6773
6774 return out.strip();
6775 }
6776
6777 function jumboMulTo (self, num, out) {
6778 var fftm = new FFTM();
6779 return fftm.mulp(self, num, out);
6780 }
6781
6782 BN.prototype.mulTo = function mulTo (num, out) {
6783 var res;
6784 var len = this.length + num.length;
6785 if (this.length === 10 && num.length === 10) {
6786 res = comb10MulTo(this, num, out);
6787 } else if (len < 63) {
6788 res = smallMulTo(this, num, out);
6789 } else if (len < 1024) {
6790 res = bigMulTo(this, num, out);
6791 } else {
6792 res = jumboMulTo(this, num, out);
6793 }
6794
6795 return res;
6796 };
6797
6798 // Cooley-Tukey algorithm for FFT
6799 // slightly revisited to rely on looping instead of recursion
6800
6801 function FFTM (x, y) {
6802 this.x = x;
6803 this.y = y;
6804 }
6805
6806 FFTM.prototype.makeRBT = function makeRBT (N) {
6807 var t = new Array(N);
6808 var l = BN.prototype._countBits(N) - 1;
6809 for (var i = 0; i < N; i++) {
6810 t[i] = this.revBin(i, l, N);
6811 }
6812
6813 return t;
6814 };
6815
6816 // Returns binary-reversed representation of `x`
6817 FFTM.prototype.revBin = function revBin (x, l, N) {
6818 if (x === 0 || x === N - 1) return x;
6819
6820 var rb = 0;
6821 for (var i = 0; i < l; i++) {
6822 rb |= (x & 1) << (l - i - 1);
6823 x >>= 1;
6824 }
6825
6826 return rb;
6827 };
6828
6829 // Performs "tweedling" phase, therefore 'emulating'
6830 // behaviour of the recursive algorithm
6831 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
6832 for (var i = 0; i < N; i++) {
6833 rtws[i] = rws[rbt[i]];
6834 itws[i] = iws[rbt[i]];
6835 }
6836 };
6837
6838 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
6839 this.permute(rbt, rws, iws, rtws, itws, N);
6840
6841 for (var s = 1; s < N; s <<= 1) {
6842 var l = s << 1;
6843
6844 var rtwdf = Math.cos(2 * Math.PI / l);
6845 var itwdf = Math.sin(2 * Math.PI / l);
6846
6847 for (var p = 0; p < N; p += l) {
6848 var rtwdf_ = rtwdf;
6849 var itwdf_ = itwdf;
6850
6851 for (var j = 0; j < s; j++) {
6852 var re = rtws[p + j];
6853 var ie = itws[p + j];
6854
6855 var ro = rtws[p + j + s];
6856 var io = itws[p + j + s];
6857
6858 var rx = rtwdf_ * ro - itwdf_ * io;
6859
6860 io = rtwdf_ * io + itwdf_ * ro;
6861 ro = rx;
6862
6863 rtws[p + j] = re + ro;
6864 itws[p + j] = ie + io;
6865
6866 rtws[p + j + s] = re - ro;
6867 itws[p + j + s] = ie - io;
6868
6869 /* jshint maxdepth : false */
6870 if (j !== l) {
6871 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
6872
6873 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
6874 rtwdf_ = rx;
6875 }
6876 }
6877 }
6878 }
6879 };
6880
6881 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
6882 var N = Math.max(m, n) | 1;
6883 var odd = N & 1;
6884 var i = 0;
6885 for (N = N / 2 | 0; N; N = N >>> 1) {
6886 i++;
6887 }
6888
6889 return 1 << i + 1 + odd;
6890 };
6891
6892 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
6893 if (N <= 1) return;
6894
6895 for (var i = 0; i < N / 2; i++) {
6896 var t = rws[i];
6897
6898 rws[i] = rws[N - i - 1];
6899 rws[N - i - 1] = t;
6900
6901 t = iws[i];
6902
6903 iws[i] = -iws[N - i - 1];
6904 iws[N - i - 1] = -t;
6905 }
6906 };
6907
6908 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
6909 var carry = 0;
6910 for (var i = 0; i < N / 2; i++) {
6911 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
6912 Math.round(ws[2 * i] / N) +
6913 carry;
6914
6915 ws[i] = w & 0x3ffffff;
6916
6917 if (w < 0x4000000) {
6918 carry = 0;
6919 } else {
6920 carry = w / 0x4000000 | 0;
6921 }
6922 }
6923
6924 return ws;
6925 };
6926
6927 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
6928 var carry = 0;
6929 for (var i = 0; i < len; i++) {
6930 carry = carry + (ws[i] | 0);
6931
6932 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
6933 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
6934 }
6935
6936 // Pad with zeroes
6937 for (i = 2 * len; i < N; ++i) {
6938 rws[i] = 0;
6939 }
6940
6941 assert(carry === 0);
6942 assert((carry & ~0x1fff) === 0);
6943 };
6944
6945 FFTM.prototype.stub = function stub (N) {
6946 var ph = new Array(N);
6947 for (var i = 0; i < N; i++) {
6948 ph[i] = 0;
6949 }
6950
6951 return ph;
6952 };
6953
6954 FFTM.prototype.mulp = function mulp (x, y, out) {
6955 var N = 2 * this.guessLen13b(x.length, y.length);
6956
6957 var rbt = this.makeRBT(N);
6958
6959 var _ = this.stub(N);
6960
6961 var rws = new Array(N);
6962 var rwst = new Array(N);
6963 var iwst = new Array(N);
6964
6965 var nrws = new Array(N);
6966 var nrwst = new Array(N);
6967 var niwst = new Array(N);
6968
6969 var rmws = out.words;
6970 rmws.length = N;
6971
6972 this.convert13b(x.words, x.length, rws, N);
6973 this.convert13b(y.words, y.length, nrws, N);
6974
6975 this.transform(rws, _, rwst, iwst, N, rbt);
6976 this.transform(nrws, _, nrwst, niwst, N, rbt);
6977
6978 for (var i = 0; i < N; i++) {
6979 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
6980 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
6981 rwst[i] = rx;
6982 }
6983
6984 this.conjugate(rwst, iwst, N);
6985 this.transform(rwst, iwst, rmws, _, N, rbt);
6986 this.conjugate(rmws, _, N);
6987 this.normalize13b(rmws, N);
6988
6989 out.negative = x.negative ^ y.negative;
6990 out.length = x.length + y.length;
6991 return out.strip();
6992 };
6993
6994 // Multiply `this` by `num`
6995 BN.prototype.mul = function mul (num) {
6996 var out = new BN(null);
6997 out.words = new Array(this.length + num.length);
6998 return this.mulTo(num, out);
6999 };
7000
7001 // Multiply employing FFT
7002 BN.prototype.mulf = function mulf (num) {
7003 var out = new BN(null);
7004 out.words = new Array(this.length + num.length);
7005 return jumboMulTo(this, num, out);
7006 };
7007
7008 // In-place Multiplication
7009 BN.prototype.imul = function imul (num) {
7010 return this.clone().mulTo(num, this);
7011 };
7012
7013 BN.prototype.imuln = function imuln (num) {
7014 assert(typeof num === 'number');
7015 assert(num < 0x4000000);
7016
7017 // Carry
7018 var carry = 0;
7019 for (var i = 0; i < this.length; i++) {
7020 var w = (this.words[i] | 0) * num;
7021 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
7022 carry >>= 26;
7023 carry += (w / 0x4000000) | 0;
7024 // NOTE: lo is 27bit maximum
7025 carry += lo >>> 26;
7026 this.words[i] = lo & 0x3ffffff;
7027 }
7028
7029 if (carry !== 0) {
7030 this.words[i] = carry;
7031 this.length++;
7032 }
7033
7034 return this;
7035 };
7036
7037 BN.prototype.muln = function muln (num) {
7038 return this.clone().imuln(num);
7039 };
7040
7041 // `this` * `this`
7042 BN.prototype.sqr = function sqr () {
7043 return this.mul(this);
7044 };
7045
7046 // `this` * `this` in-place
7047 BN.prototype.isqr = function isqr () {
7048 return this.imul(this.clone());
7049 };
7050
7051 // Math.pow(`this`, `num`)
7052 BN.prototype.pow = function pow (num) {
7053 var w = toBitArray(num);
7054 if (w.length === 0) return new BN(1);
7055
7056 // Skip leading zeroes
7057 var res = this;
7058 for (var i = 0; i < w.length; i++, res = res.sqr()) {
7059 if (w[i] !== 0) break;
7060 }
7061
7062 if (++i < w.length) {
7063 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
7064 if (w[i] === 0) continue;
7065
7066 res = res.mul(q);
7067 }
7068 }
7069
7070 return res;
7071 };
7072
7073 // Shift-left in-place
7074 BN.prototype.iushln = function iushln (bits) {
7075 assert(typeof bits === 'number' && bits >= 0);
7076 var r = bits % 26;
7077 var s = (bits - r) / 26;
7078 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
7079 var i;
7080
7081 if (r !== 0) {
7082 var carry = 0;
7083
7084 for (i = 0; i < this.length; i++) {
7085 var newCarry = this.words[i] & carryMask;
7086 var c = ((this.words[i] | 0) - newCarry) << r;
7087 this.words[i] = c | carry;
7088 carry = newCarry >>> (26 - r);
7089 }
7090
7091 if (carry) {
7092 this.words[i] = carry;
7093 this.length++;
7094 }
7095 }
7096
7097 if (s !== 0) {
7098 for (i = this.length - 1; i >= 0; i--) {
7099 this.words[i + s] = this.words[i];
7100 }
7101
7102 for (i = 0; i < s; i++) {
7103 this.words[i] = 0;
7104 }
7105
7106 this.length += s;
7107 }
7108
7109 return this.strip();
7110 };
7111
7112 BN.prototype.ishln = function ishln (bits) {
7113 // TODO(indutny): implement me
7114 assert(this.negative === 0);
7115 return this.iushln(bits);
7116 };
7117
7118 // Shift-right in-place
7119 // NOTE: `hint` is a lowest bit before trailing zeroes
7120 // NOTE: if `extended` is present - it will be filled with destroyed bits
7121 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
7122 assert(typeof bits === 'number' && bits >= 0);
7123 var h;
7124 if (hint) {
7125 h = (hint - (hint % 26)) / 26;
7126 } else {
7127 h = 0;
7128 }
7129
7130 var r = bits % 26;
7131 var s = Math.min((bits - r) / 26, this.length);
7132 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
7133 var maskedWords = extended;
7134
7135 h -= s;
7136 h = Math.max(0, h);
7137
7138 // Extended mode, copy masked part
7139 if (maskedWords) {
7140 for (var i = 0; i < s; i++) {
7141 maskedWords.words[i] = this.words[i];
7142 }
7143 maskedWords.length = s;
7144 }
7145
7146 if (s === 0) {
7147 // No-op, we should not move anything at all
7148 } else if (this.length > s) {
7149 this.length -= s;
7150 for (i = 0; i < this.length; i++) {
7151 this.words[i] = this.words[i + s];
7152 }
7153 } else {
7154 this.words[0] = 0;
7155 this.length = 1;
7156 }
7157
7158 var carry = 0;
7159 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
7160 var word = this.words[i] | 0;
7161 this.words[i] = (carry << (26 - r)) | (word >>> r);
7162 carry = word & mask;
7163 }
7164
7165 // Push carried bits as a mask
7166 if (maskedWords && carry !== 0) {
7167 maskedWords.words[maskedWords.length++] = carry;
7168 }
7169
7170 if (this.length === 0) {
7171 this.words[0] = 0;
7172 this.length = 1;
7173 }
7174
7175 return this.strip();
7176 };
7177
7178 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
7179 // TODO(indutny): implement me
7180 assert(this.negative === 0);
7181 return this.iushrn(bits, hint, extended);
7182 };
7183
7184 // Shift-left
7185 BN.prototype.shln = function shln (bits) {
7186 return this.clone().ishln(bits);
7187 };
7188
7189 BN.prototype.ushln = function ushln (bits) {
7190 return this.clone().iushln(bits);
7191 };
7192
7193 // Shift-right
7194 BN.prototype.shrn = function shrn (bits) {
7195 return this.clone().ishrn(bits);
7196 };
7197
7198 BN.prototype.ushrn = function ushrn (bits) {
7199 return this.clone().iushrn(bits);
7200 };
7201
7202 // Test if n bit is set
7203 BN.prototype.testn = function testn (bit) {
7204 assert(typeof bit === 'number' && bit >= 0);
7205 var r = bit % 26;
7206 var s = (bit - r) / 26;
7207 var q = 1 << r;
7208
7209 // Fast case: bit is much higher than all existing words
7210 if (this.length <= s) return false;
7211
7212 // Check bit and return
7213 var w = this.words[s];
7214
7215 return !!(w & q);
7216 };
7217
7218 // Return only lowers bits of number (in-place)
7219 BN.prototype.imaskn = function imaskn (bits) {
7220 assert(typeof bits === 'number' && bits >= 0);
7221 var r = bits % 26;
7222 var s = (bits - r) / 26;
7223
7224 assert(this.negative === 0, 'imaskn works only with positive numbers');
7225
7226 if (this.length <= s) {
7227 return this;
7228 }
7229
7230 if (r !== 0) {
7231 s++;
7232 }
7233 this.length = Math.min(s, this.length);
7234
7235 if (r !== 0) {
7236 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
7237 this.words[this.length - 1] &= mask;
7238 }
7239
7240 return this.strip();
7241 };
7242
7243 // Return only lowers bits of number
7244 BN.prototype.maskn = function maskn (bits) {
7245 return this.clone().imaskn(bits);
7246 };
7247
7248 // Add plain number `num` to `this`
7249 BN.prototype.iaddn = function iaddn (num) {
7250 assert(typeof num === 'number');
7251 assert(num < 0x4000000);
7252 if (num < 0) return this.isubn(-num);
7253
7254 // Possible sign change
7255 if (this.negative !== 0) {
7256 if (this.length === 1 && (this.words[0] | 0) < num) {
7257 this.words[0] = num - (this.words[0] | 0);
7258 this.negative = 0;
7259 return this;
7260 }
7261
7262 this.negative = 0;
7263 this.isubn(num);
7264 this.negative = 1;
7265 return this;
7266 }
7267
7268 // Add without checks
7269 return this._iaddn(num);
7270 };
7271
7272 BN.prototype._iaddn = function _iaddn (num) {
7273 this.words[0] += num;
7274
7275 // Carry
7276 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
7277 this.words[i] -= 0x4000000;
7278 if (i === this.length - 1) {
7279 this.words[i + 1] = 1;
7280 } else {
7281 this.words[i + 1]++;
7282 }
7283 }
7284 this.length = Math.max(this.length, i + 1);
7285
7286 return this;
7287 };
7288
7289 // Subtract plain number `num` from `this`
7290 BN.prototype.isubn = function isubn (num) {
7291 assert(typeof num === 'number');
7292 assert(num < 0x4000000);
7293 if (num < 0) return this.iaddn(-num);
7294
7295 if (this.negative !== 0) {
7296 this.negative = 0;
7297 this.iaddn(num);
7298 this.negative = 1;
7299 return this;
7300 }
7301
7302 this.words[0] -= num;
7303
7304 if (this.length === 1 && this.words[0] < 0) {
7305 this.words[0] = -this.words[0];
7306 this.negative = 1;
7307 } else {
7308 // Carry
7309 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
7310 this.words[i] += 0x4000000;
7311 this.words[i + 1] -= 1;
7312 }
7313 }
7314
7315 return this.strip();
7316 };
7317
7318 BN.prototype.addn = function addn (num) {
7319 return this.clone().iaddn(num);
7320 };
7321
7322 BN.prototype.subn = function subn (num) {
7323 return this.clone().isubn(num);
7324 };
7325
7326 BN.prototype.iabs = function iabs () {
7327 this.negative = 0;
7328
7329 return this;
7330 };
7331
7332 BN.prototype.abs = function abs () {
7333 return this.clone().iabs();
7334 };
7335
7336 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
7337 var len = num.length + shift;
7338 var i;
7339
7340 this._expand(len);
7341
7342 var w;
7343 var carry = 0;
7344 for (i = 0; i < num.length; i++) {
7345 w = (this.words[i + shift] | 0) + carry;
7346 var right = (num.words[i] | 0) * mul;
7347 w -= right & 0x3ffffff;
7348 carry = (w >> 26) - ((right / 0x4000000) | 0);
7349 this.words[i + shift] = w & 0x3ffffff;
7350 }
7351 for (; i < this.length - shift; i++) {
7352 w = (this.words[i + shift] | 0) + carry;
7353 carry = w >> 26;
7354 this.words[i + shift] = w & 0x3ffffff;
7355 }
7356
7357 if (carry === 0) return this.strip();
7358
7359 // Subtraction overflow
7360 assert(carry === -1);
7361 carry = 0;
7362 for (i = 0; i < this.length; i++) {
7363 w = -(this.words[i] | 0) + carry;
7364 carry = w >> 26;
7365 this.words[i] = w & 0x3ffffff;
7366 }
7367 this.negative = 1;
7368
7369 return this.strip();
7370 };
7371
7372 BN.prototype._wordDiv = function _wordDiv (num, mode) {
7373 var shift = this.length - num.length;
7374
7375 var a = this.clone();
7376 var b = num;
7377
7378 // Normalize
7379 var bhi = b.words[b.length - 1] | 0;
7380 var bhiBits = this._countBits(bhi);
7381 shift = 26 - bhiBits;
7382 if (shift !== 0) {
7383 b = b.ushln(shift);
7384 a.iushln(shift);
7385 bhi = b.words[b.length - 1] | 0;
7386 }
7387
7388 // Initialize quotient
7389 var m = a.length - b.length;
7390 var q;
7391
7392 if (mode !== 'mod') {
7393 q = new BN(null);
7394 q.length = m + 1;
7395 q.words = new Array(q.length);
7396 for (var i = 0; i < q.length; i++) {
7397 q.words[i] = 0;
7398 }
7399 }
7400
7401 var diff = a.clone()._ishlnsubmul(b, 1, m);
7402 if (diff.negative === 0) {
7403 a = diff;
7404 if (q) {
7405 q.words[m] = 1;
7406 }
7407 }
7408
7409 for (var j = m - 1; j >= 0; j--) {
7410 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
7411 (a.words[b.length + j - 1] | 0);
7412
7413 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
7414 // (0x7ffffff)
7415 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
7416
7417 a._ishlnsubmul(b, qj, j);
7418 while (a.negative !== 0) {
7419 qj--;
7420 a.negative = 0;
7421 a._ishlnsubmul(b, 1, j);
7422 if (!a.isZero()) {
7423 a.negative ^= 1;
7424 }
7425 }
7426 if (q) {
7427 q.words[j] = qj;
7428 }
7429 }
7430 if (q) {
7431 q.strip();
7432 }
7433 a.strip();
7434
7435 // Denormalize
7436 if (mode !== 'div' && shift !== 0) {
7437 a.iushrn(shift);
7438 }
7439
7440 return {
7441 div: q || null,
7442 mod: a
7443 };
7444 };
7445
7446 // NOTE: 1) `mode` can be set to `mod` to request mod only,
7447 // to `div` to request div only, or be absent to
7448 // request both div & mod
7449 // 2) `positive` is true if unsigned mod is requested
7450 BN.prototype.divmod = function divmod (num, mode, positive) {
7451 assert(!num.isZero());
7452
7453 if (this.isZero()) {
7454 return {
7455 div: new BN(0),
7456 mod: new BN(0)
7457 };
7458 }
7459
7460 var div, mod, res;
7461 if (this.negative !== 0 && num.negative === 0) {
7462 res = this.neg().divmod(num, mode);
7463
7464 if (mode !== 'mod') {
7465 div = res.div.neg();
7466 }
7467
7468 if (mode !== 'div') {
7469 mod = res.mod.neg();
7470 if (positive && mod.negative !== 0) {
7471 mod.iadd(num);
7472 }
7473 }
7474
7475 return {
7476 div: div,
7477 mod: mod
7478 };
7479 }
7480
7481 if (this.negative === 0 && num.negative !== 0) {
7482 res = this.divmod(num.neg(), mode);
7483
7484 if (mode !== 'mod') {
7485 div = res.div.neg();
7486 }
7487
7488 return {
7489 div: div,
7490 mod: res.mod
7491 };
7492 }
7493
7494 if ((this.negative & num.negative) !== 0) {
7495 res = this.neg().divmod(num.neg(), mode);
7496
7497 if (mode !== 'div') {
7498 mod = res.mod.neg();
7499 if (positive && mod.negative !== 0) {
7500 mod.isub(num);
7501 }
7502 }
7503
7504 return {
7505 div: res.div,
7506 mod: mod
7507 };
7508 }
7509
7510 // Both numbers are positive at this point
7511
7512 // Strip both numbers to approximate shift value
7513 if (num.length > this.length || this.cmp(num) < 0) {
7514 return {
7515 div: new BN(0),
7516 mod: this
7517 };
7518 }
7519
7520 // Very short reduction
7521 if (num.length === 1) {
7522 if (mode === 'div') {
7523 return {
7524 div: this.divn(num.words[0]),
7525 mod: null
7526 };
7527 }
7528
7529 if (mode === 'mod') {
7530 return {
7531 div: null,
7532 mod: new BN(this.modn(num.words[0]))
7533 };
7534 }
7535
7536 return {
7537 div: this.divn(num.words[0]),
7538 mod: new BN(this.modn(num.words[0]))
7539 };
7540 }
7541
7542 return this._wordDiv(num, mode);
7543 };
7544
7545 // Find `this` / `num`
7546 BN.prototype.div = function div (num) {
7547 return this.divmod(num, 'div', false).div;
7548 };
7549
7550 // Find `this` % `num`
7551 BN.prototype.mod = function mod (num) {
7552 return this.divmod(num, 'mod', false).mod;
7553 };
7554
7555 BN.prototype.umod = function umod (num) {
7556 return this.divmod(num, 'mod', true).mod;
7557 };
7558
7559 // Find Round(`this` / `num`)
7560 BN.prototype.divRound = function divRound (num) {
7561 var dm = this.divmod(num);
7562
7563 // Fast case - exact division
7564 if (dm.mod.isZero()) return dm.div;
7565
7566 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
7567
7568 var half = num.ushrn(1);
7569 var r2 = num.andln(1);
7570 var cmp = mod.cmp(half);
7571
7572 // Round down
7573 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
7574
7575 // Round up
7576 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
7577 };
7578
7579 BN.prototype.modn = function modn (num) {
7580 assert(num <= 0x3ffffff);
7581 var p = (1 << 26) % num;
7582
7583 var acc = 0;
7584 for (var i = this.length - 1; i >= 0; i--) {
7585 acc = (p * acc + (this.words[i] | 0)) % num;
7586 }
7587
7588 return acc;
7589 };
7590
7591 // In-place division by number
7592 BN.prototype.idivn = function idivn (num) {
7593 assert(num <= 0x3ffffff);
7594
7595 var carry = 0;
7596 for (var i = this.length - 1; i >= 0; i--) {
7597 var w = (this.words[i] | 0) + carry * 0x4000000;
7598 this.words[i] = (w / num) | 0;
7599 carry = w % num;
7600 }
7601
7602 return this.strip();
7603 };
7604
7605 BN.prototype.divn = function divn (num) {
7606 return this.clone().idivn(num);
7607 };
7608
7609 BN.prototype.egcd = function egcd (p) {
7610 assert(p.negative === 0);
7611 assert(!p.isZero());
7612
7613 var x = this;
7614 var y = p.clone();
7615
7616 if (x.negative !== 0) {
7617 x = x.umod(p);
7618 } else {
7619 x = x.clone();
7620 }
7621
7622 // A * x + B * y = x
7623 var A = new BN(1);
7624 var B = new BN(0);
7625
7626 // C * x + D * y = y
7627 var C = new BN(0);
7628 var D = new BN(1);
7629
7630 var g = 0;
7631
7632 while (x.isEven() && y.isEven()) {
7633 x.iushrn(1);
7634 y.iushrn(1);
7635 ++g;
7636 }
7637
7638 var yp = y.clone();
7639 var xp = x.clone();
7640
7641 while (!x.isZero()) {
7642 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
7643 if (i > 0) {
7644 x.iushrn(i);
7645 while (i-- > 0) {
7646 if (A.isOdd() || B.isOdd()) {
7647 A.iadd(yp);
7648 B.isub(xp);
7649 }
7650
7651 A.iushrn(1);
7652 B.iushrn(1);
7653 }
7654 }
7655
7656 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
7657 if (j > 0) {
7658 y.iushrn(j);
7659 while (j-- > 0) {
7660 if (C.isOdd() || D.isOdd()) {
7661 C.iadd(yp);
7662 D.isub(xp);
7663 }
7664
7665 C.iushrn(1);
7666 D.iushrn(1);
7667 }
7668 }
7669
7670 if (x.cmp(y) >= 0) {
7671 x.isub(y);
7672 A.isub(C);
7673 B.isub(D);
7674 } else {
7675 y.isub(x);
7676 C.isub(A);
7677 D.isub(B);
7678 }
7679 }
7680
7681 return {
7682 a: C,
7683 b: D,
7684 gcd: y.iushln(g)
7685 };
7686 };
7687
7688 // This is reduced incarnation of the binary EEA
7689 // above, designated to invert members of the
7690 // _prime_ fields F(p) at a maximal speed
7691 BN.prototype._invmp = function _invmp (p) {
7692 assert(p.negative === 0);
7693 assert(!p.isZero());
7694
7695 var a = this;
7696 var b = p.clone();
7697
7698 if (a.negative !== 0) {
7699 a = a.umod(p);
7700 } else {
7701 a = a.clone();
7702 }
7703
7704 var x1 = new BN(1);
7705 var x2 = new BN(0);
7706
7707 var delta = b.clone();
7708
7709 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
7710 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
7711 if (i > 0) {
7712 a.iushrn(i);
7713 while (i-- > 0) {
7714 if (x1.isOdd()) {
7715 x1.iadd(delta);
7716 }
7717
7718 x1.iushrn(1);
7719 }
7720 }
7721
7722 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
7723 if (j > 0) {
7724 b.iushrn(j);
7725 while (j-- > 0) {
7726 if (x2.isOdd()) {
7727 x2.iadd(delta);
7728 }
7729
7730 x2.iushrn(1);
7731 }
7732 }
7733
7734 if (a.cmp(b) >= 0) {
7735 a.isub(b);
7736 x1.isub(x2);
7737 } else {
7738 b.isub(a);
7739 x2.isub(x1);
7740 }
7741 }
7742
7743 var res;
7744 if (a.cmpn(1) === 0) {
7745 res = x1;
7746 } else {
7747 res = x2;
7748 }
7749
7750 if (res.cmpn(0) < 0) {
7751 res.iadd(p);
7752 }
7753
7754 return res;
7755 };
7756
7757 BN.prototype.gcd = function gcd (num) {
7758 if (this.isZero()) return num.abs();
7759 if (num.isZero()) return this.abs();
7760
7761 var a = this.clone();
7762 var b = num.clone();
7763 a.negative = 0;
7764 b.negative = 0;
7765
7766 // Remove common factor of two
7767 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
7768 a.iushrn(1);
7769 b.iushrn(1);
7770 }
7771
7772 do {
7773 while (a.isEven()) {
7774 a.iushrn(1);
7775 }
7776 while (b.isEven()) {
7777 b.iushrn(1);
7778 }
7779
7780 var r = a.cmp(b);
7781 if (r < 0) {
7782 // Swap `a` and `b` to make `a` always bigger than `b`
7783 var t = a;
7784 a = b;
7785 b = t;
7786 } else if (r === 0 || b.cmpn(1) === 0) {
7787 break;
7788 }
7789
7790 a.isub(b);
7791 } while (true);
7792
7793 return b.iushln(shift);
7794 };
7795
7796 // Invert number in the field F(num)
7797 BN.prototype.invm = function invm (num) {
7798 return this.egcd(num).a.umod(num);
7799 };
7800
7801 BN.prototype.isEven = function isEven () {
7802 return (this.words[0] & 1) === 0;
7803 };
7804
7805 BN.prototype.isOdd = function isOdd () {
7806 return (this.words[0] & 1) === 1;
7807 };
7808
7809 // And first word and num
7810 BN.prototype.andln = function andln (num) {
7811 return this.words[0] & num;
7812 };
7813
7814 // Increment at the bit position in-line
7815 BN.prototype.bincn = function bincn (bit) {
7816 assert(typeof bit === 'number');
7817 var r = bit % 26;
7818 var s = (bit - r) / 26;
7819 var q = 1 << r;
7820
7821 // Fast case: bit is much higher than all existing words
7822 if (this.length <= s) {
7823 this._expand(s + 1);
7824 this.words[s] |= q;
7825 return this;
7826 }
7827
7828 // Add bit and propagate, if needed
7829 var carry = q;
7830 for (var i = s; carry !== 0 && i < this.length; i++) {
7831 var w = this.words[i] | 0;
7832 w += carry;
7833 carry = w >>> 26;
7834 w &= 0x3ffffff;
7835 this.words[i] = w;
7836 }
7837 if (carry !== 0) {
7838 this.words[i] = carry;
7839 this.length++;
7840 }
7841 return this;
7842 };
7843
7844 BN.prototype.isZero = function isZero () {
7845 return this.length === 1 && this.words[0] === 0;
7846 };
7847
7848 BN.prototype.cmpn = function cmpn (num) {
7849 var negative = num < 0;
7850
7851 if (this.negative !== 0 && !negative) return -1;
7852 if (this.negative === 0 && negative) return 1;
7853
7854 this.strip();
7855
7856 var res;
7857 if (this.length > 1) {
7858 res = 1;
7859 } else {
7860 if (negative) {
7861 num = -num;
7862 }
7863
7864 assert(num <= 0x3ffffff, 'Number is too big');
7865
7866 var w = this.words[0] | 0;
7867 res = w === num ? 0 : w < num ? -1 : 1;
7868 }
7869 if (this.negative !== 0) return -res | 0;
7870 return res;
7871 };
7872
7873 // Compare two numbers and return:
7874 // 1 - if `this` > `num`
7875 // 0 - if `this` == `num`
7876 // -1 - if `this` < `num`
7877 BN.prototype.cmp = function cmp (num) {
7878 if (this.negative !== 0 && num.negative === 0) return -1;
7879 if (this.negative === 0 && num.negative !== 0) return 1;
7880
7881 var res = this.ucmp(num);
7882 if (this.negative !== 0) return -res | 0;
7883 return res;
7884 };
7885
7886 // Unsigned comparison
7887 BN.prototype.ucmp = function ucmp (num) {
7888 // At this point both numbers have the same sign
7889 if (this.length > num.length) return 1;
7890 if (this.length < num.length) return -1;
7891
7892 var res = 0;
7893 for (var i = this.length - 1; i >= 0; i--) {
7894 var a = this.words[i] | 0;
7895 var b = num.words[i] | 0;
7896
7897 if (a === b) continue;
7898 if (a < b) {
7899 res = -1;
7900 } else if (a > b) {
7901 res = 1;
7902 }
7903 break;
7904 }
7905 return res;
7906 };
7907
7908 BN.prototype.gtn = function gtn (num) {
7909 return this.cmpn(num) === 1;
7910 };
7911
7912 BN.prototype.gt = function gt (num) {
7913 return this.cmp(num) === 1;
7914 };
7915
7916 BN.prototype.gten = function gten (num) {
7917 return this.cmpn(num) >= 0;
7918 };
7919
7920 BN.prototype.gte = function gte (num) {
7921 return this.cmp(num) >= 0;
7922 };
7923
7924 BN.prototype.ltn = function ltn (num) {
7925 return this.cmpn(num) === -1;
7926 };
7927
7928 BN.prototype.lt = function lt (num) {
7929 return this.cmp(num) === -1;
7930 };
7931
7932 BN.prototype.lten = function lten (num) {
7933 return this.cmpn(num) <= 0;
7934 };
7935
7936 BN.prototype.lte = function lte (num) {
7937 return this.cmp(num) <= 0;
7938 };
7939
7940 BN.prototype.eqn = function eqn (num) {
7941 return this.cmpn(num) === 0;
7942 };
7943
7944 BN.prototype.eq = function eq (num) {
7945 return this.cmp(num) === 0;
7946 };
7947
7948 //
7949 // A reduce context, could be using montgomery or something better, depending
7950 // on the `m` itself.
7951 //
7952 BN.red = function red (num) {
7953 return new Red(num);
7954 };
7955
7956 BN.prototype.toRed = function toRed (ctx) {
7957 assert(!this.red, 'Already a number in reduction context');
7958 assert(this.negative === 0, 'red works only with positives');
7959 return ctx.convertTo(this)._forceRed(ctx);
7960 };
7961
7962 BN.prototype.fromRed = function fromRed () {
7963 assert(this.red, 'fromRed works only with numbers in reduction context');
7964 return this.red.convertFrom(this);
7965 };
7966
7967 BN.prototype._forceRed = function _forceRed (ctx) {
7968 this.red = ctx;
7969 return this;
7970 };
7971
7972 BN.prototype.forceRed = function forceRed (ctx) {
7973 assert(!this.red, 'Already a number in reduction context');
7974 return this._forceRed(ctx);
7975 };
7976
7977 BN.prototype.redAdd = function redAdd (num) {
7978 assert(this.red, 'redAdd works only with red numbers');
7979 return this.red.add(this, num);
7980 };
7981
7982 BN.prototype.redIAdd = function redIAdd (num) {
7983 assert(this.red, 'redIAdd works only with red numbers');
7984 return this.red.iadd(this, num);
7985 };
7986
7987 BN.prototype.redSub = function redSub (num) {
7988 assert(this.red, 'redSub works only with red numbers');
7989 return this.red.sub(this, num);
7990 };
7991
7992 BN.prototype.redISub = function redISub (num) {
7993 assert(this.red, 'redISub works only with red numbers');
7994 return this.red.isub(this, num);
7995 };
7996
7997 BN.prototype.redShl = function redShl (num) {
7998 assert(this.red, 'redShl works only with red numbers');
7999 return this.red.shl(this, num);
8000 };
8001
8002 BN.prototype.redMul = function redMul (num) {
8003 assert(this.red, 'redMul works only with red numbers');
8004 this.red._verify2(this, num);
8005 return this.red.mul(this, num);
8006 };
8007
8008 BN.prototype.redIMul = function redIMul (num) {
8009 assert(this.red, 'redMul works only with red numbers');
8010 this.red._verify2(this, num);
8011 return this.red.imul(this, num);
8012 };
8013
8014 BN.prototype.redSqr = function redSqr () {
8015 assert(this.red, 'redSqr works only with red numbers');
8016 this.red._verify1(this);
8017 return this.red.sqr(this);
8018 };
8019
8020 BN.prototype.redISqr = function redISqr () {
8021 assert(this.red, 'redISqr works only with red numbers');
8022 this.red._verify1(this);
8023 return this.red.isqr(this);
8024 };
8025
8026 // Square root over p
8027 BN.prototype.redSqrt = function redSqrt () {
8028 assert(this.red, 'redSqrt works only with red numbers');
8029 this.red._verify1(this);
8030 return this.red.sqrt(this);
8031 };
8032
8033 BN.prototype.redInvm = function redInvm () {
8034 assert(this.red, 'redInvm works only with red numbers');
8035 this.red._verify1(this);
8036 return this.red.invm(this);
8037 };
8038
8039 // Return negative clone of `this` % `red modulo`
8040 BN.prototype.redNeg = function redNeg () {
8041 assert(this.red, 'redNeg works only with red numbers');
8042 this.red._verify1(this);
8043 return this.red.neg(this);
8044 };
8045
8046 BN.prototype.redPow = function redPow (num) {
8047 assert(this.red && !num.red, 'redPow(normalNum)');
8048 this.red._verify1(this);
8049 return this.red.pow(this, num);
8050 };
8051
8052 // Prime numbers with efficient reduction
8053 var primes = {
8054 k256: null,
8055 p224: null,
8056 p192: null,
8057 p25519: null
8058 };
8059
8060 // Pseudo-Mersenne prime
8061 function MPrime (name, p) {
8062 // P = 2 ^ N - K
8063 this.name = name;
8064 this.p = new BN(p, 16);
8065 this.n = this.p.bitLength();
8066 this.k = new BN(1).iushln(this.n).isub(this.p);
8067
8068 this.tmp = this._tmp();
8069 }
8070
8071 MPrime.prototype._tmp = function _tmp () {
8072 var tmp = new BN(null);
8073 tmp.words = new Array(Math.ceil(this.n / 13));
8074 return tmp;
8075 };
8076
8077 MPrime.prototype.ireduce = function ireduce (num) {
8078 // Assumes that `num` is less than `P^2`
8079 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
8080 var r = num;
8081 var rlen;
8082
8083 do {
8084 this.split(r, this.tmp);
8085 r = this.imulK(r);
8086 r = r.iadd(this.tmp);
8087 rlen = r.bitLength();
8088 } while (rlen > this.n);
8089
8090 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
8091 if (cmp === 0) {
8092 r.words[0] = 0;
8093 r.length = 1;
8094 } else if (cmp > 0) {
8095 r.isub(this.p);
8096 } else {
8097 r.strip();
8098 }
8099
8100 return r;
8101 };
8102
8103 MPrime.prototype.split = function split (input, out) {
8104 input.iushrn(this.n, 0, out);
8105 };
8106
8107 MPrime.prototype.imulK = function imulK (num) {
8108 return num.imul(this.k);
8109 };
8110
8111 function K256 () {
8112 MPrime.call(
8113 this,
8114 'k256',
8115 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
8116 }
8117 inherits(K256, MPrime);
8118
8119 K256.prototype.split = function split (input, output) {
8120 // 256 = 9 * 26 + 22
8121 var mask = 0x3fffff;
8122
8123 var outLen = Math.min(input.length, 9);
8124 for (var i = 0; i < outLen; i++) {
8125 output.words[i] = input.words[i];
8126 }
8127 output.length = outLen;
8128
8129 if (input.length <= 9) {
8130 input.words[0] = 0;
8131 input.length = 1;
8132 return;
8133 }
8134
8135 // Shift by 9 limbs
8136 var prev = input.words[9];
8137 output.words[output.length++] = prev & mask;
8138
8139 for (i = 10; i < input.length; i++) {
8140 var next = input.words[i] | 0;
8141 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
8142 prev = next;
8143 }
8144 prev >>>= 22;
8145 input.words[i - 10] = prev;
8146 if (prev === 0 && input.length > 10) {
8147 input.length -= 10;
8148 } else {
8149 input.length -= 9;
8150 }
8151 };
8152
8153 K256.prototype.imulK = function imulK (num) {
8154 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
8155 num.words[num.length] = 0;
8156 num.words[num.length + 1] = 0;
8157 num.length += 2;
8158
8159 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
8160 var lo = 0;
8161 for (var i = 0; i < num.length; i++) {
8162 var w = num.words[i] | 0;
8163 lo += w * 0x3d1;
8164 num.words[i] = lo & 0x3ffffff;
8165 lo = w * 0x40 + ((lo / 0x4000000) | 0);
8166 }
8167
8168 // Fast length reduction
8169 if (num.words[num.length - 1] === 0) {
8170 num.length--;
8171 if (num.words[num.length - 1] === 0) {
8172 num.length--;
8173 }
8174 }
8175 return num;
8176 };
8177
8178 function P224 () {
8179 MPrime.call(
8180 this,
8181 'p224',
8182 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
8183 }
8184 inherits(P224, MPrime);
8185
8186 function P192 () {
8187 MPrime.call(
8188 this,
8189 'p192',
8190 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
8191 }
8192 inherits(P192, MPrime);
8193
8194 function P25519 () {
8195 // 2 ^ 255 - 19
8196 MPrime.call(
8197 this,
8198 '25519',
8199 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
8200 }
8201 inherits(P25519, MPrime);
8202
8203 P25519.prototype.imulK = function imulK (num) {
8204 // K = 0x13
8205 var carry = 0;
8206 for (var i = 0; i < num.length; i++) {
8207 var hi = (num.words[i] | 0) * 0x13 + carry;
8208 var lo = hi & 0x3ffffff;
8209 hi >>>= 26;
8210
8211 num.words[i] = lo;
8212 carry = hi;
8213 }
8214 if (carry !== 0) {
8215 num.words[num.length++] = carry;
8216 }
8217 return num;
8218 };
8219
8220 // Exported mostly for testing purposes, use plain name instead
8221 BN._prime = function prime (name) {
8222 // Cached version of prime
8223 if (primes[name]) return primes[name];
8224
8225 var prime;
8226 if (name === 'k256') {
8227 prime = new K256();
8228 } else if (name === 'p224') {
8229 prime = new P224();
8230 } else if (name === 'p192') {
8231 prime = new P192();
8232 } else if (name === 'p25519') {
8233 prime = new P25519();
8234 } else {
8235 throw new Error('Unknown prime ' + name);
8236 }
8237 primes[name] = prime;
8238
8239 return prime;
8240 };
8241
8242 //
8243 // Base reduction engine
8244 //
8245 function Red (m) {
8246 if (typeof m === 'string') {
8247 var prime = BN._prime(m);
8248 this.m = prime.p;
8249 this.prime = prime;
8250 } else {
8251 assert(m.gtn(1), 'modulus must be greater than 1');
8252 this.m = m;
8253 this.prime = null;
8254 }
8255 }
8256
8257 Red.prototype._verify1 = function _verify1 (a) {
8258 assert(a.negative === 0, 'red works only with positives');
8259 assert(a.red, 'red works only with red numbers');
8260 };
8261
8262 Red.prototype._verify2 = function _verify2 (a, b) {
8263 assert((a.negative | b.negative) === 0, 'red works only with positives');
8264 assert(a.red && a.red === b.red,
8265 'red works only with red numbers');
8266 };
8267
8268 Red.prototype.imod = function imod (a) {
8269 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
8270 return a.umod(this.m)._forceRed(this);
8271 };
8272
8273 Red.prototype.neg = function neg (a) {
8274 if (a.isZero()) {
8275 return a.clone();
8276 }
8277
8278 return this.m.sub(a)._forceRed(this);
8279 };
8280
8281 Red.prototype.add = function add (a, b) {
8282 this._verify2(a, b);
8283
8284 var res = a.add(b);
8285 if (res.cmp(this.m) >= 0) {
8286 res.isub(this.m);
8287 }
8288 return res._forceRed(this);
8289 };
8290
8291 Red.prototype.iadd = function iadd (a, b) {
8292 this._verify2(a, b);
8293
8294 var res = a.iadd(b);
8295 if (res.cmp(this.m) >= 0) {
8296 res.isub(this.m);
8297 }
8298 return res;
8299 };
8300
8301 Red.prototype.sub = function sub (a, b) {
8302 this._verify2(a, b);
8303
8304 var res = a.sub(b);
8305 if (res.cmpn(0) < 0) {
8306 res.iadd(this.m);
8307 }
8308 return res._forceRed(this);
8309 };
8310
8311 Red.prototype.isub = function isub (a, b) {
8312 this._verify2(a, b);
8313
8314 var res = a.isub(b);
8315 if (res.cmpn(0) < 0) {
8316 res.iadd(this.m);
8317 }
8318 return res;
8319 };
8320
8321 Red.prototype.shl = function shl (a, num) {
8322 this._verify1(a);
8323 return this.imod(a.ushln(num));
8324 };
8325
8326 Red.prototype.imul = function imul (a, b) {
8327 this._verify2(a, b);
8328 return this.imod(a.imul(b));
8329 };
8330
8331 Red.prototype.mul = function mul (a, b) {
8332 this._verify2(a, b);
8333 return this.imod(a.mul(b));
8334 };
8335
8336 Red.prototype.isqr = function isqr (a) {
8337 return this.imul(a, a.clone());
8338 };
8339
8340 Red.prototype.sqr = function sqr (a) {
8341 return this.mul(a, a);
8342 };
8343
8344 Red.prototype.sqrt = function sqrt (a) {
8345 if (a.isZero()) return a.clone();
8346
8347 var mod3 = this.m.andln(3);
8348 assert(mod3 % 2 === 1);
8349
8350 // Fast case
8351 if (mod3 === 3) {
8352 var pow = this.m.add(new BN(1)).iushrn(2);
8353 return this.pow(a, pow);
8354 }
8355
8356 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
8357 //
8358 // Find Q and S, that Q * 2 ^ S = (P - 1)
8359 var q = this.m.subn(1);
8360 var s = 0;
8361 while (!q.isZero() && q.andln(1) === 0) {
8362 s++;
8363 q.iushrn(1);
8364 }
8365 assert(!q.isZero());
8366
8367 var one = new BN(1).toRed(this);
8368 var nOne = one.redNeg();
8369
8370 // Find quadratic non-residue
8371 // NOTE: Max is such because of generalized Riemann hypothesis.
8372 var lpow = this.m.subn(1).iushrn(1);
8373 var z = this.m.bitLength();
8374 z = new BN(2 * z * z).toRed(this);
8375
8376 while (this.pow(z, lpow).cmp(nOne) !== 0) {
8377 z.redIAdd(nOne);
8378 }
8379
8380 var c = this.pow(z, q);
8381 var r = this.pow(a, q.addn(1).iushrn(1));
8382 var t = this.pow(a, q);
8383 var m = s;
8384 while (t.cmp(one) !== 0) {
8385 var tmp = t;
8386 for (var i = 0; tmp.cmp(one) !== 0; i++) {
8387 tmp = tmp.redSqr();
8388 }
8389 assert(i < m);
8390 var b = this.pow(c, new BN(1).iushln(m - i - 1));
8391
8392 r = r.redMul(b);
8393 c = b.redSqr();
8394 t = t.redMul(c);
8395 m = i;
8396 }
8397
8398 return r;
8399 };
8400
8401 Red.prototype.invm = function invm (a) {
8402 var inv = a._invmp(this.m);
8403 if (inv.negative !== 0) {
8404 inv.negative = 0;
8405 return this.imod(inv).redNeg();
8406 } else {
8407 return this.imod(inv);
8408 }
8409 };
8410
8411 Red.prototype.pow = function pow (a, num) {
8412 if (num.isZero()) return new BN(1).toRed(this);
8413 if (num.cmpn(1) === 0) return a.clone();
8414
8415 var windowSize = 4;
8416 var wnd = new Array(1 << windowSize);
8417 wnd[0] = new BN(1).toRed(this);
8418 wnd[1] = a;
8419 for (var i = 2; i < wnd.length; i++) {
8420 wnd[i] = this.mul(wnd[i - 1], a);
8421 }
8422
8423 var res = wnd[0];
8424 var current = 0;
8425 var currentLen = 0;
8426 var start = num.bitLength() % 26;
8427 if (start === 0) {
8428 start = 26;
8429 }
8430
8431 for (i = num.length - 1; i >= 0; i--) {
8432 var word = num.words[i];
8433 for (var j = start - 1; j >= 0; j--) {
8434 var bit = (word >> j) & 1;
8435 if (res !== wnd[0]) {
8436 res = this.sqr(res);
8437 }
8438
8439 if (bit === 0 && current === 0) {
8440 currentLen = 0;
8441 continue;
8442 }
8443
8444 current <<= 1;
8445 current |= bit;
8446 currentLen++;
8447 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
8448
8449 res = this.mul(res, wnd[current]);
8450 currentLen = 0;
8451 current = 0;
8452 }
8453 start = 26;
8454 }
8455
8456 return res;
8457 };
8458
8459 Red.prototype.convertTo = function convertTo (num) {
8460 var r = num.umod(this.m);
8461
8462 return r === num ? r.clone() : r;
8463 };
8464
8465 Red.prototype.convertFrom = function convertFrom (num) {
8466 var res = num.clone();
8467 res.red = null;
8468 return res;
8469 };
8470
8471 //
8472 // Montgomery method engine
8473 //
8474
8475 BN.mont = function mont (num) {
8476 return new Mont(num);
8477 };
8478
8479 function Mont (m) {
8480 Red.call(this, m);
8481
8482 this.shift = this.m.bitLength();
8483 if (this.shift % 26 !== 0) {
8484 this.shift += 26 - (this.shift % 26);
8485 }
8486
8487 this.r = new BN(1).iushln(this.shift);
8488 this.r2 = this.imod(this.r.sqr());
8489 this.rinv = this.r._invmp(this.m);
8490
8491 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
8492 this.minv = this.minv.umod(this.r);
8493 this.minv = this.r.sub(this.minv);
8494 }
8495 inherits(Mont, Red);
8496
8497 Mont.prototype.convertTo = function convertTo (num) {
8498 return this.imod(num.ushln(this.shift));
8499 };
8500
8501 Mont.prototype.convertFrom = function convertFrom (num) {
8502 var r = this.imod(num.mul(this.rinv));
8503 r.red = null;
8504 return r;
8505 };
8506
8507 Mont.prototype.imul = function imul (a, b) {
8508 if (a.isZero() || b.isZero()) {
8509 a.words[0] = 0;
8510 a.length = 1;
8511 return a;
8512 }
8513
8514 var t = a.imul(b);
8515 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
8516 var u = t.isub(c).iushrn(this.shift);
8517 var res = u;
8518
8519 if (u.cmp(this.m) >= 0) {
8520 res = u.isub(this.m);
8521 } else if (u.cmpn(0) < 0) {
8522 res = u.iadd(this.m);
8523 }
8524
8525 return res._forceRed(this);
8526 };
8527
8528 Mont.prototype.mul = function mul (a, b) {
8529 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
8530
8531 var t = a.mul(b);
8532 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
8533 var u = t.isub(c).iushrn(this.shift);
8534 var res = u;
8535 if (u.cmp(this.m) >= 0) {
8536 res = u.isub(this.m);
8537 } else if (u.cmpn(0) < 0) {
8538 res = u.iadd(this.m);
8539 }
8540
8541 return res._forceRed(this);
8542 };
8543
8544 Mont.prototype.invm = function invm (a) {
8545 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
8546 var res = this.imod(a._invmp(this.m).mul(this.r2));
8547 return res._forceRed(this);
8548 };
8549})(typeof module === 'undefined' || module, this);
8550
8551},{"buffer":23}],22:[function(require,module,exports){
8552var r;
8553
8554module.exports = function rand(len) {
8555 if (!r)
8556 r = new Rand(null);
8557
8558 return r.generate(len);
8559};
8560
8561function Rand(rand) {
8562 this.rand = rand;
8563}
8564module.exports.Rand = Rand;
8565
8566Rand.prototype.generate = function generate(len) {
8567 return this._rand(len);
8568};
8569
8570// Emulate crypto API using randy
8571Rand.prototype._rand = function _rand(n) {
8572 if (this.rand.getBytes)
8573 return this.rand.getBytes(n);
8574
8575 var res = new Uint8Array(n);
8576 for (var i = 0; i < res.length; i++)
8577 res[i] = this.rand.getByte();
8578 return res;
8579};
8580
8581if (typeof self === 'object') {
8582 if (self.crypto && self.crypto.getRandomValues) {
8583 // Modern browsers
8584 Rand.prototype._rand = function _rand(n) {
8585 var arr = new Uint8Array(n);
8586 self.crypto.getRandomValues(arr);
8587 return arr;
8588 };
8589 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
8590 // IE
8591 Rand.prototype._rand = function _rand(n) {
8592 var arr = new Uint8Array(n);
8593 self.msCrypto.getRandomValues(arr);
8594 return arr;
8595 };
8596
8597 // Safari's WebWorkers do not have `crypto`
8598 } else if (typeof window === 'object') {
8599 // Old junk
8600 Rand.prototype._rand = function() {
8601 throw new Error('Not implemented yet');
8602 };
8603 }
8604} else {
8605 // Node.js or Web worker with no crypto support
8606 try {
8607 var crypto = require('crypto');
8608 if (typeof crypto.randomBytes !== 'function')
8609 throw new Error('Not supported');
8610
8611 Rand.prototype._rand = function _rand(n) {
8612 return crypto.randomBytes(n);
8613 };
8614 } catch (e) {
8615 }
8616}
8617
8618},{"crypto":23}],23:[function(require,module,exports){
8619
8620},{}],24:[function(require,module,exports){
8621// based on the aes implimentation in triple sec
8622// https://github.com/keybase/triplesec
8623// which is in turn based on the one from crypto-js
8624// https://code.google.com/p/crypto-js/
8625
8626var Buffer = require('safe-buffer').Buffer
8627
8628function asUInt32Array (buf) {
8629 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
8630
8631 var len = (buf.length / 4) | 0
8632 var out = new Array(len)
8633
8634 for (var i = 0; i < len; i++) {
8635 out[i] = buf.readUInt32BE(i * 4)
8636 }
8637
8638 return out
8639}
8640
8641function scrubVec (v) {
8642 for (var i = 0; i < v.length; v++) {
8643 v[i] = 0
8644 }
8645}
8646
8647function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
8648 var SUB_MIX0 = SUB_MIX[0]
8649 var SUB_MIX1 = SUB_MIX[1]
8650 var SUB_MIX2 = SUB_MIX[2]
8651 var SUB_MIX3 = SUB_MIX[3]
8652
8653 var s0 = M[0] ^ keySchedule[0]
8654 var s1 = M[1] ^ keySchedule[1]
8655 var s2 = M[2] ^ keySchedule[2]
8656 var s3 = M[3] ^ keySchedule[3]
8657 var t0, t1, t2, t3
8658 var ksRow = 4
8659
8660 for (var round = 1; round < nRounds; round++) {
8661 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
8662 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
8663 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
8664 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
8665 s0 = t0
8666 s1 = t1
8667 s2 = t2
8668 s3 = t3
8669 }
8670
8671 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
8672 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
8673 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
8674 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
8675 t0 = t0 >>> 0
8676 t1 = t1 >>> 0
8677 t2 = t2 >>> 0
8678 t3 = t3 >>> 0
8679
8680 return [t0, t1, t2, t3]
8681}
8682
8683// AES constants
8684var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
8685var G = (function () {
8686 // Compute double table
8687 var d = new Array(256)
8688 for (var j = 0; j < 256; j++) {
8689 if (j < 128) {
8690 d[j] = j << 1
8691 } else {
8692 d[j] = (j << 1) ^ 0x11b
8693 }
8694 }
8695
8696 var SBOX = []
8697 var INV_SBOX = []
8698 var SUB_MIX = [[], [], [], []]
8699 var INV_SUB_MIX = [[], [], [], []]
8700
8701 // Walk GF(2^8)
8702 var x = 0
8703 var xi = 0
8704 for (var i = 0; i < 256; ++i) {
8705 // Compute sbox
8706 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
8707 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
8708 SBOX[x] = sx
8709 INV_SBOX[sx] = x
8710
8711 // Compute multiplication
8712 var x2 = d[x]
8713 var x4 = d[x2]
8714 var x8 = d[x4]
8715
8716 // Compute sub bytes, mix columns tables
8717 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
8718 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
8719 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
8720 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
8721 SUB_MIX[3][x] = t
8722
8723 // Compute inv sub bytes, inv mix columns tables
8724 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
8725 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
8726 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
8727 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
8728 INV_SUB_MIX[3][sx] = t
8729
8730 if (x === 0) {
8731 x = xi = 1
8732 } else {
8733 x = x2 ^ d[d[d[x8 ^ x2]]]
8734 xi ^= d[d[xi]]
8735 }
8736 }
8737
8738 return {
8739 SBOX: SBOX,
8740 INV_SBOX: INV_SBOX,
8741 SUB_MIX: SUB_MIX,
8742 INV_SUB_MIX: INV_SUB_MIX
8743 }
8744})()
8745
8746function AES (key) {
8747 this._key = asUInt32Array(key)
8748 this._reset()
8749}
8750
8751AES.blockSize = 4 * 4
8752AES.keySize = 256 / 8
8753AES.prototype.blockSize = AES.blockSize
8754AES.prototype.keySize = AES.keySize
8755AES.prototype._reset = function () {
8756 var keyWords = this._key
8757 var keySize = keyWords.length
8758 var nRounds = keySize + 6
8759 var ksRows = (nRounds + 1) * 4
8760
8761 var keySchedule = []
8762 for (var k = 0; k < keySize; k++) {
8763 keySchedule[k] = keyWords[k]
8764 }
8765
8766 for (k = keySize; k < ksRows; k++) {
8767 var t = keySchedule[k - 1]
8768
8769 if (k % keySize === 0) {
8770 t = (t << 8) | (t >>> 24)
8771 t =
8772 (G.SBOX[t >>> 24] << 24) |
8773 (G.SBOX[(t >>> 16) & 0xff] << 16) |
8774 (G.SBOX[(t >>> 8) & 0xff] << 8) |
8775 (G.SBOX[t & 0xff])
8776
8777 t ^= RCON[(k / keySize) | 0] << 24
8778 } else if (keySize > 6 && k % keySize === 4) {
8779 t =
8780 (G.SBOX[t >>> 24] << 24) |
8781 (G.SBOX[(t >>> 16) & 0xff] << 16) |
8782 (G.SBOX[(t >>> 8) & 0xff] << 8) |
8783 (G.SBOX[t & 0xff])
8784 }
8785
8786 keySchedule[k] = keySchedule[k - keySize] ^ t
8787 }
8788
8789 var invKeySchedule = []
8790 for (var ik = 0; ik < ksRows; ik++) {
8791 var ksR = ksRows - ik
8792 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
8793
8794 if (ik < 4 || ksR <= 4) {
8795 invKeySchedule[ik] = tt
8796 } else {
8797 invKeySchedule[ik] =
8798 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
8799 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
8800 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
8801 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
8802 }
8803 }
8804
8805 this._nRounds = nRounds
8806 this._keySchedule = keySchedule
8807 this._invKeySchedule = invKeySchedule
8808}
8809
8810AES.prototype.encryptBlockRaw = function (M) {
8811 M = asUInt32Array(M)
8812 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
8813}
8814
8815AES.prototype.encryptBlock = function (M) {
8816 var out = this.encryptBlockRaw(M)
8817 var buf = Buffer.allocUnsafe(16)
8818 buf.writeUInt32BE(out[0], 0)
8819 buf.writeUInt32BE(out[1], 4)
8820 buf.writeUInt32BE(out[2], 8)
8821 buf.writeUInt32BE(out[3], 12)
8822 return buf
8823}
8824
8825AES.prototype.decryptBlock = function (M) {
8826 M = asUInt32Array(M)
8827
8828 // swap
8829 var m1 = M[1]
8830 M[1] = M[3]
8831 M[3] = m1
8832
8833 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
8834 var buf = Buffer.allocUnsafe(16)
8835 buf.writeUInt32BE(out[0], 0)
8836 buf.writeUInt32BE(out[3], 4)
8837 buf.writeUInt32BE(out[2], 8)
8838 buf.writeUInt32BE(out[1], 12)
8839 return buf
8840}
8841
8842AES.prototype.scrub = function () {
8843 scrubVec(this._keySchedule)
8844 scrubVec(this._invKeySchedule)
8845 scrubVec(this._key)
8846}
8847
8848module.exports.AES = AES
8849
8850},{"safe-buffer":156}],25:[function(require,module,exports){
8851var aes = require('./aes')
8852var Buffer = require('safe-buffer').Buffer
8853var Transform = require('cipher-base')
8854var inherits = require('inherits')
8855var GHASH = require('./ghash')
8856var xor = require('buffer-xor')
8857var incr32 = require('./incr32')
8858
8859function xorTest (a, b) {
8860 var out = 0
8861 if (a.length !== b.length) out++
8862
8863 var len = Math.min(a.length, b.length)
8864 for (var i = 0; i < len; ++i) {
8865 out += (a[i] ^ b[i])
8866 }
8867
8868 return out
8869}
8870
8871function calcIv (self, iv, ck) {
8872 if (iv.length === 12) {
8873 self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
8874 return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
8875 }
8876 var ghash = new GHASH(ck)
8877 var len = iv.length
8878 var toPad = len % 16
8879 ghash.update(iv)
8880 if (toPad) {
8881 toPad = 16 - toPad
8882 ghash.update(Buffer.alloc(toPad, 0))
8883 }
8884 ghash.update(Buffer.alloc(8, 0))
8885 var ivBits = len * 8
8886 var tail = Buffer.alloc(8)
8887 tail.writeUIntBE(ivBits, 0, 8)
8888 ghash.update(tail)
8889 self._finID = ghash.state
8890 var out = Buffer.from(self._finID)
8891 incr32(out)
8892 return out
8893}
8894function StreamCipher (mode, key, iv, decrypt) {
8895 Transform.call(this)
8896
8897 var h = Buffer.alloc(4, 0)
8898
8899 this._cipher = new aes.AES(key)
8900 var ck = this._cipher.encryptBlock(h)
8901 this._ghash = new GHASH(ck)
8902 iv = calcIv(this, iv, ck)
8903
8904 this._prev = Buffer.from(iv)
8905 this._cache = Buffer.allocUnsafe(0)
8906 this._secCache = Buffer.allocUnsafe(0)
8907 this._decrypt = decrypt
8908 this._alen = 0
8909 this._len = 0
8910 this._mode = mode
8911
8912 this._authTag = null
8913 this._called = false
8914}
8915
8916inherits(StreamCipher, Transform)
8917
8918StreamCipher.prototype._update = function (chunk) {
8919 if (!this._called && this._alen) {
8920 var rump = 16 - (this._alen % 16)
8921 if (rump < 16) {
8922 rump = Buffer.alloc(rump, 0)
8923 this._ghash.update(rump)
8924 }
8925 }
8926
8927 this._called = true
8928 var out = this._mode.encrypt(this, chunk)
8929 if (this._decrypt) {
8930 this._ghash.update(chunk)
8931 } else {
8932 this._ghash.update(out)
8933 }
8934 this._len += chunk.length
8935 return out
8936}
8937
8938StreamCipher.prototype._final = function () {
8939 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
8940
8941 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
8942 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
8943
8944 this._authTag = tag
8945 this._cipher.scrub()
8946}
8947
8948StreamCipher.prototype.getAuthTag = function getAuthTag () {
8949 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
8950
8951 return this._authTag
8952}
8953
8954StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
8955 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
8956
8957 this._authTag = tag
8958}
8959
8960StreamCipher.prototype.setAAD = function setAAD (buf) {
8961 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
8962
8963 this._ghash.update(buf)
8964 this._alen += buf.length
8965}
8966
8967module.exports = StreamCipher
8968
8969},{"./aes":24,"./ghash":29,"./incr32":30,"buffer-xor":52,"cipher-base":54,"inherits":107,"safe-buffer":156}],26:[function(require,module,exports){
8970var ciphers = require('./encrypter')
8971var deciphers = require('./decrypter')
8972var modes = require('./modes/list.json')
8973
8974function getCiphers () {
8975 return Object.keys(modes)
8976}
8977
8978exports.createCipher = exports.Cipher = ciphers.createCipher
8979exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
8980exports.createDecipher = exports.Decipher = deciphers.createDecipher
8981exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
8982exports.listCiphers = exports.getCiphers = getCiphers
8983
8984},{"./decrypter":27,"./encrypter":28,"./modes/list.json":38}],27:[function(require,module,exports){
8985var AuthCipher = require('./authCipher')
8986var Buffer = require('safe-buffer').Buffer
8987var MODES = require('./modes')
8988var StreamCipher = require('./streamCipher')
8989var Transform = require('cipher-base')
8990var aes = require('./aes')
8991var ebtk = require('evp_bytestokey')
8992var inherits = require('inherits')
8993
8994function Decipher (mode, key, iv) {
8995 Transform.call(this)
8996
8997 this._cache = new Splitter()
8998 this._last = void 0
8999 this._cipher = new aes.AES(key)
9000 this._prev = Buffer.from(iv)
9001 this._mode = mode
9002 this._autopadding = true
9003}
9004
9005inherits(Decipher, Transform)
9006
9007Decipher.prototype._update = function (data) {
9008 this._cache.add(data)
9009 var chunk
9010 var thing
9011 var out = []
9012 while ((chunk = this._cache.get(this._autopadding))) {
9013 thing = this._mode.decrypt(this, chunk)
9014 out.push(thing)
9015 }
9016 return Buffer.concat(out)
9017}
9018
9019Decipher.prototype._final = function () {
9020 var chunk = this._cache.flush()
9021 if (this._autopadding) {
9022 return unpad(this._mode.decrypt(this, chunk))
9023 } else if (chunk) {
9024 throw new Error('data not multiple of block length')
9025 }
9026}
9027
9028Decipher.prototype.setAutoPadding = function (setTo) {
9029 this._autopadding = !!setTo
9030 return this
9031}
9032
9033function Splitter () {
9034 this.cache = Buffer.allocUnsafe(0)
9035}
9036
9037Splitter.prototype.add = function (data) {
9038 this.cache = Buffer.concat([this.cache, data])
9039}
9040
9041Splitter.prototype.get = function (autoPadding) {
9042 var out
9043 if (autoPadding) {
9044 if (this.cache.length > 16) {
9045 out = this.cache.slice(0, 16)
9046 this.cache = this.cache.slice(16)
9047 return out
9048 }
9049 } else {
9050 if (this.cache.length >= 16) {
9051 out = this.cache.slice(0, 16)
9052 this.cache = this.cache.slice(16)
9053 return out
9054 }
9055 }
9056
9057 return null
9058}
9059
9060Splitter.prototype.flush = function () {
9061 if (this.cache.length) return this.cache
9062}
9063
9064function unpad (last) {
9065 var padded = last[15]
9066 var i = -1
9067 while (++i < padded) {
9068 if (last[(i + (16 - padded))] !== padded) {
9069 throw new Error('unable to decrypt data')
9070 }
9071 }
9072 if (padded === 16) return
9073
9074 return last.slice(0, 16 - padded)
9075}
9076
9077function createDecipheriv (suite, password, iv) {
9078 var config = MODES[suite.toLowerCase()]
9079 if (!config) throw new TypeError('invalid suite type')
9080
9081 if (typeof iv === 'string') iv = Buffer.from(iv)
9082 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
9083
9084 if (typeof password === 'string') password = Buffer.from(password)
9085 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
9086
9087 if (config.type === 'stream') {
9088 return new StreamCipher(config.module, password, iv, true)
9089 } else if (config.type === 'auth') {
9090 return new AuthCipher(config.module, password, iv, true)
9091 }
9092
9093 return new Decipher(config.module, password, iv)
9094}
9095
9096function createDecipher (suite, password) {
9097 var config = MODES[suite.toLowerCase()]
9098 if (!config) throw new TypeError('invalid suite type')
9099
9100 var keys = ebtk(password, false, config.key, config.iv)
9101 return createDecipheriv(suite, keys.key, keys.iv)
9102}
9103
9104exports.createDecipher = createDecipher
9105exports.createDecipheriv = createDecipheriv
9106
9107},{"./aes":24,"./authCipher":25,"./modes":37,"./streamCipher":40,"cipher-base":54,"evp_bytestokey":90,"inherits":107,"safe-buffer":156}],28:[function(require,module,exports){
9108var MODES = require('./modes')
9109var AuthCipher = require('./authCipher')
9110var Buffer = require('safe-buffer').Buffer
9111var StreamCipher = require('./streamCipher')
9112var Transform = require('cipher-base')
9113var aes = require('./aes')
9114var ebtk = require('evp_bytestokey')
9115var inherits = require('inherits')
9116
9117function Cipher (mode, key, iv) {
9118 Transform.call(this)
9119
9120 this._cache = new Splitter()
9121 this._cipher = new aes.AES(key)
9122 this._prev = Buffer.from(iv)
9123 this._mode = mode
9124 this._autopadding = true
9125}
9126
9127inherits(Cipher, Transform)
9128
9129Cipher.prototype._update = function (data) {
9130 this._cache.add(data)
9131 var chunk
9132 var thing
9133 var out = []
9134
9135 while ((chunk = this._cache.get())) {
9136 thing = this._mode.encrypt(this, chunk)
9137 out.push(thing)
9138 }
9139
9140 return Buffer.concat(out)
9141}
9142
9143var PADDING = Buffer.alloc(16, 0x10)
9144
9145Cipher.prototype._final = function () {
9146 var chunk = this._cache.flush()
9147 if (this._autopadding) {
9148 chunk = this._mode.encrypt(this, chunk)
9149 this._cipher.scrub()
9150 return chunk
9151 }
9152
9153 if (!chunk.equals(PADDING)) {
9154 this._cipher.scrub()
9155 throw new Error('data not multiple of block length')
9156 }
9157}
9158
9159Cipher.prototype.setAutoPadding = function (setTo) {
9160 this._autopadding = !!setTo
9161 return this
9162}
9163
9164function Splitter () {
9165 this.cache = Buffer.allocUnsafe(0)
9166}
9167
9168Splitter.prototype.add = function (data) {
9169 this.cache = Buffer.concat([this.cache, data])
9170}
9171
9172Splitter.prototype.get = function () {
9173 if (this.cache.length > 15) {
9174 var out = this.cache.slice(0, 16)
9175 this.cache = this.cache.slice(16)
9176 return out
9177 }
9178 return null
9179}
9180
9181Splitter.prototype.flush = function () {
9182 var len = 16 - this.cache.length
9183 var padBuff = Buffer.allocUnsafe(len)
9184
9185 var i = -1
9186 while (++i < len) {
9187 padBuff.writeUInt8(len, i)
9188 }
9189
9190 return Buffer.concat([this.cache, padBuff])
9191}
9192
9193function createCipheriv (suite, password, iv) {
9194 var config = MODES[suite.toLowerCase()]
9195 if (!config) throw new TypeError('invalid suite type')
9196
9197 if (typeof password === 'string') password = Buffer.from(password)
9198 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
9199
9200 if (typeof iv === 'string') iv = Buffer.from(iv)
9201 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
9202
9203 if (config.type === 'stream') {
9204 return new StreamCipher(config.module, password, iv)
9205 } else if (config.type === 'auth') {
9206 return new AuthCipher(config.module, password, iv)
9207 }
9208
9209 return new Cipher(config.module, password, iv)
9210}
9211
9212function createCipher (suite, password) {
9213 var config = MODES[suite.toLowerCase()]
9214 if (!config) throw new TypeError('invalid suite type')
9215
9216 var keys = ebtk(password, false, config.key, config.iv)
9217 return createCipheriv(suite, keys.key, keys.iv)
9218}
9219
9220exports.createCipheriv = createCipheriv
9221exports.createCipher = createCipher
9222
9223},{"./aes":24,"./authCipher":25,"./modes":37,"./streamCipher":40,"cipher-base":54,"evp_bytestokey":90,"inherits":107,"safe-buffer":156}],29:[function(require,module,exports){
9224var Buffer = require('safe-buffer').Buffer
9225var ZEROES = Buffer.alloc(16, 0)
9226
9227function toArray (buf) {
9228 return [
9229 buf.readUInt32BE(0),
9230 buf.readUInt32BE(4),
9231 buf.readUInt32BE(8),
9232 buf.readUInt32BE(12)
9233 ]
9234}
9235
9236function fromArray (out) {
9237 var buf = Buffer.allocUnsafe(16)
9238 buf.writeUInt32BE(out[0] >>> 0, 0)
9239 buf.writeUInt32BE(out[1] >>> 0, 4)
9240 buf.writeUInt32BE(out[2] >>> 0, 8)
9241 buf.writeUInt32BE(out[3] >>> 0, 12)
9242 return buf
9243}
9244
9245function GHASH (key) {
9246 this.h = key
9247 this.state = Buffer.alloc(16, 0)
9248 this.cache = Buffer.allocUnsafe(0)
9249}
9250
9251// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
9252// by Juho Vähä-Herttua
9253GHASH.prototype.ghash = function (block) {
9254 var i = -1
9255 while (++i < block.length) {
9256 this.state[i] ^= block[i]
9257 }
9258 this._multiply()
9259}
9260
9261GHASH.prototype._multiply = function () {
9262 var Vi = toArray(this.h)
9263 var Zi = [0, 0, 0, 0]
9264 var j, xi, lsbVi
9265 var i = -1
9266 while (++i < 128) {
9267 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
9268 if (xi) {
9269 // Z_i+1 = Z_i ^ V_i
9270 Zi[0] ^= Vi[0]
9271 Zi[1] ^= Vi[1]
9272 Zi[2] ^= Vi[2]
9273 Zi[3] ^= Vi[3]
9274 }
9275
9276 // Store the value of LSB(V_i)
9277 lsbVi = (Vi[3] & 1) !== 0
9278
9279 // V_i+1 = V_i >> 1
9280 for (j = 3; j > 0; j--) {
9281 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
9282 }
9283 Vi[0] = Vi[0] >>> 1
9284
9285 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
9286 if (lsbVi) {
9287 Vi[0] = Vi[0] ^ (0xe1 << 24)
9288 }
9289 }
9290 this.state = fromArray(Zi)
9291}
9292
9293GHASH.prototype.update = function (buf) {
9294 this.cache = Buffer.concat([this.cache, buf])
9295 var chunk
9296 while (this.cache.length >= 16) {
9297 chunk = this.cache.slice(0, 16)
9298 this.cache = this.cache.slice(16)
9299 this.ghash(chunk)
9300 }
9301}
9302
9303GHASH.prototype.final = function (abl, bl) {
9304 if (this.cache.length) {
9305 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
9306 }
9307
9308 this.ghash(fromArray([0, abl, 0, bl]))
9309 return this.state
9310}
9311
9312module.exports = GHASH
9313
9314},{"safe-buffer":156}],30:[function(require,module,exports){
9315function incr32 (iv) {
9316 var len = iv.length
9317 var item
9318 while (len--) {
9319 item = iv.readUInt8(len)
9320 if (item === 255) {
9321 iv.writeUInt8(0, len)
9322 } else {
9323 item++
9324 iv.writeUInt8(item, len)
9325 break
9326 }
9327 }
9328}
9329module.exports = incr32
9330
9331},{}],31:[function(require,module,exports){
9332var xor = require('buffer-xor')
9333
9334exports.encrypt = function (self, block) {
9335 var data = xor(block, self._prev)
9336
9337 self._prev = self._cipher.encryptBlock(data)
9338 return self._prev
9339}
9340
9341exports.decrypt = function (self, block) {
9342 var pad = self._prev
9343
9344 self._prev = block
9345 var out = self._cipher.decryptBlock(block)
9346
9347 return xor(out, pad)
9348}
9349
9350},{"buffer-xor":52}],32:[function(require,module,exports){
9351var Buffer = require('safe-buffer').Buffer
9352var xor = require('buffer-xor')
9353
9354function encryptStart (self, data, decrypt) {
9355 var len = data.length
9356 var out = xor(data, self._cache)
9357 self._cache = self._cache.slice(len)
9358 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
9359 return out
9360}
9361
9362exports.encrypt = function (self, data, decrypt) {
9363 var out = Buffer.allocUnsafe(0)
9364 var len
9365
9366 while (data.length) {
9367 if (self._cache.length === 0) {
9368 self._cache = self._cipher.encryptBlock(self._prev)
9369 self._prev = Buffer.allocUnsafe(0)
9370 }
9371
9372 if (self._cache.length <= data.length) {
9373 len = self._cache.length
9374 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
9375 data = data.slice(len)
9376 } else {
9377 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
9378 break
9379 }
9380 }
9381
9382 return out
9383}
9384
9385},{"buffer-xor":52,"safe-buffer":156}],33:[function(require,module,exports){
9386var Buffer = require('safe-buffer').Buffer
9387
9388function encryptByte (self, byteParam, decrypt) {
9389 var pad
9390 var i = -1
9391 var len = 8
9392 var out = 0
9393 var bit, value
9394 while (++i < len) {
9395 pad = self._cipher.encryptBlock(self._prev)
9396 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
9397 value = pad[0] ^ bit
9398 out += ((value & 0x80) >> (i % 8))
9399 self._prev = shiftIn(self._prev, decrypt ? bit : value)
9400 }
9401 return out
9402}
9403
9404function shiftIn (buffer, value) {
9405 var len = buffer.length
9406 var i = -1
9407 var out = Buffer.allocUnsafe(buffer.length)
9408 buffer = Buffer.concat([buffer, Buffer.from([value])])
9409
9410 while (++i < len) {
9411 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
9412 }
9413
9414 return out
9415}
9416
9417exports.encrypt = function (self, chunk, decrypt) {
9418 var len = chunk.length
9419 var out = Buffer.allocUnsafe(len)
9420 var i = -1
9421
9422 while (++i < len) {
9423 out[i] = encryptByte(self, chunk[i], decrypt)
9424 }
9425
9426 return out
9427}
9428
9429},{"safe-buffer":156}],34:[function(require,module,exports){
9430var Buffer = require('safe-buffer').Buffer
9431
9432function encryptByte (self, byteParam, decrypt) {
9433 var pad = self._cipher.encryptBlock(self._prev)
9434 var out = pad[0] ^ byteParam
9435
9436 self._prev = Buffer.concat([
9437 self._prev.slice(1),
9438 Buffer.from([decrypt ? byteParam : out])
9439 ])
9440
9441 return out
9442}
9443
9444exports.encrypt = function (self, chunk, decrypt) {
9445 var len = chunk.length
9446 var out = Buffer.allocUnsafe(len)
9447 var i = -1
9448
9449 while (++i < len) {
9450 out[i] = encryptByte(self, chunk[i], decrypt)
9451 }
9452
9453 return out
9454}
9455
9456},{"safe-buffer":156}],35:[function(require,module,exports){
9457var xor = require('buffer-xor')
9458var Buffer = require('safe-buffer').Buffer
9459var incr32 = require('../incr32')
9460
9461function getBlock (self) {
9462 var out = self._cipher.encryptBlockRaw(self._prev)
9463 incr32(self._prev)
9464 return out
9465}
9466
9467var blockSize = 16
9468exports.encrypt = function (self, chunk) {
9469 var chunkNum = Math.ceil(chunk.length / blockSize)
9470 var start = self._cache.length
9471 self._cache = Buffer.concat([
9472 self._cache,
9473 Buffer.allocUnsafe(chunkNum * blockSize)
9474 ])
9475 for (var i = 0; i < chunkNum; i++) {
9476 var out = getBlock(self)
9477 var offset = start + i * blockSize
9478 self._cache.writeUInt32BE(out[0], offset + 0)
9479 self._cache.writeUInt32BE(out[1], offset + 4)
9480 self._cache.writeUInt32BE(out[2], offset + 8)
9481 self._cache.writeUInt32BE(out[3], offset + 12)
9482 }
9483 var pad = self._cache.slice(0, chunk.length)
9484 self._cache = self._cache.slice(chunk.length)
9485 return xor(chunk, pad)
9486}
9487
9488},{"../incr32":30,"buffer-xor":52,"safe-buffer":156}],36:[function(require,module,exports){
9489exports.encrypt = function (self, block) {
9490 return self._cipher.encryptBlock(block)
9491}
9492
9493exports.decrypt = function (self, block) {
9494 return self._cipher.decryptBlock(block)
9495}
9496
9497},{}],37:[function(require,module,exports){
9498var modeModules = {
9499 ECB: require('./ecb'),
9500 CBC: require('./cbc'),
9501 CFB: require('./cfb'),
9502 CFB8: require('./cfb8'),
9503 CFB1: require('./cfb1'),
9504 OFB: require('./ofb'),
9505 CTR: require('./ctr'),
9506 GCM: require('./ctr')
9507}
9508
9509var modes = require('./list.json')
9510
9511for (var key in modes) {
9512 modes[key].module = modeModules[modes[key].mode]
9513}
9514
9515module.exports = modes
9516
9517},{"./cbc":31,"./cfb":32,"./cfb1":33,"./cfb8":34,"./ctr":35,"./ecb":36,"./list.json":38,"./ofb":39}],38:[function(require,module,exports){
9518module.exports={
9519 "aes-128-ecb": {
9520 "cipher": "AES",
9521 "key": 128,
9522 "iv": 0,
9523 "mode": "ECB",
9524 "type": "block"
9525 },
9526 "aes-192-ecb": {
9527 "cipher": "AES",
9528 "key": 192,
9529 "iv": 0,
9530 "mode": "ECB",
9531 "type": "block"
9532 },
9533 "aes-256-ecb": {
9534 "cipher": "AES",
9535 "key": 256,
9536 "iv": 0,
9537 "mode": "ECB",
9538 "type": "block"
9539 },
9540 "aes-128-cbc": {
9541 "cipher": "AES",
9542 "key": 128,
9543 "iv": 16,
9544 "mode": "CBC",
9545 "type": "block"
9546 },
9547 "aes-192-cbc": {
9548 "cipher": "AES",
9549 "key": 192,
9550 "iv": 16,
9551 "mode": "CBC",
9552 "type": "block"
9553 },
9554 "aes-256-cbc": {
9555 "cipher": "AES",
9556 "key": 256,
9557 "iv": 16,
9558 "mode": "CBC",
9559 "type": "block"
9560 },
9561 "aes128": {
9562 "cipher": "AES",
9563 "key": 128,
9564 "iv": 16,
9565 "mode": "CBC",
9566 "type": "block"
9567 },
9568 "aes192": {
9569 "cipher": "AES",
9570 "key": 192,
9571 "iv": 16,
9572 "mode": "CBC",
9573 "type": "block"
9574 },
9575 "aes256": {
9576 "cipher": "AES",
9577 "key": 256,
9578 "iv": 16,
9579 "mode": "CBC",
9580 "type": "block"
9581 },
9582 "aes-128-cfb": {
9583 "cipher": "AES",
9584 "key": 128,
9585 "iv": 16,
9586 "mode": "CFB",
9587 "type": "stream"
9588 },
9589 "aes-192-cfb": {
9590 "cipher": "AES",
9591 "key": 192,
9592 "iv": 16,
9593 "mode": "CFB",
9594 "type": "stream"
9595 },
9596 "aes-256-cfb": {
9597 "cipher": "AES",
9598 "key": 256,
9599 "iv": 16,
9600 "mode": "CFB",
9601 "type": "stream"
9602 },
9603 "aes-128-cfb8": {
9604 "cipher": "AES",
9605 "key": 128,
9606 "iv": 16,
9607 "mode": "CFB8",
9608 "type": "stream"
9609 },
9610 "aes-192-cfb8": {
9611 "cipher": "AES",
9612 "key": 192,
9613 "iv": 16,
9614 "mode": "CFB8",
9615 "type": "stream"
9616 },
9617 "aes-256-cfb8": {
9618 "cipher": "AES",
9619 "key": 256,
9620 "iv": 16,
9621 "mode": "CFB8",
9622 "type": "stream"
9623 },
9624 "aes-128-cfb1": {
9625 "cipher": "AES",
9626 "key": 128,
9627 "iv": 16,
9628 "mode": "CFB1",
9629 "type": "stream"
9630 },
9631 "aes-192-cfb1": {
9632 "cipher": "AES",
9633 "key": 192,
9634 "iv": 16,
9635 "mode": "CFB1",
9636 "type": "stream"
9637 },
9638 "aes-256-cfb1": {
9639 "cipher": "AES",
9640 "key": 256,
9641 "iv": 16,
9642 "mode": "CFB1",
9643 "type": "stream"
9644 },
9645 "aes-128-ofb": {
9646 "cipher": "AES",
9647 "key": 128,
9648 "iv": 16,
9649 "mode": "OFB",
9650 "type": "stream"
9651 },
9652 "aes-192-ofb": {
9653 "cipher": "AES",
9654 "key": 192,
9655 "iv": 16,
9656 "mode": "OFB",
9657 "type": "stream"
9658 },
9659 "aes-256-ofb": {
9660 "cipher": "AES",
9661 "key": 256,
9662 "iv": 16,
9663 "mode": "OFB",
9664 "type": "stream"
9665 },
9666 "aes-128-ctr": {
9667 "cipher": "AES",
9668 "key": 128,
9669 "iv": 16,
9670 "mode": "CTR",
9671 "type": "stream"
9672 },
9673 "aes-192-ctr": {
9674 "cipher": "AES",
9675 "key": 192,
9676 "iv": 16,
9677 "mode": "CTR",
9678 "type": "stream"
9679 },
9680 "aes-256-ctr": {
9681 "cipher": "AES",
9682 "key": 256,
9683 "iv": 16,
9684 "mode": "CTR",
9685 "type": "stream"
9686 },
9687 "aes-128-gcm": {
9688 "cipher": "AES",
9689 "key": 128,
9690 "iv": 12,
9691 "mode": "GCM",
9692 "type": "auth"
9693 },
9694 "aes-192-gcm": {
9695 "cipher": "AES",
9696 "key": 192,
9697 "iv": 12,
9698 "mode": "GCM",
9699 "type": "auth"
9700 },
9701 "aes-256-gcm": {
9702 "cipher": "AES",
9703 "key": 256,
9704 "iv": 12,
9705 "mode": "GCM",
9706 "type": "auth"
9707 }
9708}
9709
9710},{}],39:[function(require,module,exports){
9711(function (Buffer){
9712var xor = require('buffer-xor')
9713
9714function getBlock (self) {
9715 self._prev = self._cipher.encryptBlock(self._prev)
9716 return self._prev
9717}
9718
9719exports.encrypt = function (self, chunk) {
9720 while (self._cache.length < chunk.length) {
9721 self._cache = Buffer.concat([self._cache, getBlock(self)])
9722 }
9723
9724 var pad = self._cache.slice(0, chunk.length)
9725 self._cache = self._cache.slice(chunk.length)
9726 return xor(chunk, pad)
9727}
9728
9729}).call(this,require("buffer").Buffer)
9730},{"buffer":53,"buffer-xor":52}],40:[function(require,module,exports){
9731var aes = require('./aes')
9732var Buffer = require('safe-buffer').Buffer
9733var Transform = require('cipher-base')
9734var inherits = require('inherits')
9735
9736function StreamCipher (mode, key, iv, decrypt) {
9737 Transform.call(this)
9738
9739 this._cipher = new aes.AES(key)
9740 this._prev = Buffer.from(iv)
9741 this._cache = Buffer.allocUnsafe(0)
9742 this._secCache = Buffer.allocUnsafe(0)
9743 this._decrypt = decrypt
9744 this._mode = mode
9745}
9746
9747inherits(StreamCipher, Transform)
9748
9749StreamCipher.prototype._update = function (chunk) {
9750 return this._mode.encrypt(this, chunk, this._decrypt)
9751}
9752
9753StreamCipher.prototype._final = function () {
9754 this._cipher.scrub()
9755}
9756
9757module.exports = StreamCipher
9758
9759},{"./aes":24,"cipher-base":54,"inherits":107,"safe-buffer":156}],41:[function(require,module,exports){
9760var ebtk = require('evp_bytestokey')
9761var aes = require('browserify-aes/browser')
9762var DES = require('browserify-des')
9763var desModes = require('browserify-des/modes')
9764var aesModes = require('browserify-aes/modes')
9765function createCipher (suite, password) {
9766 var keyLen, ivLen
9767 suite = suite.toLowerCase()
9768 if (aesModes[suite]) {
9769 keyLen = aesModes[suite].key
9770 ivLen = aesModes[suite].iv
9771 } else if (desModes[suite]) {
9772 keyLen = desModes[suite].key * 8
9773 ivLen = desModes[suite].iv
9774 } else {
9775 throw new TypeError('invalid suite type')
9776 }
9777 var keys = ebtk(password, false, keyLen, ivLen)
9778 return createCipheriv(suite, keys.key, keys.iv)
9779}
9780function createDecipher (suite, password) {
9781 var keyLen, ivLen
9782 suite = suite.toLowerCase()
9783 if (aesModes[suite]) {
9784 keyLen = aesModes[suite].key
9785 ivLen = aesModes[suite].iv
9786 } else if (desModes[suite]) {
9787 keyLen = desModes[suite].key * 8
9788 ivLen = desModes[suite].iv
9789 } else {
9790 throw new TypeError('invalid suite type')
9791 }
9792 var keys = ebtk(password, false, keyLen, ivLen)
9793 return createDecipheriv(suite, keys.key, keys.iv)
9794}
9795
9796function createCipheriv (suite, key, iv) {
9797 suite = suite.toLowerCase()
9798 if (aesModes[suite]) {
9799 return aes.createCipheriv(suite, key, iv)
9800 } else if (desModes[suite]) {
9801 return new DES({
9802 key: key,
9803 iv: iv,
9804 mode: suite
9805 })
9806 } else {
9807 throw new TypeError('invalid suite type')
9808 }
9809}
9810function createDecipheriv (suite, key, iv) {
9811 suite = suite.toLowerCase()
9812 if (aesModes[suite]) {
9813 return aes.createDecipheriv(suite, key, iv)
9814 } else if (desModes[suite]) {
9815 return new DES({
9816 key: key,
9817 iv: iv,
9818 mode: suite,
9819 decrypt: true
9820 })
9821 } else {
9822 throw new TypeError('invalid suite type')
9823 }
9824}
9825exports.createCipher = exports.Cipher = createCipher
9826exports.createCipheriv = exports.Cipheriv = createCipheriv
9827exports.createDecipher = exports.Decipher = createDecipher
9828exports.createDecipheriv = exports.Decipheriv = createDecipheriv
9829function getCiphers () {
9830 return Object.keys(desModes).concat(aes.getCiphers())
9831}
9832exports.listCiphers = exports.getCiphers = getCiphers
9833
9834},{"browserify-aes/browser":26,"browserify-aes/modes":37,"browserify-des":42,"browserify-des/modes":43,"evp_bytestokey":90}],42:[function(require,module,exports){
9835(function (Buffer){
9836var CipherBase = require('cipher-base')
9837var des = require('des.js')
9838var inherits = require('inherits')
9839
9840var modes = {
9841 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
9842 'des-ede3': des.EDE,
9843 'des-ede-cbc': des.CBC.instantiate(des.EDE),
9844 'des-ede': des.EDE,
9845 'des-cbc': des.CBC.instantiate(des.DES),
9846 'des-ecb': des.DES
9847}
9848modes.des = modes['des-cbc']
9849modes.des3 = modes['des-ede3-cbc']
9850module.exports = DES
9851inherits(DES, CipherBase)
9852function DES (opts) {
9853 CipherBase.call(this)
9854 var modeName = opts.mode.toLowerCase()
9855 var mode = modes[modeName]
9856 var type
9857 if (opts.decrypt) {
9858 type = 'decrypt'
9859 } else {
9860 type = 'encrypt'
9861 }
9862 var key = opts.key
9863 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
9864 key = Buffer.concat([key, key.slice(0, 8)])
9865 }
9866 var iv = opts.iv
9867 this._des = mode.create({
9868 key: key,
9869 iv: iv,
9870 type: type
9871 })
9872}
9873DES.prototype._update = function (data) {
9874 return new Buffer(this._des.update(data))
9875}
9876DES.prototype._final = function () {
9877 return new Buffer(this._des.final())
9878}
9879
9880}).call(this,require("buffer").Buffer)
9881},{"buffer":53,"cipher-base":54,"des.js":63,"inherits":107}],43:[function(require,module,exports){
9882exports['des-ecb'] = {
9883 key: 8,
9884 iv: 0
9885}
9886exports['des-cbc'] = exports.des = {
9887 key: 8,
9888 iv: 8
9889}
9890exports['des-ede3-cbc'] = exports.des3 = {
9891 key: 24,
9892 iv: 8
9893}
9894exports['des-ede3'] = {
9895 key: 24,
9896 iv: 0
9897}
9898exports['des-ede-cbc'] = {
9899 key: 16,
9900 iv: 8
9901}
9902exports['des-ede'] = {
9903 key: 16,
9904 iv: 0
9905}
9906
9907},{}],44:[function(require,module,exports){
9908(function (Buffer){
9909var bn = require('bn.js');
9910var randomBytes = require('randombytes');
9911module.exports = crt;
9912function blind(priv) {
9913 var r = getr(priv);
9914 var blinder = r.toRed(bn.mont(priv.modulus))
9915 .redPow(new bn(priv.publicExponent)).fromRed();
9916 return {
9917 blinder: blinder,
9918 unblinder:r.invm(priv.modulus)
9919 };
9920}
9921function crt(msg, priv) {
9922 var blinds = blind(priv);
9923 var len = priv.modulus.byteLength();
9924 var mod = bn.mont(priv.modulus);
9925 var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
9926 var c1 = blinded.toRed(bn.mont(priv.prime1));
9927 var c2 = blinded.toRed(bn.mont(priv.prime2));
9928 var qinv = priv.coefficient;
9929 var p = priv.prime1;
9930 var q = priv.prime2;
9931 var m1 = c1.redPow(priv.exponent1);
9932 var m2 = c2.redPow(priv.exponent2);
9933 m1 = m1.fromRed();
9934 m2 = m2.fromRed();
9935 var h = m1.isub(m2).imul(qinv).umod(p);
9936 h.imul(q);
9937 m2.iadd(h);
9938 return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
9939}
9940crt.getr = getr;
9941function getr(priv) {
9942 var len = priv.modulus.byteLength();
9943 var r = new bn(randomBytes(len));
9944 while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
9945 r = new bn(randomBytes(len));
9946 }
9947 return r;
9948}
9949
9950}).call(this,require("buffer").Buffer)
9951},{"bn.js":21,"buffer":53,"randombytes":140}],45:[function(require,module,exports){
9952module.exports = require('./browser/algorithms.json')
9953
9954},{"./browser/algorithms.json":46}],46:[function(require,module,exports){
9955module.exports={
9956 "sha224WithRSAEncryption": {
9957 "sign": "rsa",
9958 "hash": "sha224",
9959 "id": "302d300d06096086480165030402040500041c"
9960 },
9961 "RSA-SHA224": {
9962 "sign": "ecdsa/rsa",
9963 "hash": "sha224",
9964 "id": "302d300d06096086480165030402040500041c"
9965 },
9966 "sha256WithRSAEncryption": {
9967 "sign": "rsa",
9968 "hash": "sha256",
9969 "id": "3031300d060960864801650304020105000420"
9970 },
9971 "RSA-SHA256": {
9972 "sign": "ecdsa/rsa",
9973 "hash": "sha256",
9974 "id": "3031300d060960864801650304020105000420"
9975 },
9976 "sha384WithRSAEncryption": {
9977 "sign": "rsa",
9978 "hash": "sha384",
9979 "id": "3041300d060960864801650304020205000430"
9980 },
9981 "RSA-SHA384": {
9982 "sign": "ecdsa/rsa",
9983 "hash": "sha384",
9984 "id": "3041300d060960864801650304020205000430"
9985 },
9986 "sha512WithRSAEncryption": {
9987 "sign": "rsa",
9988 "hash": "sha512",
9989 "id": "3051300d060960864801650304020305000440"
9990 },
9991 "RSA-SHA512": {
9992 "sign": "ecdsa/rsa",
9993 "hash": "sha512",
9994 "id": "3051300d060960864801650304020305000440"
9995 },
9996 "RSA-SHA1": {
9997 "sign": "rsa",
9998 "hash": "sha1",
9999 "id": "3021300906052b0e03021a05000414"
10000 },
10001 "ecdsa-with-SHA1": {
10002 "sign": "ecdsa",
10003 "hash": "sha1",
10004 "id": ""
10005 },
10006 "sha256": {
10007 "sign": "ecdsa",
10008 "hash": "sha256",
10009 "id": ""
10010 },
10011 "sha224": {
10012 "sign": "ecdsa",
10013 "hash": "sha224",
10014 "id": ""
10015 },
10016 "sha384": {
10017 "sign": "ecdsa",
10018 "hash": "sha384",
10019 "id": ""
10020 },
10021 "sha512": {
10022 "sign": "ecdsa",
10023 "hash": "sha512",
10024 "id": ""
10025 },
10026 "DSA-SHA": {
10027 "sign": "dsa",
10028 "hash": "sha1",
10029 "id": ""
10030 },
10031 "DSA-SHA1": {
10032 "sign": "dsa",
10033 "hash": "sha1",
10034 "id": ""
10035 },
10036 "DSA": {
10037 "sign": "dsa",
10038 "hash": "sha1",
10039 "id": ""
10040 },
10041 "DSA-WITH-SHA224": {
10042 "sign": "dsa",
10043 "hash": "sha224",
10044 "id": ""
10045 },
10046 "DSA-SHA224": {
10047 "sign": "dsa",
10048 "hash": "sha224",
10049 "id": ""
10050 },
10051 "DSA-WITH-SHA256": {
10052 "sign": "dsa",
10053 "hash": "sha256",
10054 "id": ""
10055 },
10056 "DSA-SHA256": {
10057 "sign": "dsa",
10058 "hash": "sha256",
10059 "id": ""
10060 },
10061 "DSA-WITH-SHA384": {
10062 "sign": "dsa",
10063 "hash": "sha384",
10064 "id": ""
10065 },
10066 "DSA-SHA384": {
10067 "sign": "dsa",
10068 "hash": "sha384",
10069 "id": ""
10070 },
10071 "DSA-WITH-SHA512": {
10072 "sign": "dsa",
10073 "hash": "sha512",
10074 "id": ""
10075 },
10076 "DSA-SHA512": {
10077 "sign": "dsa",
10078 "hash": "sha512",
10079 "id": ""
10080 },
10081 "DSA-RIPEMD160": {
10082 "sign": "dsa",
10083 "hash": "rmd160",
10084 "id": ""
10085 },
10086 "ripemd160WithRSA": {
10087 "sign": "rsa",
10088 "hash": "rmd160",
10089 "id": "3021300906052b2403020105000414"
10090 },
10091 "RSA-RIPEMD160": {
10092 "sign": "rsa",
10093 "hash": "rmd160",
10094 "id": "3021300906052b2403020105000414"
10095 },
10096 "md5WithRSAEncryption": {
10097 "sign": "rsa",
10098 "hash": "md5",
10099 "id": "3020300c06082a864886f70d020505000410"
10100 },
10101 "RSA-MD5": {
10102 "sign": "rsa",
10103 "hash": "md5",
10104 "id": "3020300c06082a864886f70d020505000410"
10105 }
10106}
10107
10108},{}],47:[function(require,module,exports){
10109module.exports={
10110 "1.3.132.0.10": "secp256k1",
10111 "1.3.132.0.33": "p224",
10112 "1.2.840.10045.3.1.1": "p192",
10113 "1.2.840.10045.3.1.7": "p256",
10114 "1.3.132.0.34": "p384",
10115 "1.3.132.0.35": "p521"
10116}
10117
10118},{}],48:[function(require,module,exports){
10119(function (Buffer){
10120var createHash = require('create-hash')
10121var stream = require('stream')
10122var inherits = require('inherits')
10123var sign = require('./sign')
10124var verify = require('./verify')
10125
10126var algorithms = require('./algorithms.json')
10127Object.keys(algorithms).forEach(function (key) {
10128 algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
10129 algorithms[key.toLowerCase()] = algorithms[key]
10130})
10131
10132function Sign (algorithm) {
10133 stream.Writable.call(this)
10134
10135 var data = algorithms[algorithm]
10136 if (!data) throw new Error('Unknown message digest')
10137
10138 this._hashType = data.hash
10139 this._hash = createHash(data.hash)
10140 this._tag = data.id
10141 this._signType = data.sign
10142}
10143inherits(Sign, stream.Writable)
10144
10145Sign.prototype._write = function _write (data, _, done) {
10146 this._hash.update(data)
10147 done()
10148}
10149
10150Sign.prototype.update = function update (data, enc) {
10151 if (typeof data === 'string') data = new Buffer(data, enc)
10152
10153 this._hash.update(data)
10154 return this
10155}
10156
10157Sign.prototype.sign = function signMethod (key, enc) {
10158 this.end()
10159 var hash = this._hash.digest()
10160 var sig = sign(hash, key, this._hashType, this._signType, this._tag)
10161
10162 return enc ? sig.toString(enc) : sig
10163}
10164
10165function Verify (algorithm) {
10166 stream.Writable.call(this)
10167
10168 var data = algorithms[algorithm]
10169 if (!data) throw new Error('Unknown message digest')
10170
10171 this._hash = createHash(data.hash)
10172 this._tag = data.id
10173 this._signType = data.sign
10174}
10175inherits(Verify, stream.Writable)
10176
10177Verify.prototype._write = function _write (data, _, done) {
10178 this._hash.update(data)
10179 done()
10180}
10181
10182Verify.prototype.update = function update (data, enc) {
10183 if (typeof data === 'string') data = new Buffer(data, enc)
10184
10185 this._hash.update(data)
10186 return this
10187}
10188
10189Verify.prototype.verify = function verifyMethod (key, sig, enc) {
10190 if (typeof sig === 'string') sig = new Buffer(sig, enc)
10191
10192 this.end()
10193 var hash = this._hash.digest()
10194 return verify(sig, hash, key, this._signType, this._tag)
10195}
10196
10197function createSign (algorithm) {
10198 return new Sign(algorithm)
10199}
10200
10201function createVerify (algorithm) {
10202 return new Verify(algorithm)
10203}
10204
10205module.exports = {
10206 Sign: createSign,
10207 Verify: createVerify,
10208 createSign: createSign,
10209 createVerify: createVerify
10210}
10211
10212}).call(this,require("buffer").Buffer)
10213},{"./algorithms.json":46,"./sign":49,"./verify":50,"buffer":53,"create-hash":57,"inherits":107,"stream":172}],49:[function(require,module,exports){
10214(function (Buffer){
10215// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
10216var createHmac = require('create-hmac')
10217var crt = require('browserify-rsa')
10218var EC = require('elliptic').ec
10219var BN = require('bn.js')
10220var parseKeys = require('parse-asn1')
10221var curves = require('./curves.json')
10222
10223function sign (hash, key, hashType, signType, tag) {
10224 var priv = parseKeys(key)
10225 if (priv.curve) {
10226 // rsa keys can be interpreted as ecdsa ones in openssl
10227 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
10228 return ecSign(hash, priv)
10229 } else if (priv.type === 'dsa') {
10230 if (signType !== 'dsa') throw new Error('wrong private key type')
10231 return dsaSign(hash, priv, hashType)
10232 } else {
10233 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
10234 }
10235 hash = Buffer.concat([tag, hash])
10236 var len = priv.modulus.byteLength()
10237 var pad = [ 0, 1 ]
10238 while (hash.length + pad.length + 1 < len) pad.push(0xff)
10239 pad.push(0x00)
10240 var i = -1
10241 while (++i < hash.length) pad.push(hash[i])
10242
10243 var out = crt(pad, priv)
10244 return out
10245}
10246
10247function ecSign (hash, priv) {
10248 var curveId = curves[priv.curve.join('.')]
10249 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
10250
10251 var curve = new EC(curveId)
10252 var key = curve.keyFromPrivate(priv.privateKey)
10253 var out = key.sign(hash)
10254
10255 return new Buffer(out.toDER())
10256}
10257
10258function dsaSign (hash, priv, algo) {
10259 var x = priv.params.priv_key
10260 var p = priv.params.p
10261 var q = priv.params.q
10262 var g = priv.params.g
10263 var r = new BN(0)
10264 var k
10265 var H = bits2int(hash, q).mod(q)
10266 var s = false
10267 var kv = getKey(x, q, hash, algo)
10268 while (s === false) {
10269 k = makeKey(q, kv, algo)
10270 r = makeR(g, k, p, q)
10271 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
10272 if (s.cmpn(0) === 0) {
10273 s = false
10274 r = new BN(0)
10275 }
10276 }
10277 return toDER(r, s)
10278}
10279
10280function toDER (r, s) {
10281 r = r.toArray()
10282 s = s.toArray()
10283
10284 // Pad values
10285 if (r[0] & 0x80) r = [ 0 ].concat(r)
10286 if (s[0] & 0x80) s = [ 0 ].concat(s)
10287
10288 var total = r.length + s.length + 4
10289 var res = [ 0x30, total, 0x02, r.length ]
10290 res = res.concat(r, [ 0x02, s.length ], s)
10291 return new Buffer(res)
10292}
10293
10294function getKey (x, q, hash, algo) {
10295 x = new Buffer(x.toArray())
10296 if (x.length < q.byteLength()) {
10297 var zeros = new Buffer(q.byteLength() - x.length)
10298 zeros.fill(0)
10299 x = Buffer.concat([ zeros, x ])
10300 }
10301 var hlen = hash.length
10302 var hbits = bits2octets(hash, q)
10303 var v = new Buffer(hlen)
10304 v.fill(1)
10305 var k = new Buffer(hlen)
10306 k.fill(0)
10307 k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
10308 v = createHmac(algo, k).update(v).digest()
10309 k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
10310 v = createHmac(algo, k).update(v).digest()
10311 return { k: k, v: v }
10312}
10313
10314function bits2int (obits, q) {
10315 var bits = new BN(obits)
10316 var shift = (obits.length << 3) - q.bitLength()
10317 if (shift > 0) bits.ishrn(shift)
10318 return bits
10319}
10320
10321function bits2octets (bits, q) {
10322 bits = bits2int(bits, q)
10323 bits = bits.mod(q)
10324 var out = new Buffer(bits.toArray())
10325 if (out.length < q.byteLength()) {
10326 var zeros = new Buffer(q.byteLength() - out.length)
10327 zeros.fill(0)
10328 out = Buffer.concat([ zeros, out ])
10329 }
10330 return out
10331}
10332
10333function makeKey (q, kv, algo) {
10334 var t
10335 var k
10336
10337 do {
10338 t = new Buffer(0)
10339
10340 while (t.length * 8 < q.bitLength()) {
10341 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
10342 t = Buffer.concat([ t, kv.v ])
10343 }
10344
10345 k = bits2int(t, q)
10346 kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
10347 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
10348 } while (k.cmp(q) !== -1)
10349
10350 return k
10351}
10352
10353function makeR (g, k, p, q) {
10354 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
10355}
10356
10357module.exports = sign
10358module.exports.getKey = getKey
10359module.exports.makeKey = makeKey
10360
10361}).call(this,require("buffer").Buffer)
10362},{"./curves.json":47,"bn.js":21,"browserify-rsa":44,"buffer":53,"create-hmac":60,"elliptic":73,"parse-asn1":126}],50:[function(require,module,exports){
10363(function (Buffer){
10364// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
10365var BN = require('bn.js')
10366var EC = require('elliptic').ec
10367var parseKeys = require('parse-asn1')
10368var curves = require('./curves.json')
10369
10370function verify (sig, hash, key, signType, tag) {
10371 var pub = parseKeys(key)
10372 if (pub.type === 'ec') {
10373 // rsa keys can be interpreted as ecdsa ones in openssl
10374 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
10375 return ecVerify(sig, hash, pub)
10376 } else if (pub.type === 'dsa') {
10377 if (signType !== 'dsa') throw new Error('wrong public key type')
10378 return dsaVerify(sig, hash, pub)
10379 } else {
10380 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
10381 }
10382 hash = Buffer.concat([tag, hash])
10383 var len = pub.modulus.byteLength()
10384 var pad = [ 1 ]
10385 var padNum = 0
10386 while (hash.length + pad.length + 2 < len) {
10387 pad.push(0xff)
10388 padNum++
10389 }
10390 pad.push(0x00)
10391 var i = -1
10392 while (++i < hash.length) {
10393 pad.push(hash[i])
10394 }
10395 pad = new Buffer(pad)
10396 var red = BN.mont(pub.modulus)
10397 sig = new BN(sig).toRed(red)
10398
10399 sig = sig.redPow(new BN(pub.publicExponent))
10400 sig = new Buffer(sig.fromRed().toArray())
10401 var out = padNum < 8 ? 1 : 0
10402 len = Math.min(sig.length, pad.length)
10403 if (sig.length !== pad.length) out = 1
10404
10405 i = -1
10406 while (++i < len) out |= sig[i] ^ pad[i]
10407 return out === 0
10408}
10409
10410function ecVerify (sig, hash, pub) {
10411 var curveId = curves[pub.data.algorithm.curve.join('.')]
10412 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
10413
10414 var curve = new EC(curveId)
10415 var pubkey = pub.data.subjectPrivateKey.data
10416
10417 return curve.verify(hash, sig, pubkey)
10418}
10419
10420function dsaVerify (sig, hash, pub) {
10421 var p = pub.data.p
10422 var q = pub.data.q
10423 var g = pub.data.g
10424 var y = pub.data.pub_key
10425 var unpacked = parseKeys.signature.decode(sig, 'der')
10426 var s = unpacked.s
10427 var r = unpacked.r
10428 checkValue(s, q)
10429 checkValue(r, q)
10430 var montp = BN.mont(p)
10431 var w = s.invm(q)
10432 var v = g.toRed(montp)
10433 .redPow(new BN(hash).mul(w).mod(q))
10434 .fromRed()
10435 .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
10436 .mod(p)
10437 .mod(q)
10438 return v.cmp(r) === 0
10439}
10440
10441function checkValue (b, q) {
10442 if (b.cmpn(0) <= 0) throw new Error('invalid sig')
10443 if (b.cmp(q) >= q) throw new Error('invalid sig')
10444}
10445
10446module.exports = verify
10447
10448}).call(this,require("buffer").Buffer)
10449},{"./curves.json":47,"bn.js":21,"buffer":53,"elliptic":73,"parse-asn1":126}],51:[function(require,module,exports){
10450var basex = require('base-x')
10451var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
10452
10453module.exports = basex(ALPHABET)
10454
10455},{"base-x":17}],52:[function(require,module,exports){
10456(function (Buffer){
10457module.exports = function xor (a, b) {
10458 var length = Math.min(a.length, b.length)
10459 var buffer = new Buffer(length)
10460
10461 for (var i = 0; i < length; ++i) {
10462 buffer[i] = a[i] ^ b[i]
10463 }
10464
10465 return buffer
10466}
10467
10468}).call(this,require("buffer").Buffer)
10469},{"buffer":53}],53:[function(require,module,exports){
10470/*!
10471 * The buffer module from node.js, for the browser.
10472 *
10473 * @author Feross Aboukhadijeh <https://feross.org>
10474 * @license MIT
10475 */
10476/* eslint-disable no-proto */
10477
10478'use strict'
10479
10480var base64 = require('base64-js')
10481var ieee754 = require('ieee754')
10482
10483exports.Buffer = Buffer
10484exports.SlowBuffer = SlowBuffer
10485exports.INSPECT_MAX_BYTES = 50
10486
10487var K_MAX_LENGTH = 0x7fffffff
10488exports.kMaxLength = K_MAX_LENGTH
10489
10490/**
10491 * If `Buffer.TYPED_ARRAY_SUPPORT`:
10492 * === true Use Uint8Array implementation (fastest)
10493 * === false Print warning and recommend using `buffer` v4.x which has an Object
10494 * implementation (most compatible, even IE6)
10495 *
10496 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
10497 * Opera 11.6+, iOS 4.2+.
10498 *
10499 * We report that the browser does not support typed arrays if the are not subclassable
10500 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
10501 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
10502 * for __proto__ and has a buggy typed array implementation.
10503 */
10504Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
10505
10506if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
10507 typeof console.error === 'function') {
10508 console.error(
10509 'This browser lacks typed array (Uint8Array) support which is required by ' +
10510 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
10511 )
10512}
10513
10514function typedArraySupport () {
10515 // Can typed array instances can be augmented?
10516 try {
10517 var arr = new Uint8Array(1)
10518 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
10519 return arr.foo() === 42
10520 } catch (e) {
10521 return false
10522 }
10523}
10524
10525function createBuffer (length) {
10526 if (length > K_MAX_LENGTH) {
10527 throw new RangeError('Invalid typed array length')
10528 }
10529 // Return an augmented `Uint8Array` instance
10530 var buf = new Uint8Array(length)
10531 buf.__proto__ = Buffer.prototype
10532 return buf
10533}
10534
10535/**
10536 * The Buffer constructor returns instances of `Uint8Array` that have their
10537 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
10538 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
10539 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
10540 * returns a single octet.
10541 *
10542 * The `Uint8Array` prototype remains unmodified.
10543 */
10544
10545function Buffer (arg, encodingOrOffset, length) {
10546 // Common case.
10547 if (typeof arg === 'number') {
10548 if (typeof encodingOrOffset === 'string') {
10549 throw new Error(
10550 'If encoding is specified then the first argument must be a string'
10551 )
10552 }
10553 return allocUnsafe(arg)
10554 }
10555 return from(arg, encodingOrOffset, length)
10556}
10557
10558// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
10559if (typeof Symbol !== 'undefined' && Symbol.species &&
10560 Buffer[Symbol.species] === Buffer) {
10561 Object.defineProperty(Buffer, Symbol.species, {
10562 value: null,
10563 configurable: true,
10564 enumerable: false,
10565 writable: false
10566 })
10567}
10568
10569Buffer.poolSize = 8192 // not used by this implementation
10570
10571function from (value, encodingOrOffset, length) {
10572 if (typeof value === 'number') {
10573 throw new TypeError('"value" argument must not be a number')
10574 }
10575
10576 if (isArrayBuffer(value)) {
10577 return fromArrayBuffer(value, encodingOrOffset, length)
10578 }
10579
10580 if (typeof value === 'string') {
10581 return fromString(value, encodingOrOffset)
10582 }
10583
10584 return fromObject(value)
10585}
10586
10587/**
10588 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
10589 * if value is a number.
10590 * Buffer.from(str[, encoding])
10591 * Buffer.from(array)
10592 * Buffer.from(buffer)
10593 * Buffer.from(arrayBuffer[, byteOffset[, length]])
10594 **/
10595Buffer.from = function (value, encodingOrOffset, length) {
10596 return from(value, encodingOrOffset, length)
10597}
10598
10599// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
10600// https://github.com/feross/buffer/pull/148
10601Buffer.prototype.__proto__ = Uint8Array.prototype
10602Buffer.__proto__ = Uint8Array
10603
10604function assertSize (size) {
10605 if (typeof size !== 'number') {
10606 throw new TypeError('"size" argument must be a number')
10607 } else if (size < 0) {
10608 throw new RangeError('"size" argument must not be negative')
10609 }
10610}
10611
10612function alloc (size, fill, encoding) {
10613 assertSize(size)
10614 if (size <= 0) {
10615 return createBuffer(size)
10616 }
10617 if (fill !== undefined) {
10618 // Only pay attention to encoding if it's a string. This
10619 // prevents accidentally sending in a number that would
10620 // be interpretted as a start offset.
10621 return typeof encoding === 'string'
10622 ? createBuffer(size).fill(fill, encoding)
10623 : createBuffer(size).fill(fill)
10624 }
10625 return createBuffer(size)
10626}
10627
10628/**
10629 * Creates a new filled Buffer instance.
10630 * alloc(size[, fill[, encoding]])
10631 **/
10632Buffer.alloc = function (size, fill, encoding) {
10633 return alloc(size, fill, encoding)
10634}
10635
10636function allocUnsafe (size) {
10637 assertSize(size)
10638 return createBuffer(size < 0 ? 0 : checked(size) | 0)
10639}
10640
10641/**
10642 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
10643 * */
10644Buffer.allocUnsafe = function (size) {
10645 return allocUnsafe(size)
10646}
10647/**
10648 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
10649 */
10650Buffer.allocUnsafeSlow = function (size) {
10651 return allocUnsafe(size)
10652}
10653
10654function fromString (string, encoding) {
10655 if (typeof encoding !== 'string' || encoding === '') {
10656 encoding = 'utf8'
10657 }
10658
10659 if (!Buffer.isEncoding(encoding)) {
10660 throw new TypeError('"encoding" must be a valid string encoding')
10661 }
10662
10663 var length = byteLength(string, encoding) | 0
10664 var buf = createBuffer(length)
10665
10666 var actual = buf.write(string, encoding)
10667
10668 if (actual !== length) {
10669 // Writing a hex string, for example, that contains invalid characters will
10670 // cause everything after the first invalid character to be ignored. (e.g.
10671 // 'abxxcd' will be treated as 'ab')
10672 buf = buf.slice(0, actual)
10673 }
10674
10675 return buf
10676}
10677
10678function fromArrayLike (array) {
10679 var length = array.length < 0 ? 0 : checked(array.length) | 0
10680 var buf = createBuffer(length)
10681 for (var i = 0; i < length; i += 1) {
10682 buf[i] = array[i] & 255
10683 }
10684 return buf
10685}
10686
10687function fromArrayBuffer (array, byteOffset, length) {
10688 if (byteOffset < 0 || array.byteLength < byteOffset) {
10689 throw new RangeError('\'offset\' is out of bounds')
10690 }
10691
10692 if (array.byteLength < byteOffset + (length || 0)) {
10693 throw new RangeError('\'length\' is out of bounds')
10694 }
10695
10696 var buf
10697 if (byteOffset === undefined && length === undefined) {
10698 buf = new Uint8Array(array)
10699 } else if (length === undefined) {
10700 buf = new Uint8Array(array, byteOffset)
10701 } else {
10702 buf = new Uint8Array(array, byteOffset, length)
10703 }
10704
10705 // Return an augmented `Uint8Array` instance
10706 buf.__proto__ = Buffer.prototype
10707 return buf
10708}
10709
10710function fromObject (obj) {
10711 if (Buffer.isBuffer(obj)) {
10712 var len = checked(obj.length) | 0
10713 var buf = createBuffer(len)
10714
10715 if (buf.length === 0) {
10716 return buf
10717 }
10718
10719 obj.copy(buf, 0, 0, len)
10720 return buf
10721 }
10722
10723 if (obj) {
10724 if (isArrayBufferView(obj) || 'length' in obj) {
10725 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
10726 return createBuffer(0)
10727 }
10728 return fromArrayLike(obj)
10729 }
10730
10731 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
10732 return fromArrayLike(obj.data)
10733 }
10734 }
10735
10736 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
10737}
10738
10739function checked (length) {
10740 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
10741 // length is NaN (which is otherwise coerced to zero.)
10742 if (length >= K_MAX_LENGTH) {
10743 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
10744 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
10745 }
10746 return length | 0
10747}
10748
10749function SlowBuffer (length) {
10750 if (+length != length) { // eslint-disable-line eqeqeq
10751 length = 0
10752 }
10753 return Buffer.alloc(+length)
10754}
10755
10756Buffer.isBuffer = function isBuffer (b) {
10757 return b != null && b._isBuffer === true
10758}
10759
10760Buffer.compare = function compare (a, b) {
10761 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
10762 throw new TypeError('Arguments must be Buffers')
10763 }
10764
10765 if (a === b) return 0
10766
10767 var x = a.length
10768 var y = b.length
10769
10770 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
10771 if (a[i] !== b[i]) {
10772 x = a[i]
10773 y = b[i]
10774 break
10775 }
10776 }
10777
10778 if (x < y) return -1
10779 if (y < x) return 1
10780 return 0
10781}
10782
10783Buffer.isEncoding = function isEncoding (encoding) {
10784 switch (String(encoding).toLowerCase()) {
10785 case 'hex':
10786 case 'utf8':
10787 case 'utf-8':
10788 case 'ascii':
10789 case 'latin1':
10790 case 'binary':
10791 case 'base64':
10792 case 'ucs2':
10793 case 'ucs-2':
10794 case 'utf16le':
10795 case 'utf-16le':
10796 return true
10797 default:
10798 return false
10799 }
10800}
10801
10802Buffer.concat = function concat (list, length) {
10803 if (!Array.isArray(list)) {
10804 throw new TypeError('"list" argument must be an Array of Buffers')
10805 }
10806
10807 if (list.length === 0) {
10808 return Buffer.alloc(0)
10809 }
10810
10811 var i
10812 if (length === undefined) {
10813 length = 0
10814 for (i = 0; i < list.length; ++i) {
10815 length += list[i].length
10816 }
10817 }
10818
10819 var buffer = Buffer.allocUnsafe(length)
10820 var pos = 0
10821 for (i = 0; i < list.length; ++i) {
10822 var buf = list[i]
10823 if (!Buffer.isBuffer(buf)) {
10824 throw new TypeError('"list" argument must be an Array of Buffers')
10825 }
10826 buf.copy(buffer, pos)
10827 pos += buf.length
10828 }
10829 return buffer
10830}
10831
10832function byteLength (string, encoding) {
10833 if (Buffer.isBuffer(string)) {
10834 return string.length
10835 }
10836 if (isArrayBufferView(string) || isArrayBuffer(string)) {
10837 return string.byteLength
10838 }
10839 if (typeof string !== 'string') {
10840 string = '' + string
10841 }
10842
10843 var len = string.length
10844 if (len === 0) return 0
10845
10846 // Use a for loop to avoid recursion
10847 var loweredCase = false
10848 for (;;) {
10849 switch (encoding) {
10850 case 'ascii':
10851 case 'latin1':
10852 case 'binary':
10853 return len
10854 case 'utf8':
10855 case 'utf-8':
10856 case undefined:
10857 return utf8ToBytes(string).length
10858 case 'ucs2':
10859 case 'ucs-2':
10860 case 'utf16le':
10861 case 'utf-16le':
10862 return len * 2
10863 case 'hex':
10864 return len >>> 1
10865 case 'base64':
10866 return base64ToBytes(string).length
10867 default:
10868 if (loweredCase) return utf8ToBytes(string).length // assume utf8
10869 encoding = ('' + encoding).toLowerCase()
10870 loweredCase = true
10871 }
10872 }
10873}
10874Buffer.byteLength = byteLength
10875
10876function slowToString (encoding, start, end) {
10877 var loweredCase = false
10878
10879 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
10880 // property of a typed array.
10881
10882 // This behaves neither like String nor Uint8Array in that we set start/end
10883 // to their upper/lower bounds if the value passed is out of range.
10884 // undefined is handled specially as per ECMA-262 6th Edition,
10885 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
10886 if (start === undefined || start < 0) {
10887 start = 0
10888 }
10889 // Return early if start > this.length. Done here to prevent potential uint32
10890 // coercion fail below.
10891 if (start > this.length) {
10892 return ''
10893 }
10894
10895 if (end === undefined || end > this.length) {
10896 end = this.length
10897 }
10898
10899 if (end <= 0) {
10900 return ''
10901 }
10902
10903 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
10904 end >>>= 0
10905 start >>>= 0
10906
10907 if (end <= start) {
10908 return ''
10909 }
10910
10911 if (!encoding) encoding = 'utf8'
10912
10913 while (true) {
10914 switch (encoding) {
10915 case 'hex':
10916 return hexSlice(this, start, end)
10917
10918 case 'utf8':
10919 case 'utf-8':
10920 return utf8Slice(this, start, end)
10921
10922 case 'ascii':
10923 return asciiSlice(this, start, end)
10924
10925 case 'latin1':
10926 case 'binary':
10927 return latin1Slice(this, start, end)
10928
10929 case 'base64':
10930 return base64Slice(this, start, end)
10931
10932 case 'ucs2':
10933 case 'ucs-2':
10934 case 'utf16le':
10935 case 'utf-16le':
10936 return utf16leSlice(this, start, end)
10937
10938 default:
10939 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
10940 encoding = (encoding + '').toLowerCase()
10941 loweredCase = true
10942 }
10943 }
10944}
10945
10946// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
10947// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
10948// reliably in a browserify context because there could be multiple different
10949// copies of the 'buffer' package in use. This method works even for Buffer
10950// instances that were created from another copy of the `buffer` package.
10951// See: https://github.com/feross/buffer/issues/154
10952Buffer.prototype._isBuffer = true
10953
10954function swap (b, n, m) {
10955 var i = b[n]
10956 b[n] = b[m]
10957 b[m] = i
10958}
10959
10960Buffer.prototype.swap16 = function swap16 () {
10961 var len = this.length
10962 if (len % 2 !== 0) {
10963 throw new RangeError('Buffer size must be a multiple of 16-bits')
10964 }
10965 for (var i = 0; i < len; i += 2) {
10966 swap(this, i, i + 1)
10967 }
10968 return this
10969}
10970
10971Buffer.prototype.swap32 = function swap32 () {
10972 var len = this.length
10973 if (len % 4 !== 0) {
10974 throw new RangeError('Buffer size must be a multiple of 32-bits')
10975 }
10976 for (var i = 0; i < len; i += 4) {
10977 swap(this, i, i + 3)
10978 swap(this, i + 1, i + 2)
10979 }
10980 return this
10981}
10982
10983Buffer.prototype.swap64 = function swap64 () {
10984 var len = this.length
10985 if (len % 8 !== 0) {
10986 throw new RangeError('Buffer size must be a multiple of 64-bits')
10987 }
10988 for (var i = 0; i < len; i += 8) {
10989 swap(this, i, i + 7)
10990 swap(this, i + 1, i + 6)
10991 swap(this, i + 2, i + 5)
10992 swap(this, i + 3, i + 4)
10993 }
10994 return this
10995}
10996
10997Buffer.prototype.toString = function toString () {
10998 var length = this.length
10999 if (length === 0) return ''
11000 if (arguments.length === 0) return utf8Slice(this, 0, length)
11001 return slowToString.apply(this, arguments)
11002}
11003
11004Buffer.prototype.equals = function equals (b) {
11005 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
11006 if (this === b) return true
11007 return Buffer.compare(this, b) === 0
11008}
11009
11010Buffer.prototype.inspect = function inspect () {
11011 var str = ''
11012 var max = exports.INSPECT_MAX_BYTES
11013 if (this.length > 0) {
11014 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
11015 if (this.length > max) str += ' ... '
11016 }
11017 return '<Buffer ' + str + '>'
11018}
11019
11020Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
11021 if (!Buffer.isBuffer(target)) {
11022 throw new TypeError('Argument must be a Buffer')
11023 }
11024
11025 if (start === undefined) {
11026 start = 0
11027 }
11028 if (end === undefined) {
11029 end = target ? target.length : 0
11030 }
11031 if (thisStart === undefined) {
11032 thisStart = 0
11033 }
11034 if (thisEnd === undefined) {
11035 thisEnd = this.length
11036 }
11037
11038 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
11039 throw new RangeError('out of range index')
11040 }
11041
11042 if (thisStart >= thisEnd && start >= end) {
11043 return 0
11044 }
11045 if (thisStart >= thisEnd) {
11046 return -1
11047 }
11048 if (start >= end) {
11049 return 1
11050 }
11051
11052 start >>>= 0
11053 end >>>= 0
11054 thisStart >>>= 0
11055 thisEnd >>>= 0
11056
11057 if (this === target) return 0
11058
11059 var x = thisEnd - thisStart
11060 var y = end - start
11061 var len = Math.min(x, y)
11062
11063 var thisCopy = this.slice(thisStart, thisEnd)
11064 var targetCopy = target.slice(start, end)
11065
11066 for (var i = 0; i < len; ++i) {
11067 if (thisCopy[i] !== targetCopy[i]) {
11068 x = thisCopy[i]
11069 y = targetCopy[i]
11070 break
11071 }
11072 }
11073
11074 if (x < y) return -1
11075 if (y < x) return 1
11076 return 0
11077}
11078
11079// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
11080// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
11081//
11082// Arguments:
11083// - buffer - a Buffer to search
11084// - val - a string, Buffer, or number
11085// - byteOffset - an index into `buffer`; will be clamped to an int32
11086// - encoding - an optional encoding, relevant is val is a string
11087// - dir - true for indexOf, false for lastIndexOf
11088function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
11089 // Empty buffer means no match
11090 if (buffer.length === 0) return -1
11091
11092 // Normalize byteOffset
11093 if (typeof byteOffset === 'string') {
11094 encoding = byteOffset
11095 byteOffset = 0
11096 } else if (byteOffset > 0x7fffffff) {
11097 byteOffset = 0x7fffffff
11098 } else if (byteOffset < -0x80000000) {
11099 byteOffset = -0x80000000
11100 }
11101 byteOffset = +byteOffset // Coerce to Number.
11102 if (numberIsNaN(byteOffset)) {
11103 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
11104 byteOffset = dir ? 0 : (buffer.length - 1)
11105 }
11106
11107 // Normalize byteOffset: negative offsets start from the end of the buffer
11108 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
11109 if (byteOffset >= buffer.length) {
11110 if (dir) return -1
11111 else byteOffset = buffer.length - 1
11112 } else if (byteOffset < 0) {
11113 if (dir) byteOffset = 0
11114 else return -1
11115 }
11116
11117 // Normalize val
11118 if (typeof val === 'string') {
11119 val = Buffer.from(val, encoding)
11120 }
11121
11122 // Finally, search either indexOf (if dir is true) or lastIndexOf
11123 if (Buffer.isBuffer(val)) {
11124 // Special case: looking for empty string/buffer always fails
11125 if (val.length === 0) {
11126 return -1
11127 }
11128 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
11129 } else if (typeof val === 'number') {
11130 val = val & 0xFF // Search for a byte value [0-255]
11131 if (typeof Uint8Array.prototype.indexOf === 'function') {
11132 if (dir) {
11133 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
11134 } else {
11135 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
11136 }
11137 }
11138 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
11139 }
11140
11141 throw new TypeError('val must be string, number or Buffer')
11142}
11143
11144function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
11145 var indexSize = 1
11146 var arrLength = arr.length
11147 var valLength = val.length
11148
11149 if (encoding !== undefined) {
11150 encoding = String(encoding).toLowerCase()
11151 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
11152 encoding === 'utf16le' || encoding === 'utf-16le') {
11153 if (arr.length < 2 || val.length < 2) {
11154 return -1
11155 }
11156 indexSize = 2
11157 arrLength /= 2
11158 valLength /= 2
11159 byteOffset /= 2
11160 }
11161 }
11162
11163 function read (buf, i) {
11164 if (indexSize === 1) {
11165 return buf[i]
11166 } else {
11167 return buf.readUInt16BE(i * indexSize)
11168 }
11169 }
11170
11171 var i
11172 if (dir) {
11173 var foundIndex = -1
11174 for (i = byteOffset; i < arrLength; i++) {
11175 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
11176 if (foundIndex === -1) foundIndex = i
11177 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
11178 } else {
11179 if (foundIndex !== -1) i -= i - foundIndex
11180 foundIndex = -1
11181 }
11182 }
11183 } else {
11184 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
11185 for (i = byteOffset; i >= 0; i--) {
11186 var found = true
11187 for (var j = 0; j < valLength; j++) {
11188 if (read(arr, i + j) !== read(val, j)) {
11189 found = false
11190 break
11191 }
11192 }
11193 if (found) return i
11194 }
11195 }
11196
11197 return -1
11198}
11199
11200Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
11201 return this.indexOf(val, byteOffset, encoding) !== -1
11202}
11203
11204Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
11205 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
11206}
11207
11208Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
11209 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
11210}
11211
11212function hexWrite (buf, string, offset, length) {
11213 offset = Number(offset) || 0
11214 var remaining = buf.length - offset
11215 if (!length) {
11216 length = remaining
11217 } else {
11218 length = Number(length)
11219 if (length > remaining) {
11220 length = remaining
11221 }
11222 }
11223
11224 // must be an even number of digits
11225 var strLen = string.length
11226 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
11227
11228 if (length > strLen / 2) {
11229 length = strLen / 2
11230 }
11231 for (var i = 0; i < length; ++i) {
11232 var parsed = parseInt(string.substr(i * 2, 2), 16)
11233 if (numberIsNaN(parsed)) return i
11234 buf[offset + i] = parsed
11235 }
11236 return i
11237}
11238
11239function utf8Write (buf, string, offset, length) {
11240 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
11241}
11242
11243function asciiWrite (buf, string, offset, length) {
11244 return blitBuffer(asciiToBytes(string), buf, offset, length)
11245}
11246
11247function latin1Write (buf, string, offset, length) {
11248 return asciiWrite(buf, string, offset, length)
11249}
11250
11251function base64Write (buf, string, offset, length) {
11252 return blitBuffer(base64ToBytes(string), buf, offset, length)
11253}
11254
11255function ucs2Write (buf, string, offset, length) {
11256 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
11257}
11258
11259Buffer.prototype.write = function write (string, offset, length, encoding) {
11260 // Buffer#write(string)
11261 if (offset === undefined) {
11262 encoding = 'utf8'
11263 length = this.length
11264 offset = 0
11265 // Buffer#write(string, encoding)
11266 } else if (length === undefined && typeof offset === 'string') {
11267 encoding = offset
11268 length = this.length
11269 offset = 0
11270 // Buffer#write(string, offset[, length][, encoding])
11271 } else if (isFinite(offset)) {
11272 offset = offset >>> 0
11273 if (isFinite(length)) {
11274 length = length >>> 0
11275 if (encoding === undefined) encoding = 'utf8'
11276 } else {
11277 encoding = length
11278 length = undefined
11279 }
11280 } else {
11281 throw new Error(
11282 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
11283 )
11284 }
11285
11286 var remaining = this.length - offset
11287 if (length === undefined || length > remaining) length = remaining
11288
11289 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
11290 throw new RangeError('Attempt to write outside buffer bounds')
11291 }
11292
11293 if (!encoding) encoding = 'utf8'
11294
11295 var loweredCase = false
11296 for (;;) {
11297 switch (encoding) {
11298 case 'hex':
11299 return hexWrite(this, string, offset, length)
11300
11301 case 'utf8':
11302 case 'utf-8':
11303 return utf8Write(this, string, offset, length)
11304
11305 case 'ascii':
11306 return asciiWrite(this, string, offset, length)
11307
11308 case 'latin1':
11309 case 'binary':
11310 return latin1Write(this, string, offset, length)
11311
11312 case 'base64':
11313 // Warning: maxLength not taken into account in base64Write
11314 return base64Write(this, string, offset, length)
11315
11316 case 'ucs2':
11317 case 'ucs-2':
11318 case 'utf16le':
11319 case 'utf-16le':
11320 return ucs2Write(this, string, offset, length)
11321
11322 default:
11323 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
11324 encoding = ('' + encoding).toLowerCase()
11325 loweredCase = true
11326 }
11327 }
11328}
11329
11330Buffer.prototype.toJSON = function toJSON () {
11331 return {
11332 type: 'Buffer',
11333 data: Array.prototype.slice.call(this._arr || this, 0)
11334 }
11335}
11336
11337function base64Slice (buf, start, end) {
11338 if (start === 0 && end === buf.length) {
11339 return base64.fromByteArray(buf)
11340 } else {
11341 return base64.fromByteArray(buf.slice(start, end))
11342 }
11343}
11344
11345function utf8Slice (buf, start, end) {
11346 end = Math.min(buf.length, end)
11347 var res = []
11348
11349 var i = start
11350 while (i < end) {
11351 var firstByte = buf[i]
11352 var codePoint = null
11353 var bytesPerSequence = (firstByte > 0xEF) ? 4
11354 : (firstByte > 0xDF) ? 3
11355 : (firstByte > 0xBF) ? 2
11356 : 1
11357
11358 if (i + bytesPerSequence <= end) {
11359 var secondByte, thirdByte, fourthByte, tempCodePoint
11360
11361 switch (bytesPerSequence) {
11362 case 1:
11363 if (firstByte < 0x80) {
11364 codePoint = firstByte
11365 }
11366 break
11367 case 2:
11368 secondByte = buf[i + 1]
11369 if ((secondByte & 0xC0) === 0x80) {
11370 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
11371 if (tempCodePoint > 0x7F) {
11372 codePoint = tempCodePoint
11373 }
11374 }
11375 break
11376 case 3:
11377 secondByte = buf[i + 1]
11378 thirdByte = buf[i + 2]
11379 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
11380 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
11381 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
11382 codePoint = tempCodePoint
11383 }
11384 }
11385 break
11386 case 4:
11387 secondByte = buf[i + 1]
11388 thirdByte = buf[i + 2]
11389 fourthByte = buf[i + 3]
11390 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
11391 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
11392 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
11393 codePoint = tempCodePoint
11394 }
11395 }
11396 }
11397 }
11398
11399 if (codePoint === null) {
11400 // we did not generate a valid codePoint so insert a
11401 // replacement char (U+FFFD) and advance only 1 byte
11402 codePoint = 0xFFFD
11403 bytesPerSequence = 1
11404 } else if (codePoint > 0xFFFF) {
11405 // encode to utf16 (surrogate pair dance)
11406 codePoint -= 0x10000
11407 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
11408 codePoint = 0xDC00 | codePoint & 0x3FF
11409 }
11410
11411 res.push(codePoint)
11412 i += bytesPerSequence
11413 }
11414
11415 return decodeCodePointsArray(res)
11416}
11417
11418// Based on http://stackoverflow.com/a/22747272/680742, the browser with
11419// the lowest limit is Chrome, with 0x10000 args.
11420// We go 1 magnitude less, for safety
11421var MAX_ARGUMENTS_LENGTH = 0x1000
11422
11423function decodeCodePointsArray (codePoints) {
11424 var len = codePoints.length
11425 if (len <= MAX_ARGUMENTS_LENGTH) {
11426 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
11427 }
11428
11429 // Decode in chunks to avoid "call stack size exceeded".
11430 var res = ''
11431 var i = 0
11432 while (i < len) {
11433 res += String.fromCharCode.apply(
11434 String,
11435 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
11436 )
11437 }
11438 return res
11439}
11440
11441function asciiSlice (buf, start, end) {
11442 var ret = ''
11443 end = Math.min(buf.length, end)
11444
11445 for (var i = start; i < end; ++i) {
11446 ret += String.fromCharCode(buf[i] & 0x7F)
11447 }
11448 return ret
11449}
11450
11451function latin1Slice (buf, start, end) {
11452 var ret = ''
11453 end = Math.min(buf.length, end)
11454
11455 for (var i = start; i < end; ++i) {
11456 ret += String.fromCharCode(buf[i])
11457 }
11458 return ret
11459}
11460
11461function hexSlice (buf, start, end) {
11462 var len = buf.length
11463
11464 if (!start || start < 0) start = 0
11465 if (!end || end < 0 || end > len) end = len
11466
11467 var out = ''
11468 for (var i = start; i < end; ++i) {
11469 out += toHex(buf[i])
11470 }
11471 return out
11472}
11473
11474function utf16leSlice (buf, start, end) {
11475 var bytes = buf.slice(start, end)
11476 var res = ''
11477 for (var i = 0; i < bytes.length; i += 2) {
11478 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
11479 }
11480 return res
11481}
11482
11483Buffer.prototype.slice = function slice (start, end) {
11484 var len = this.length
11485 start = ~~start
11486 end = end === undefined ? len : ~~end
11487
11488 if (start < 0) {
11489 start += len
11490 if (start < 0) start = 0
11491 } else if (start > len) {
11492 start = len
11493 }
11494
11495 if (end < 0) {
11496 end += len
11497 if (end < 0) end = 0
11498 } else if (end > len) {
11499 end = len
11500 }
11501
11502 if (end < start) end = start
11503
11504 var newBuf = this.subarray(start, end)
11505 // Return an augmented `Uint8Array` instance
11506 newBuf.__proto__ = Buffer.prototype
11507 return newBuf
11508}
11509
11510/*
11511 * Need to make sure that buffer isn't trying to write out of bounds.
11512 */
11513function checkOffset (offset, ext, length) {
11514 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
11515 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
11516}
11517
11518Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
11519 offset = offset >>> 0
11520 byteLength = byteLength >>> 0
11521 if (!noAssert) checkOffset(offset, byteLength, this.length)
11522
11523 var val = this[offset]
11524 var mul = 1
11525 var i = 0
11526 while (++i < byteLength && (mul *= 0x100)) {
11527 val += this[offset + i] * mul
11528 }
11529
11530 return val
11531}
11532
11533Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
11534 offset = offset >>> 0
11535 byteLength = byteLength >>> 0
11536 if (!noAssert) {
11537 checkOffset(offset, byteLength, this.length)
11538 }
11539
11540 var val = this[offset + --byteLength]
11541 var mul = 1
11542 while (byteLength > 0 && (mul *= 0x100)) {
11543 val += this[offset + --byteLength] * mul
11544 }
11545
11546 return val
11547}
11548
11549Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
11550 offset = offset >>> 0
11551 if (!noAssert) checkOffset(offset, 1, this.length)
11552 return this[offset]
11553}
11554
11555Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
11556 offset = offset >>> 0
11557 if (!noAssert) checkOffset(offset, 2, this.length)
11558 return this[offset] | (this[offset + 1] << 8)
11559}
11560
11561Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
11562 offset = offset >>> 0
11563 if (!noAssert) checkOffset(offset, 2, this.length)
11564 return (this[offset] << 8) | this[offset + 1]
11565}
11566
11567Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
11568 offset = offset >>> 0
11569 if (!noAssert) checkOffset(offset, 4, this.length)
11570
11571 return ((this[offset]) |
11572 (this[offset + 1] << 8) |
11573 (this[offset + 2] << 16)) +
11574 (this[offset + 3] * 0x1000000)
11575}
11576
11577Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
11578 offset = offset >>> 0
11579 if (!noAssert) checkOffset(offset, 4, this.length)
11580
11581 return (this[offset] * 0x1000000) +
11582 ((this[offset + 1] << 16) |
11583 (this[offset + 2] << 8) |
11584 this[offset + 3])
11585}
11586
11587Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
11588 offset = offset >>> 0
11589 byteLength = byteLength >>> 0
11590 if (!noAssert) checkOffset(offset, byteLength, this.length)
11591
11592 var val = this[offset]
11593 var mul = 1
11594 var i = 0
11595 while (++i < byteLength && (mul *= 0x100)) {
11596 val += this[offset + i] * mul
11597 }
11598 mul *= 0x80
11599
11600 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
11601
11602 return val
11603}
11604
11605Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
11606 offset = offset >>> 0
11607 byteLength = byteLength >>> 0
11608 if (!noAssert) checkOffset(offset, byteLength, this.length)
11609
11610 var i = byteLength
11611 var mul = 1
11612 var val = this[offset + --i]
11613 while (i > 0 && (mul *= 0x100)) {
11614 val += this[offset + --i] * mul
11615 }
11616 mul *= 0x80
11617
11618 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
11619
11620 return val
11621}
11622
11623Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
11624 offset = offset >>> 0
11625 if (!noAssert) checkOffset(offset, 1, this.length)
11626 if (!(this[offset] & 0x80)) return (this[offset])
11627 return ((0xff - this[offset] + 1) * -1)
11628}
11629
11630Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
11631 offset = offset >>> 0
11632 if (!noAssert) checkOffset(offset, 2, this.length)
11633 var val = this[offset] | (this[offset + 1] << 8)
11634 return (val & 0x8000) ? val | 0xFFFF0000 : val
11635}
11636
11637Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
11638 offset = offset >>> 0
11639 if (!noAssert) checkOffset(offset, 2, this.length)
11640 var val = this[offset + 1] | (this[offset] << 8)
11641 return (val & 0x8000) ? val | 0xFFFF0000 : val
11642}
11643
11644Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
11645 offset = offset >>> 0
11646 if (!noAssert) checkOffset(offset, 4, this.length)
11647
11648 return (this[offset]) |
11649 (this[offset + 1] << 8) |
11650 (this[offset + 2] << 16) |
11651 (this[offset + 3] << 24)
11652}
11653
11654Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
11655 offset = offset >>> 0
11656 if (!noAssert) checkOffset(offset, 4, this.length)
11657
11658 return (this[offset] << 24) |
11659 (this[offset + 1] << 16) |
11660 (this[offset + 2] << 8) |
11661 (this[offset + 3])
11662}
11663
11664Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
11665 offset = offset >>> 0
11666 if (!noAssert) checkOffset(offset, 4, this.length)
11667 return ieee754.read(this, offset, true, 23, 4)
11668}
11669
11670Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
11671 offset = offset >>> 0
11672 if (!noAssert) checkOffset(offset, 4, this.length)
11673 return ieee754.read(this, offset, false, 23, 4)
11674}
11675
11676Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
11677 offset = offset >>> 0
11678 if (!noAssert) checkOffset(offset, 8, this.length)
11679 return ieee754.read(this, offset, true, 52, 8)
11680}
11681
11682Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
11683 offset = offset >>> 0
11684 if (!noAssert) checkOffset(offset, 8, this.length)
11685 return ieee754.read(this, offset, false, 52, 8)
11686}
11687
11688function checkInt (buf, value, offset, ext, max, min) {
11689 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
11690 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
11691 if (offset + ext > buf.length) throw new RangeError('Index out of range')
11692}
11693
11694Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
11695 value = +value
11696 offset = offset >>> 0
11697 byteLength = byteLength >>> 0
11698 if (!noAssert) {
11699 var maxBytes = Math.pow(2, 8 * byteLength) - 1
11700 checkInt(this, value, offset, byteLength, maxBytes, 0)
11701 }
11702
11703 var mul = 1
11704 var i = 0
11705 this[offset] = value & 0xFF
11706 while (++i < byteLength && (mul *= 0x100)) {
11707 this[offset + i] = (value / mul) & 0xFF
11708 }
11709
11710 return offset + byteLength
11711}
11712
11713Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
11714 value = +value
11715 offset = offset >>> 0
11716 byteLength = byteLength >>> 0
11717 if (!noAssert) {
11718 var maxBytes = Math.pow(2, 8 * byteLength) - 1
11719 checkInt(this, value, offset, byteLength, maxBytes, 0)
11720 }
11721
11722 var i = byteLength - 1
11723 var mul = 1
11724 this[offset + i] = value & 0xFF
11725 while (--i >= 0 && (mul *= 0x100)) {
11726 this[offset + i] = (value / mul) & 0xFF
11727 }
11728
11729 return offset + byteLength
11730}
11731
11732Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
11733 value = +value
11734 offset = offset >>> 0
11735 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
11736 this[offset] = (value & 0xff)
11737 return offset + 1
11738}
11739
11740Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
11741 value = +value
11742 offset = offset >>> 0
11743 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
11744 this[offset] = (value & 0xff)
11745 this[offset + 1] = (value >>> 8)
11746 return offset + 2
11747}
11748
11749Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
11750 value = +value
11751 offset = offset >>> 0
11752 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
11753 this[offset] = (value >>> 8)
11754 this[offset + 1] = (value & 0xff)
11755 return offset + 2
11756}
11757
11758Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
11759 value = +value
11760 offset = offset >>> 0
11761 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
11762 this[offset + 3] = (value >>> 24)
11763 this[offset + 2] = (value >>> 16)
11764 this[offset + 1] = (value >>> 8)
11765 this[offset] = (value & 0xff)
11766 return offset + 4
11767}
11768
11769Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
11770 value = +value
11771 offset = offset >>> 0
11772 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
11773 this[offset] = (value >>> 24)
11774 this[offset + 1] = (value >>> 16)
11775 this[offset + 2] = (value >>> 8)
11776 this[offset + 3] = (value & 0xff)
11777 return offset + 4
11778}
11779
11780Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
11781 value = +value
11782 offset = offset >>> 0
11783 if (!noAssert) {
11784 var limit = Math.pow(2, (8 * byteLength) - 1)
11785
11786 checkInt(this, value, offset, byteLength, limit - 1, -limit)
11787 }
11788
11789 var i = 0
11790 var mul = 1
11791 var sub = 0
11792 this[offset] = value & 0xFF
11793 while (++i < byteLength && (mul *= 0x100)) {
11794 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
11795 sub = 1
11796 }
11797 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
11798 }
11799
11800 return offset + byteLength
11801}
11802
11803Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
11804 value = +value
11805 offset = offset >>> 0
11806 if (!noAssert) {
11807 var limit = Math.pow(2, (8 * byteLength) - 1)
11808
11809 checkInt(this, value, offset, byteLength, limit - 1, -limit)
11810 }
11811
11812 var i = byteLength - 1
11813 var mul = 1
11814 var sub = 0
11815 this[offset + i] = value & 0xFF
11816 while (--i >= 0 && (mul *= 0x100)) {
11817 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
11818 sub = 1
11819 }
11820 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
11821 }
11822
11823 return offset + byteLength
11824}
11825
11826Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
11827 value = +value
11828 offset = offset >>> 0
11829 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
11830 if (value < 0) value = 0xff + value + 1
11831 this[offset] = (value & 0xff)
11832 return offset + 1
11833}
11834
11835Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
11836 value = +value
11837 offset = offset >>> 0
11838 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
11839 this[offset] = (value & 0xff)
11840 this[offset + 1] = (value >>> 8)
11841 return offset + 2
11842}
11843
11844Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
11845 value = +value
11846 offset = offset >>> 0
11847 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
11848 this[offset] = (value >>> 8)
11849 this[offset + 1] = (value & 0xff)
11850 return offset + 2
11851}
11852
11853Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
11854 value = +value
11855 offset = offset >>> 0
11856 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
11857 this[offset] = (value & 0xff)
11858 this[offset + 1] = (value >>> 8)
11859 this[offset + 2] = (value >>> 16)
11860 this[offset + 3] = (value >>> 24)
11861 return offset + 4
11862}
11863
11864Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
11865 value = +value
11866 offset = offset >>> 0
11867 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
11868 if (value < 0) value = 0xffffffff + value + 1
11869 this[offset] = (value >>> 24)
11870 this[offset + 1] = (value >>> 16)
11871 this[offset + 2] = (value >>> 8)
11872 this[offset + 3] = (value & 0xff)
11873 return offset + 4
11874}
11875
11876function checkIEEE754 (buf, value, offset, ext, max, min) {
11877 if (offset + ext > buf.length) throw new RangeError('Index out of range')
11878 if (offset < 0) throw new RangeError('Index out of range')
11879}
11880
11881function writeFloat (buf, value, offset, littleEndian, noAssert) {
11882 value = +value
11883 offset = offset >>> 0
11884 if (!noAssert) {
11885 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
11886 }
11887 ieee754.write(buf, value, offset, littleEndian, 23, 4)
11888 return offset + 4
11889}
11890
11891Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
11892 return writeFloat(this, value, offset, true, noAssert)
11893}
11894
11895Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
11896 return writeFloat(this, value, offset, false, noAssert)
11897}
11898
11899function writeDouble (buf, value, offset, littleEndian, noAssert) {
11900 value = +value
11901 offset = offset >>> 0
11902 if (!noAssert) {
11903 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
11904 }
11905 ieee754.write(buf, value, offset, littleEndian, 52, 8)
11906 return offset + 8
11907}
11908
11909Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
11910 return writeDouble(this, value, offset, true, noAssert)
11911}
11912
11913Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
11914 return writeDouble(this, value, offset, false, noAssert)
11915}
11916
11917// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
11918Buffer.prototype.copy = function copy (target, targetStart, start, end) {
11919 if (!start) start = 0
11920 if (!end && end !== 0) end = this.length
11921 if (targetStart >= target.length) targetStart = target.length
11922 if (!targetStart) targetStart = 0
11923 if (end > 0 && end < start) end = start
11924
11925 // Copy 0 bytes; we're done
11926 if (end === start) return 0
11927 if (target.length === 0 || this.length === 0) return 0
11928
11929 // Fatal error conditions
11930 if (targetStart < 0) {
11931 throw new RangeError('targetStart out of bounds')
11932 }
11933 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
11934 if (end < 0) throw new RangeError('sourceEnd out of bounds')
11935
11936 // Are we oob?
11937 if (end > this.length) end = this.length
11938 if (target.length - targetStart < end - start) {
11939 end = target.length - targetStart + start
11940 }
11941
11942 var len = end - start
11943 var i
11944
11945 if (this === target && start < targetStart && targetStart < end) {
11946 // descending copy from end
11947 for (i = len - 1; i >= 0; --i) {
11948 target[i + targetStart] = this[i + start]
11949 }
11950 } else if (len < 1000) {
11951 // ascending copy from start
11952 for (i = 0; i < len; ++i) {
11953 target[i + targetStart] = this[i + start]
11954 }
11955 } else {
11956 Uint8Array.prototype.set.call(
11957 target,
11958 this.subarray(start, start + len),
11959 targetStart
11960 )
11961 }
11962
11963 return len
11964}
11965
11966// Usage:
11967// buffer.fill(number[, offset[, end]])
11968// buffer.fill(buffer[, offset[, end]])
11969// buffer.fill(string[, offset[, end]][, encoding])
11970Buffer.prototype.fill = function fill (val, start, end, encoding) {
11971 // Handle string cases:
11972 if (typeof val === 'string') {
11973 if (typeof start === 'string') {
11974 encoding = start
11975 start = 0
11976 end = this.length
11977 } else if (typeof end === 'string') {
11978 encoding = end
11979 end = this.length
11980 }
11981 if (val.length === 1) {
11982 var code = val.charCodeAt(0)
11983 if (code < 256) {
11984 val = code
11985 }
11986 }
11987 if (encoding !== undefined && typeof encoding !== 'string') {
11988 throw new TypeError('encoding must be a string')
11989 }
11990 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
11991 throw new TypeError('Unknown encoding: ' + encoding)
11992 }
11993 } else if (typeof val === 'number') {
11994 val = val & 255
11995 }
11996
11997 // Invalid ranges are not set to a default, so can range check early.
11998 if (start < 0 || this.length < start || this.length < end) {
11999 throw new RangeError('Out of range index')
12000 }
12001
12002 if (end <= start) {
12003 return this
12004 }
12005
12006 start = start >>> 0
12007 end = end === undefined ? this.length : end >>> 0
12008
12009 if (!val) val = 0
12010
12011 var i
12012 if (typeof val === 'number') {
12013 for (i = start; i < end; ++i) {
12014 this[i] = val
12015 }
12016 } else {
12017 var bytes = Buffer.isBuffer(val)
12018 ? val
12019 : new Buffer(val, encoding)
12020 var len = bytes.length
12021 for (i = 0; i < end - start; ++i) {
12022 this[i + start] = bytes[i % len]
12023 }
12024 }
12025
12026 return this
12027}
12028
12029// HELPER FUNCTIONS
12030// ================
12031
12032var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
12033
12034function base64clean (str) {
12035 // Node strips out invalid characters like \n and \t from the string, base64-js does not
12036 str = str.trim().replace(INVALID_BASE64_RE, '')
12037 // Node converts strings with length < 2 to ''
12038 if (str.length < 2) return ''
12039 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
12040 while (str.length % 4 !== 0) {
12041 str = str + '='
12042 }
12043 return str
12044}
12045
12046function toHex (n) {
12047 if (n < 16) return '0' + n.toString(16)
12048 return n.toString(16)
12049}
12050
12051function utf8ToBytes (string, units) {
12052 units = units || Infinity
12053 var codePoint
12054 var length = string.length
12055 var leadSurrogate = null
12056 var bytes = []
12057
12058 for (var i = 0; i < length; ++i) {
12059 codePoint = string.charCodeAt(i)
12060
12061 // is surrogate component
12062 if (codePoint > 0xD7FF && codePoint < 0xE000) {
12063 // last char was a lead
12064 if (!leadSurrogate) {
12065 // no lead yet
12066 if (codePoint > 0xDBFF) {
12067 // unexpected trail
12068 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
12069 continue
12070 } else if (i + 1 === length) {
12071 // unpaired lead
12072 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
12073 continue
12074 }
12075
12076 // valid lead
12077 leadSurrogate = codePoint
12078
12079 continue
12080 }
12081
12082 // 2 leads in a row
12083 if (codePoint < 0xDC00) {
12084 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
12085 leadSurrogate = codePoint
12086 continue
12087 }
12088
12089 // valid surrogate pair
12090 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
12091 } else if (leadSurrogate) {
12092 // valid bmp char, but last char was a lead
12093 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
12094 }
12095
12096 leadSurrogate = null
12097
12098 // encode utf8
12099 if (codePoint < 0x80) {
12100 if ((units -= 1) < 0) break
12101 bytes.push(codePoint)
12102 } else if (codePoint < 0x800) {
12103 if ((units -= 2) < 0) break
12104 bytes.push(
12105 codePoint >> 0x6 | 0xC0,
12106 codePoint & 0x3F | 0x80
12107 )
12108 } else if (codePoint < 0x10000) {
12109 if ((units -= 3) < 0) break
12110 bytes.push(
12111 codePoint >> 0xC | 0xE0,
12112 codePoint >> 0x6 & 0x3F | 0x80,
12113 codePoint & 0x3F | 0x80
12114 )
12115 } else if (codePoint < 0x110000) {
12116 if ((units -= 4) < 0) break
12117 bytes.push(
12118 codePoint >> 0x12 | 0xF0,
12119 codePoint >> 0xC & 0x3F | 0x80,
12120 codePoint >> 0x6 & 0x3F | 0x80,
12121 codePoint & 0x3F | 0x80
12122 )
12123 } else {
12124 throw new Error('Invalid code point')
12125 }
12126 }
12127
12128 return bytes
12129}
12130
12131function asciiToBytes (str) {
12132 var byteArray = []
12133 for (var i = 0; i < str.length; ++i) {
12134 // Node's code seems to be doing this and not & 0x7F..
12135 byteArray.push(str.charCodeAt(i) & 0xFF)
12136 }
12137 return byteArray
12138}
12139
12140function utf16leToBytes (str, units) {
12141 var c, hi, lo
12142 var byteArray = []
12143 for (var i = 0; i < str.length; ++i) {
12144 if ((units -= 2) < 0) break
12145
12146 c = str.charCodeAt(i)
12147 hi = c >> 8
12148 lo = c % 256
12149 byteArray.push(lo)
12150 byteArray.push(hi)
12151 }
12152
12153 return byteArray
12154}
12155
12156function base64ToBytes (str) {
12157 return base64.toByteArray(base64clean(str))
12158}
12159
12160function blitBuffer (src, dst, offset, length) {
12161 for (var i = 0; i < length; ++i) {
12162 if ((i + offset >= dst.length) || (i >= src.length)) break
12163 dst[i + offset] = src[i]
12164 }
12165 return i
12166}
12167
12168// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
12169// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
12170function isArrayBuffer (obj) {
12171 return obj instanceof ArrayBuffer ||
12172 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
12173 typeof obj.byteLength === 'number')
12174}
12175
12176// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
12177function isArrayBufferView (obj) {
12178 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
12179}
12180
12181function numberIsNaN (obj) {
12182 return obj !== obj // eslint-disable-line no-self-compare
12183}
12184
12185},{"base64-js":18,"ieee754":105}],54:[function(require,module,exports){
12186var Buffer = require('safe-buffer').Buffer
12187var Transform = require('stream').Transform
12188var StringDecoder = require('string_decoder').StringDecoder
12189var inherits = require('inherits')
12190
12191function CipherBase (hashMode) {
12192 Transform.call(this)
12193 this.hashMode = typeof hashMode === 'string'
12194 if (this.hashMode) {
12195 this[hashMode] = this._finalOrDigest
12196 } else {
12197 this.final = this._finalOrDigest
12198 }
12199 if (this._final) {
12200 this.__final = this._final
12201 this._final = null
12202 }
12203 this._decoder = null
12204 this._encoding = null
12205}
12206inherits(CipherBase, Transform)
12207
12208CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
12209 if (typeof data === 'string') {
12210 data = Buffer.from(data, inputEnc)
12211 }
12212
12213 var outData = this._update(data)
12214 if (this.hashMode) return this
12215
12216 if (outputEnc) {
12217 outData = this._toString(outData, outputEnc)
12218 }
12219
12220 return outData
12221}
12222
12223CipherBase.prototype.setAutoPadding = function () {}
12224CipherBase.prototype.getAuthTag = function () {
12225 throw new Error('trying to get auth tag in unsupported state')
12226}
12227
12228CipherBase.prototype.setAuthTag = function () {
12229 throw new Error('trying to set auth tag in unsupported state')
12230}
12231
12232CipherBase.prototype.setAAD = function () {
12233 throw new Error('trying to set aad in unsupported state')
12234}
12235
12236CipherBase.prototype._transform = function (data, _, next) {
12237 var err
12238 try {
12239 if (this.hashMode) {
12240 this._update(data)
12241 } else {
12242 this.push(this._update(data))
12243 }
12244 } catch (e) {
12245 err = e
12246 } finally {
12247 next(err)
12248 }
12249}
12250CipherBase.prototype._flush = function (done) {
12251 var err
12252 try {
12253 this.push(this.__final())
12254 } catch (e) {
12255 err = e
12256 }
12257
12258 done(err)
12259}
12260CipherBase.prototype._finalOrDigest = function (outputEnc) {
12261 var outData = this.__final() || Buffer.alloc(0)
12262 if (outputEnc) {
12263 outData = this._toString(outData, outputEnc, true)
12264 }
12265 return outData
12266}
12267
12268CipherBase.prototype._toString = function (value, enc, fin) {
12269 if (!this._decoder) {
12270 this._decoder = new StringDecoder(enc)
12271 this._encoding = enc
12272 }
12273
12274 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
12275
12276 var out = this._decoder.write(value)
12277 if (fin) {
12278 out += this._decoder.end()
12279 }
12280
12281 return out
12282}
12283
12284module.exports = CipherBase
12285
12286},{"inherits":107,"safe-buffer":156,"stream":172,"string_decoder":173}],55:[function(require,module,exports){
12287(function (Buffer){
12288// Copyright Joyent, Inc. and other Node contributors.
12289//
12290// Permission is hereby granted, free of charge, to any person obtaining a
12291// copy of this software and associated documentation files (the
12292// "Software"), to deal in the Software without restriction, including
12293// without limitation the rights to use, copy, modify, merge, publish,
12294// distribute, sublicense, and/or sell copies of the Software, and to permit
12295// persons to whom the Software is furnished to do so, subject to the
12296// following conditions:
12297//
12298// The above copyright notice and this permission notice shall be included
12299// in all copies or substantial portions of the Software.
12300//
12301// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12302// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12303// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12304// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12305// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12306// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12307// USE OR OTHER DEALINGS IN THE SOFTWARE.
12308
12309// NOTE: These type checking functions intentionally don't use `instanceof`
12310// because it is fragile and can be easily faked with `Object.create()`.
12311
12312function isArray(arg) {
12313 if (Array.isArray) {
12314 return Array.isArray(arg);
12315 }
12316 return objectToString(arg) === '[object Array]';
12317}
12318exports.isArray = isArray;
12319
12320function isBoolean(arg) {
12321 return typeof arg === 'boolean';
12322}
12323exports.isBoolean = isBoolean;
12324
12325function isNull(arg) {
12326 return arg === null;
12327}
12328exports.isNull = isNull;
12329
12330function isNullOrUndefined(arg) {
12331 return arg == null;
12332}
12333exports.isNullOrUndefined = isNullOrUndefined;
12334
12335function isNumber(arg) {
12336 return typeof arg === 'number';
12337}
12338exports.isNumber = isNumber;
12339
12340function isString(arg) {
12341 return typeof arg === 'string';
12342}
12343exports.isString = isString;
12344
12345function isSymbol(arg) {
12346 return typeof arg === 'symbol';
12347}
12348exports.isSymbol = isSymbol;
12349
12350function isUndefined(arg) {
12351 return arg === void 0;
12352}
12353exports.isUndefined = isUndefined;
12354
12355function isRegExp(re) {
12356 return objectToString(re) === '[object RegExp]';
12357}
12358exports.isRegExp = isRegExp;
12359
12360function isObject(arg) {
12361 return typeof arg === 'object' && arg !== null;
12362}
12363exports.isObject = isObject;
12364
12365function isDate(d) {
12366 return objectToString(d) === '[object Date]';
12367}
12368exports.isDate = isDate;
12369
12370function isError(e) {
12371 return (objectToString(e) === '[object Error]' || e instanceof Error);
12372}
12373exports.isError = isError;
12374
12375function isFunction(arg) {
12376 return typeof arg === 'function';
12377}
12378exports.isFunction = isFunction;
12379
12380function isPrimitive(arg) {
12381 return arg === null ||
12382 typeof arg === 'boolean' ||
12383 typeof arg === 'number' ||
12384 typeof arg === 'string' ||
12385 typeof arg === 'symbol' || // ES6 symbol
12386 typeof arg === 'undefined';
12387}
12388exports.isPrimitive = isPrimitive;
12389
12390exports.isBuffer = Buffer.isBuffer;
12391
12392function objectToString(o) {
12393 return Object.prototype.toString.call(o);
12394}
12395
12396}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
12397},{"../../is-buffer/index.js":108}],56:[function(require,module,exports){
12398(function (Buffer){
12399var elliptic = require('elliptic');
12400var BN = require('bn.js');
12401
12402module.exports = function createECDH(curve) {
12403 return new ECDH(curve);
12404};
12405
12406var aliases = {
12407 secp256k1: {
12408 name: 'secp256k1',
12409 byteLength: 32
12410 },
12411 secp224r1: {
12412 name: 'p224',
12413 byteLength: 28
12414 },
12415 prime256v1: {
12416 name: 'p256',
12417 byteLength: 32
12418 },
12419 prime192v1: {
12420 name: 'p192',
12421 byteLength: 24
12422 },
12423 ed25519: {
12424 name: 'ed25519',
12425 byteLength: 32
12426 },
12427 secp384r1: {
12428 name: 'p384',
12429 byteLength: 48
12430 },
12431 secp521r1: {
12432 name: 'p521',
12433 byteLength: 66
12434 }
12435};
12436
12437aliases.p224 = aliases.secp224r1;
12438aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
12439aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
12440aliases.p384 = aliases.secp384r1;
12441aliases.p521 = aliases.secp521r1;
12442
12443function ECDH(curve) {
12444 this.curveType = aliases[curve];
12445 if (!this.curveType ) {
12446 this.curveType = {
12447 name: curve
12448 };
12449 }
12450 this.curve = new elliptic.ec(this.curveType.name);
12451 this.keys = void 0;
12452}
12453
12454ECDH.prototype.generateKeys = function (enc, format) {
12455 this.keys = this.curve.genKeyPair();
12456 return this.getPublicKey(enc, format);
12457};
12458
12459ECDH.prototype.computeSecret = function (other, inenc, enc) {
12460 inenc = inenc || 'utf8';
12461 if (!Buffer.isBuffer(other)) {
12462 other = new Buffer(other, inenc);
12463 }
12464 var otherPub = this.curve.keyFromPublic(other).getPublic();
12465 var out = otherPub.mul(this.keys.getPrivate()).getX();
12466 return formatReturnValue(out, enc, this.curveType.byteLength);
12467};
12468
12469ECDH.prototype.getPublicKey = function (enc, format) {
12470 var key = this.keys.getPublic(format === 'compressed', true);
12471 if (format === 'hybrid') {
12472 if (key[key.length - 1] % 2) {
12473 key[0] = 7;
12474 } else {
12475 key [0] = 6;
12476 }
12477 }
12478 return formatReturnValue(key, enc);
12479};
12480
12481ECDH.prototype.getPrivateKey = function (enc) {
12482 return formatReturnValue(this.keys.getPrivate(), enc);
12483};
12484
12485ECDH.prototype.setPublicKey = function (pub, enc) {
12486 enc = enc || 'utf8';
12487 if (!Buffer.isBuffer(pub)) {
12488 pub = new Buffer(pub, enc);
12489 }
12490 this.keys._importPublic(pub);
12491 return this;
12492};
12493
12494ECDH.prototype.setPrivateKey = function (priv, enc) {
12495 enc = enc || 'utf8';
12496 if (!Buffer.isBuffer(priv)) {
12497 priv = new Buffer(priv, enc);
12498 }
12499 var _priv = new BN(priv);
12500 _priv = _priv.toString(16);
12501 this.keys._importPrivate(_priv);
12502 return this;
12503};
12504
12505function formatReturnValue(bn, enc, len) {
12506 if (!Array.isArray(bn)) {
12507 bn = bn.toArray();
12508 }
12509 var buf = new Buffer(bn);
12510 if (len && buf.length < len) {
12511 var zeros = new Buffer(len - buf.length);
12512 zeros.fill(0);
12513 buf = Buffer.concat([zeros, buf]);
12514 }
12515 if (!enc) {
12516 return buf;
12517 } else {
12518 return buf.toString(enc);
12519 }
12520}
12521
12522}).call(this,require("buffer").Buffer)
12523},{"bn.js":21,"buffer":53,"elliptic":73}],57:[function(require,module,exports){
12524(function (Buffer){
12525'use strict'
12526var inherits = require('inherits')
12527var md5 = require('./md5')
12528var RIPEMD160 = require('ripemd160')
12529var sha = require('sha.js')
12530
12531var Base = require('cipher-base')
12532
12533function HashNoConstructor (hash) {
12534 Base.call(this, 'digest')
12535
12536 this._hash = hash
12537 this.buffers = []
12538}
12539
12540inherits(HashNoConstructor, Base)
12541
12542HashNoConstructor.prototype._update = function (data) {
12543 this.buffers.push(data)
12544}
12545
12546HashNoConstructor.prototype._final = function () {
12547 var buf = Buffer.concat(this.buffers)
12548 var r = this._hash(buf)
12549 this.buffers = null
12550
12551 return r
12552}
12553
12554function Hash (hash) {
12555 Base.call(this, 'digest')
12556
12557 this._hash = hash
12558}
12559
12560inherits(Hash, Base)
12561
12562Hash.prototype._update = function (data) {
12563 this._hash.update(data)
12564}
12565
12566Hash.prototype._final = function () {
12567 return this._hash.digest()
12568}
12569
12570module.exports = function createHash (alg) {
12571 alg = alg.toLowerCase()
12572 if (alg === 'md5') return new HashNoConstructor(md5)
12573 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
12574
12575 return new Hash(sha(alg))
12576}
12577
12578}).call(this,require("buffer").Buffer)
12579},{"./md5":59,"buffer":53,"cipher-base":54,"inherits":107,"ripemd160":155,"sha.js":165}],58:[function(require,module,exports){
12580(function (Buffer){
12581'use strict'
12582var intSize = 4
12583var zeroBuffer = new Buffer(intSize)
12584zeroBuffer.fill(0)
12585
12586var charSize = 8
12587var hashSize = 16
12588
12589function toArray (buf) {
12590 if ((buf.length % intSize) !== 0) {
12591 var len = buf.length + (intSize - (buf.length % intSize))
12592 buf = Buffer.concat([buf, zeroBuffer], len)
12593 }
12594
12595 var arr = new Array(buf.length >>> 2)
12596 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
12597 arr[j] = buf.readInt32LE(i)
12598 }
12599
12600 return arr
12601}
12602
12603module.exports = function hash (buf, fn) {
12604 var arr = fn(toArray(buf), buf.length * charSize)
12605 buf = new Buffer(hashSize)
12606 for (var i = 0; i < arr.length; i++) {
12607 buf.writeInt32LE(arr[i], i << 2, true)
12608 }
12609 return buf
12610}
12611
12612}).call(this,require("buffer").Buffer)
12613},{"buffer":53}],59:[function(require,module,exports){
12614'use strict'
12615/*
12616 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
12617 * Digest Algorithm, as defined in RFC 1321.
12618 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
12619 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
12620 * Distributed under the BSD License
12621 * See http://pajhome.org.uk/crypt/md5 for more info.
12622 */
12623
12624var makeHash = require('./make-hash')
12625
12626/*
12627 * Calculate the MD5 of an array of little-endian words, and a bit length
12628 */
12629function core_md5 (x, len) {
12630 /* append padding */
12631 x[len >> 5] |= 0x80 << ((len) % 32)
12632 x[(((len + 64) >>> 9) << 4) + 14] = len
12633
12634 var a = 1732584193
12635 var b = -271733879
12636 var c = -1732584194
12637 var d = 271733878
12638
12639 for (var i = 0; i < x.length; i += 16) {
12640 var olda = a
12641 var oldb = b
12642 var oldc = c
12643 var oldd = d
12644
12645 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
12646 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
12647 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
12648 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
12649 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
12650 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
12651 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
12652 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
12653 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
12654 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
12655 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
12656 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
12657 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
12658 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
12659 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
12660 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
12661
12662 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
12663 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
12664 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
12665 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
12666 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
12667 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
12668 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
12669 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
12670 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
12671 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
12672 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
12673 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
12674 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
12675 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
12676 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
12677 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
12678
12679 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
12680 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
12681 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
12682 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
12683 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
12684 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
12685 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
12686 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
12687 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
12688 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
12689 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
12690 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
12691 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
12692 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
12693 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
12694 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
12695
12696 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
12697 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
12698 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
12699 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
12700 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
12701 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
12702 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
12703 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
12704 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
12705 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
12706 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
12707 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
12708 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
12709 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
12710 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
12711 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
12712
12713 a = safe_add(a, olda)
12714 b = safe_add(b, oldb)
12715 c = safe_add(c, oldc)
12716 d = safe_add(d, oldd)
12717 }
12718
12719 return [a, b, c, d]
12720}
12721
12722/*
12723 * These functions implement the four basic operations the algorithm uses.
12724 */
12725function md5_cmn (q, a, b, x, s, t) {
12726 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
12727}
12728
12729function md5_ff (a, b, c, d, x, s, t) {
12730 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
12731}
12732
12733function md5_gg (a, b, c, d, x, s, t) {
12734 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
12735}
12736
12737function md5_hh (a, b, c, d, x, s, t) {
12738 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
12739}
12740
12741function md5_ii (a, b, c, d, x, s, t) {
12742 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
12743}
12744
12745/*
12746 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
12747 * to work around bugs in some JS interpreters.
12748 */
12749function safe_add (x, y) {
12750 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
12751 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
12752 return (msw << 16) | (lsw & 0xFFFF)
12753}
12754
12755/*
12756 * Bitwise rotate a 32-bit number to the left.
12757 */
12758function bit_rol (num, cnt) {
12759 return (num << cnt) | (num >>> (32 - cnt))
12760}
12761
12762module.exports = function md5 (buf) {
12763 return makeHash(buf, core_md5)
12764}
12765
12766},{"./make-hash":58}],60:[function(require,module,exports){
12767'use strict'
12768var inherits = require('inherits')
12769var Legacy = require('./legacy')
12770var Base = require('cipher-base')
12771var Buffer = require('safe-buffer').Buffer
12772var md5 = require('create-hash/md5')
12773var RIPEMD160 = require('ripemd160')
12774
12775var sha = require('sha.js')
12776
12777var ZEROS = Buffer.alloc(128)
12778
12779function Hmac (alg, key) {
12780 Base.call(this, 'digest')
12781 if (typeof key === 'string') {
12782 key = Buffer.from(key)
12783 }
12784
12785 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
12786
12787 this._alg = alg
12788 this._key = key
12789 if (key.length > blocksize) {
12790 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12791 key = hash.update(key).digest()
12792 } else if (key.length < blocksize) {
12793 key = Buffer.concat([key, ZEROS], blocksize)
12794 }
12795
12796 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12797 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12798
12799 for (var i = 0; i < blocksize; i++) {
12800 ipad[i] = key[i] ^ 0x36
12801 opad[i] = key[i] ^ 0x5C
12802 }
12803 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12804 this._hash.update(ipad)
12805}
12806
12807inherits(Hmac, Base)
12808
12809Hmac.prototype._update = function (data) {
12810 this._hash.update(data)
12811}
12812
12813Hmac.prototype._final = function () {
12814 var h = this._hash.digest()
12815 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
12816 return hash.update(this._opad).update(h).digest()
12817}
12818
12819module.exports = function createHmac (alg, key) {
12820 alg = alg.toLowerCase()
12821 if (alg === 'rmd160' || alg === 'ripemd160') {
12822 return new Hmac('rmd160', key)
12823 }
12824 if (alg === 'md5') {
12825 return new Legacy(md5, key)
12826 }
12827 return new Hmac(alg, key)
12828}
12829
12830},{"./legacy":61,"cipher-base":54,"create-hash/md5":59,"inherits":107,"ripemd160":155,"safe-buffer":156,"sha.js":165}],61:[function(require,module,exports){
12831'use strict'
12832var inherits = require('inherits')
12833var Buffer = require('safe-buffer').Buffer
12834
12835var Base = require('cipher-base')
12836
12837var ZEROS = Buffer.alloc(128)
12838var blocksize = 64
12839
12840function Hmac (alg, key) {
12841 Base.call(this, 'digest')
12842 if (typeof key === 'string') {
12843 key = Buffer.from(key)
12844 }
12845
12846 this._alg = alg
12847 this._key = key
12848
12849 if (key.length > blocksize) {
12850 key = alg(key)
12851 } else if (key.length < blocksize) {
12852 key = Buffer.concat([key, ZEROS], blocksize)
12853 }
12854
12855 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12856 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12857
12858 for (var i = 0; i < blocksize; i++) {
12859 ipad[i] = key[i] ^ 0x36
12860 opad[i] = key[i] ^ 0x5C
12861 }
12862
12863 this._hash = [ipad]
12864}
12865
12866inherits(Hmac, Base)
12867
12868Hmac.prototype._update = function (data) {
12869 this._hash.push(data)
12870}
12871
12872Hmac.prototype._final = function () {
12873 var h = this._alg(Buffer.concat(this._hash))
12874 return this._alg(Buffer.concat([this._opad, h]))
12875}
12876module.exports = Hmac
12877
12878},{"cipher-base":54,"inherits":107,"safe-buffer":156}],62:[function(require,module,exports){
12879'use strict'
12880
12881exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
12882exports.createHash = exports.Hash = require('create-hash')
12883exports.createHmac = exports.Hmac = require('create-hmac')
12884
12885var algos = require('browserify-sign/algos')
12886var algoKeys = Object.keys(algos)
12887var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
12888exports.getHashes = function () {
12889 return hashes
12890}
12891
12892var p = require('pbkdf2')
12893exports.pbkdf2 = p.pbkdf2
12894exports.pbkdf2Sync = p.pbkdf2Sync
12895
12896var aes = require('browserify-cipher')
12897
12898exports.Cipher = aes.Cipher
12899exports.createCipher = aes.createCipher
12900exports.Cipheriv = aes.Cipheriv
12901exports.createCipheriv = aes.createCipheriv
12902exports.Decipher = aes.Decipher
12903exports.createDecipher = aes.createDecipher
12904exports.Decipheriv = aes.Decipheriv
12905exports.createDecipheriv = aes.createDecipheriv
12906exports.getCiphers = aes.getCiphers
12907exports.listCiphers = aes.listCiphers
12908
12909var dh = require('diffie-hellman')
12910
12911exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
12912exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
12913exports.getDiffieHellman = dh.getDiffieHellman
12914exports.createDiffieHellman = dh.createDiffieHellman
12915exports.DiffieHellman = dh.DiffieHellman
12916
12917var sign = require('browserify-sign')
12918
12919exports.createSign = sign.createSign
12920exports.Sign = sign.Sign
12921exports.createVerify = sign.createVerify
12922exports.Verify = sign.Verify
12923
12924exports.createECDH = require('create-ecdh')
12925
12926var publicEncrypt = require('public-encrypt')
12927
12928exports.publicEncrypt = publicEncrypt.publicEncrypt
12929exports.privateEncrypt = publicEncrypt.privateEncrypt
12930exports.publicDecrypt = publicEncrypt.publicDecrypt
12931exports.privateDecrypt = publicEncrypt.privateDecrypt
12932
12933// the least I can do is make error messages for the rest of the node.js/crypto api.
12934// ;[
12935// 'createCredentials'
12936// ].forEach(function (name) {
12937// exports[name] = function () {
12938// throw new Error([
12939// 'sorry, ' + name + ' is not implemented yet',
12940// 'we accept pull requests',
12941// 'https://github.com/crypto-browserify/crypto-browserify'
12942// ].join('\n'))
12943// }
12944// })
12945
12946var rf = require('randomfill')
12947
12948exports.randomFill = rf.randomFill
12949exports.randomFillSync = rf.randomFillSync
12950
12951exports.createCredentials = function () {
12952 throw new Error([
12953 'sorry, createCredentials is not implemented yet',
12954 'we accept pull requests',
12955 'https://github.com/crypto-browserify/crypto-browserify'
12956 ].join('\n'))
12957}
12958
12959exports.constants = {
12960 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
12961 'DH_CHECK_P_NOT_PRIME': 1,
12962 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
12963 'DH_NOT_SUITABLE_GENERATOR': 8,
12964 'NPN_ENABLED': 1,
12965 'ALPN_ENABLED': 1,
12966 'RSA_PKCS1_PADDING': 1,
12967 'RSA_SSLV23_PADDING': 2,
12968 'RSA_NO_PADDING': 3,
12969 'RSA_PKCS1_OAEP_PADDING': 4,
12970 'RSA_X931_PADDING': 5,
12971 'RSA_PKCS1_PSS_PADDING': 6,
12972 'POINT_CONVERSION_COMPRESSED': 2,
12973 'POINT_CONVERSION_UNCOMPRESSED': 4,
12974 'POINT_CONVERSION_HYBRID': 6
12975}
12976
12977},{"browserify-cipher":41,"browserify-sign":48,"browserify-sign/algos":45,"create-ecdh":56,"create-hash":57,"create-hmac":60,"diffie-hellman":69,"pbkdf2":127,"public-encrypt":134,"randombytes":140,"randomfill":141}],63:[function(require,module,exports){
12978'use strict';
12979
12980exports.utils = require('./des/utils');
12981exports.Cipher = require('./des/cipher');
12982exports.DES = require('./des/des');
12983exports.CBC = require('./des/cbc');
12984exports.EDE = require('./des/ede');
12985
12986},{"./des/cbc":64,"./des/cipher":65,"./des/des":66,"./des/ede":67,"./des/utils":68}],64:[function(require,module,exports){
12987'use strict';
12988
12989var assert = require('minimalistic-assert');
12990var inherits = require('inherits');
12991
12992var proto = {};
12993
12994function CBCState(iv) {
12995 assert.equal(iv.length, 8, 'Invalid IV length');
12996
12997 this.iv = new Array(8);
12998 for (var i = 0; i < this.iv.length; i++)
12999 this.iv[i] = iv[i];
13000}
13001
13002function instantiate(Base) {
13003 function CBC(options) {
13004 Base.call(this, options);
13005 this._cbcInit();
13006 }
13007 inherits(CBC, Base);
13008
13009 var keys = Object.keys(proto);
13010 for (var i = 0; i < keys.length; i++) {
13011 var key = keys[i];
13012 CBC.prototype[key] = proto[key];
13013 }
13014
13015 CBC.create = function create(options) {
13016 return new CBC(options);
13017 };
13018
13019 return CBC;
13020}
13021
13022exports.instantiate = instantiate;
13023
13024proto._cbcInit = function _cbcInit() {
13025 var state = new CBCState(this.options.iv);
13026 this._cbcState = state;
13027};
13028
13029proto._update = function _update(inp, inOff, out, outOff) {
13030 var state = this._cbcState;
13031 var superProto = this.constructor.super_.prototype;
13032
13033 var iv = state.iv;
13034 if (this.type === 'encrypt') {
13035 for (var i = 0; i < this.blockSize; i++)
13036 iv[i] ^= inp[inOff + i];
13037
13038 superProto._update.call(this, iv, 0, out, outOff);
13039
13040 for (var i = 0; i < this.blockSize; i++)
13041 iv[i] = out[outOff + i];
13042 } else {
13043 superProto._update.call(this, inp, inOff, out, outOff);
13044
13045 for (var i = 0; i < this.blockSize; i++)
13046 out[outOff + i] ^= iv[i];
13047
13048 for (var i = 0; i < this.blockSize; i++)
13049 iv[i] = inp[inOff + i];
13050 }
13051};
13052
13053},{"inherits":107,"minimalistic-assert":120}],65:[function(require,module,exports){
13054'use strict';
13055
13056var assert = require('minimalistic-assert');
13057
13058function Cipher(options) {
13059 this.options = options;
13060
13061 this.type = this.options.type;
13062 this.blockSize = 8;
13063 this._init();
13064
13065 this.buffer = new Array(this.blockSize);
13066 this.bufferOff = 0;
13067}
13068module.exports = Cipher;
13069
13070Cipher.prototype._init = function _init() {
13071 // Might be overrided
13072};
13073
13074Cipher.prototype.update = function update(data) {
13075 if (data.length === 0)
13076 return [];
13077
13078 if (this.type === 'decrypt')
13079 return this._updateDecrypt(data);
13080 else
13081 return this._updateEncrypt(data);
13082};
13083
13084Cipher.prototype._buffer = function _buffer(data, off) {
13085 // Append data to buffer
13086 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
13087 for (var i = 0; i < min; i++)
13088 this.buffer[this.bufferOff + i] = data[off + i];
13089 this.bufferOff += min;
13090
13091 // Shift next
13092 return min;
13093};
13094
13095Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
13096 this._update(this.buffer, 0, out, off);
13097 this.bufferOff = 0;
13098 return this.blockSize;
13099};
13100
13101Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
13102 var inputOff = 0;
13103 var outputOff = 0;
13104
13105 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
13106 var out = new Array(count * this.blockSize);
13107
13108 if (this.bufferOff !== 0) {
13109 inputOff += this._buffer(data, inputOff);
13110
13111 if (this.bufferOff === this.buffer.length)
13112 outputOff += this._flushBuffer(out, outputOff);
13113 }
13114
13115 // Write blocks
13116 var max = data.length - ((data.length - inputOff) % this.blockSize);
13117 for (; inputOff < max; inputOff += this.blockSize) {
13118 this._update(data, inputOff, out, outputOff);
13119 outputOff += this.blockSize;
13120 }
13121
13122 // Queue rest
13123 for (; inputOff < data.length; inputOff++, this.bufferOff++)
13124 this.buffer[this.bufferOff] = data[inputOff];
13125
13126 return out;
13127};
13128
13129Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
13130 var inputOff = 0;
13131 var outputOff = 0;
13132
13133 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
13134 var out = new Array(count * this.blockSize);
13135
13136 // TODO(indutny): optimize it, this is far from optimal
13137 for (; count > 0; count--) {
13138 inputOff += this._buffer(data, inputOff);
13139 outputOff += this._flushBuffer(out, outputOff);
13140 }
13141
13142 // Buffer rest of the input
13143 inputOff += this._buffer(data, inputOff);
13144
13145 return out;
13146};
13147
13148Cipher.prototype.final = function final(buffer) {
13149 var first;
13150 if (buffer)
13151 first = this.update(buffer);
13152
13153 var last;
13154 if (this.type === 'encrypt')
13155 last = this._finalEncrypt();
13156 else
13157 last = this._finalDecrypt();
13158
13159 if (first)
13160 return first.concat(last);
13161 else
13162 return last;
13163};
13164
13165Cipher.prototype._pad = function _pad(buffer, off) {
13166 if (off === 0)
13167 return false;
13168
13169 while (off < buffer.length)
13170 buffer[off++] = 0;
13171
13172 return true;
13173};
13174
13175Cipher.prototype._finalEncrypt = function _finalEncrypt() {
13176 if (!this._pad(this.buffer, this.bufferOff))
13177 return [];
13178
13179 var out = new Array(this.blockSize);
13180 this._update(this.buffer, 0, out, 0);
13181 return out;
13182};
13183
13184Cipher.prototype._unpad = function _unpad(buffer) {
13185 return buffer;
13186};
13187
13188Cipher.prototype._finalDecrypt = function _finalDecrypt() {
13189 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
13190 var out = new Array(this.blockSize);
13191 this._flushBuffer(out, 0);
13192
13193 return this._unpad(out);
13194};
13195
13196},{"minimalistic-assert":120}],66:[function(require,module,exports){
13197'use strict';
13198
13199var assert = require('minimalistic-assert');
13200var inherits = require('inherits');
13201
13202var des = require('../des');
13203var utils = des.utils;
13204var Cipher = des.Cipher;
13205
13206function DESState() {
13207 this.tmp = new Array(2);
13208 this.keys = null;
13209}
13210
13211function DES(options) {
13212 Cipher.call(this, options);
13213
13214 var state = new DESState();
13215 this._desState = state;
13216
13217 this.deriveKeys(state, options.key);
13218}
13219inherits(DES, Cipher);
13220module.exports = DES;
13221
13222DES.create = function create(options) {
13223 return new DES(options);
13224};
13225
13226var shiftTable = [
13227 1, 1, 2, 2, 2, 2, 2, 2,
13228 1, 2, 2, 2, 2, 2, 2, 1
13229];
13230
13231DES.prototype.deriveKeys = function deriveKeys(state, key) {
13232 state.keys = new Array(16 * 2);
13233
13234 assert.equal(key.length, this.blockSize, 'Invalid key length');
13235
13236 var kL = utils.readUInt32BE(key, 0);
13237 var kR = utils.readUInt32BE(key, 4);
13238
13239 utils.pc1(kL, kR, state.tmp, 0);
13240 kL = state.tmp[0];
13241 kR = state.tmp[1];
13242 for (var i = 0; i < state.keys.length; i += 2) {
13243 var shift = shiftTable[i >>> 1];
13244 kL = utils.r28shl(kL, shift);
13245 kR = utils.r28shl(kR, shift);
13246 utils.pc2(kL, kR, state.keys, i);
13247 }
13248};
13249
13250DES.prototype._update = function _update(inp, inOff, out, outOff) {
13251 var state = this._desState;
13252
13253 var l = utils.readUInt32BE(inp, inOff);
13254 var r = utils.readUInt32BE(inp, inOff + 4);
13255
13256 // Initial Permutation
13257 utils.ip(l, r, state.tmp, 0);
13258 l = state.tmp[0];
13259 r = state.tmp[1];
13260
13261 if (this.type === 'encrypt')
13262 this._encrypt(state, l, r, state.tmp, 0);
13263 else
13264 this._decrypt(state, l, r, state.tmp, 0);
13265
13266 l = state.tmp[0];
13267 r = state.tmp[1];
13268
13269 utils.writeUInt32BE(out, l, outOff);
13270 utils.writeUInt32BE(out, r, outOff + 4);
13271};
13272
13273DES.prototype._pad = function _pad(buffer, off) {
13274 var value = buffer.length - off;
13275 for (var i = off; i < buffer.length; i++)
13276 buffer[i] = value;
13277
13278 return true;
13279};
13280
13281DES.prototype._unpad = function _unpad(buffer) {
13282 var pad = buffer[buffer.length - 1];
13283 for (var i = buffer.length - pad; i < buffer.length; i++)
13284 assert.equal(buffer[i], pad);
13285
13286 return buffer.slice(0, buffer.length - pad);
13287};
13288
13289DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
13290 var l = lStart;
13291 var r = rStart;
13292
13293 // Apply f() x16 times
13294 for (var i = 0; i < state.keys.length; i += 2) {
13295 var keyL = state.keys[i];
13296 var keyR = state.keys[i + 1];
13297
13298 // f(r, k)
13299 utils.expand(r, state.tmp, 0);
13300
13301 keyL ^= state.tmp[0];
13302 keyR ^= state.tmp[1];
13303 var s = utils.substitute(keyL, keyR);
13304 var f = utils.permute(s);
13305
13306 var t = r;
13307 r = (l ^ f) >>> 0;
13308 l = t;
13309 }
13310
13311 // Reverse Initial Permutation
13312 utils.rip(r, l, out, off);
13313};
13314
13315DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
13316 var l = rStart;
13317 var r = lStart;
13318
13319 // Apply f() x16 times
13320 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
13321 var keyL = state.keys[i];
13322 var keyR = state.keys[i + 1];
13323
13324 // f(r, k)
13325 utils.expand(l, state.tmp, 0);
13326
13327 keyL ^= state.tmp[0];
13328 keyR ^= state.tmp[1];
13329 var s = utils.substitute(keyL, keyR);
13330 var f = utils.permute(s);
13331
13332 var t = l;
13333 l = (r ^ f) >>> 0;
13334 r = t;
13335 }
13336
13337 // Reverse Initial Permutation
13338 utils.rip(l, r, out, off);
13339};
13340
13341},{"../des":63,"inherits":107,"minimalistic-assert":120}],67:[function(require,module,exports){
13342'use strict';
13343
13344var assert = require('minimalistic-assert');
13345var inherits = require('inherits');
13346
13347var des = require('../des');
13348var Cipher = des.Cipher;
13349var DES = des.DES;
13350
13351function EDEState(type, key) {
13352 assert.equal(key.length, 24, 'Invalid key length');
13353
13354 var k1 = key.slice(0, 8);
13355 var k2 = key.slice(8, 16);
13356 var k3 = key.slice(16, 24);
13357
13358 if (type === 'encrypt') {
13359 this.ciphers = [
13360 DES.create({ type: 'encrypt', key: k1 }),
13361 DES.create({ type: 'decrypt', key: k2 }),
13362 DES.create({ type: 'encrypt', key: k3 })
13363 ];
13364 } else {
13365 this.ciphers = [
13366 DES.create({ type: 'decrypt', key: k3 }),
13367 DES.create({ type: 'encrypt', key: k2 }),
13368 DES.create({ type: 'decrypt', key: k1 })
13369 ];
13370 }
13371}
13372
13373function EDE(options) {
13374 Cipher.call(this, options);
13375
13376 var state = new EDEState(this.type, this.options.key);
13377 this._edeState = state;
13378}
13379inherits(EDE, Cipher);
13380
13381module.exports = EDE;
13382
13383EDE.create = function create(options) {
13384 return new EDE(options);
13385};
13386
13387EDE.prototype._update = function _update(inp, inOff, out, outOff) {
13388 var state = this._edeState;
13389
13390 state.ciphers[0]._update(inp, inOff, out, outOff);
13391 state.ciphers[1]._update(out, outOff, out, outOff);
13392 state.ciphers[2]._update(out, outOff, out, outOff);
13393};
13394
13395EDE.prototype._pad = DES.prototype._pad;
13396EDE.prototype._unpad = DES.prototype._unpad;
13397
13398},{"../des":63,"inherits":107,"minimalistic-assert":120}],68:[function(require,module,exports){
13399'use strict';
13400
13401exports.readUInt32BE = function readUInt32BE(bytes, off) {
13402 var res = (bytes[0 + off] << 24) |
13403 (bytes[1 + off] << 16) |
13404 (bytes[2 + off] << 8) |
13405 bytes[3 + off];
13406 return res >>> 0;
13407};
13408
13409exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
13410 bytes[0 + off] = value >>> 24;
13411 bytes[1 + off] = (value >>> 16) & 0xff;
13412 bytes[2 + off] = (value >>> 8) & 0xff;
13413 bytes[3 + off] = value & 0xff;
13414};
13415
13416exports.ip = function ip(inL, inR, out, off) {
13417 var outL = 0;
13418 var outR = 0;
13419
13420 for (var i = 6; i >= 0; i -= 2) {
13421 for (var j = 0; j <= 24; j += 8) {
13422 outL <<= 1;
13423 outL |= (inR >>> (j + i)) & 1;
13424 }
13425 for (var j = 0; j <= 24; j += 8) {
13426 outL <<= 1;
13427 outL |= (inL >>> (j + i)) & 1;
13428 }
13429 }
13430
13431 for (var i = 6; i >= 0; i -= 2) {
13432 for (var j = 1; j <= 25; j += 8) {
13433 outR <<= 1;
13434 outR |= (inR >>> (j + i)) & 1;
13435 }
13436 for (var j = 1; j <= 25; j += 8) {
13437 outR <<= 1;
13438 outR |= (inL >>> (j + i)) & 1;
13439 }
13440 }
13441
13442 out[off + 0] = outL >>> 0;
13443 out[off + 1] = outR >>> 0;
13444};
13445
13446exports.rip = function rip(inL, inR, out, off) {
13447 var outL = 0;
13448 var outR = 0;
13449
13450 for (var i = 0; i < 4; i++) {
13451 for (var j = 24; j >= 0; j -= 8) {
13452 outL <<= 1;
13453 outL |= (inR >>> (j + i)) & 1;
13454 outL <<= 1;
13455 outL |= (inL >>> (j + i)) & 1;
13456 }
13457 }
13458 for (var i = 4; i < 8; i++) {
13459 for (var j = 24; j >= 0; j -= 8) {
13460 outR <<= 1;
13461 outR |= (inR >>> (j + i)) & 1;
13462 outR <<= 1;
13463 outR |= (inL >>> (j + i)) & 1;
13464 }
13465 }
13466
13467 out[off + 0] = outL >>> 0;
13468 out[off + 1] = outR >>> 0;
13469};
13470
13471exports.pc1 = function pc1(inL, inR, out, off) {
13472 var outL = 0;
13473 var outR = 0;
13474
13475 // 7, 15, 23, 31, 39, 47, 55, 63
13476 // 6, 14, 22, 30, 39, 47, 55, 63
13477 // 5, 13, 21, 29, 39, 47, 55, 63
13478 // 4, 12, 20, 28
13479 for (var i = 7; i >= 5; i--) {
13480 for (var j = 0; j <= 24; j += 8) {
13481 outL <<= 1;
13482 outL |= (inR >> (j + i)) & 1;
13483 }
13484 for (var j = 0; j <= 24; j += 8) {
13485 outL <<= 1;
13486 outL |= (inL >> (j + i)) & 1;
13487 }
13488 }
13489 for (var j = 0; j <= 24; j += 8) {
13490 outL <<= 1;
13491 outL |= (inR >> (j + i)) & 1;
13492 }
13493
13494 // 1, 9, 17, 25, 33, 41, 49, 57
13495 // 2, 10, 18, 26, 34, 42, 50, 58
13496 // 3, 11, 19, 27, 35, 43, 51, 59
13497 // 36, 44, 52, 60
13498 for (var i = 1; i <= 3; i++) {
13499 for (var j = 0; j <= 24; j += 8) {
13500 outR <<= 1;
13501 outR |= (inR >> (j + i)) & 1;
13502 }
13503 for (var j = 0; j <= 24; j += 8) {
13504 outR <<= 1;
13505 outR |= (inL >> (j + i)) & 1;
13506 }
13507 }
13508 for (var j = 0; j <= 24; j += 8) {
13509 outR <<= 1;
13510 outR |= (inL >> (j + i)) & 1;
13511 }
13512
13513 out[off + 0] = outL >>> 0;
13514 out[off + 1] = outR >>> 0;
13515};
13516
13517exports.r28shl = function r28shl(num, shift) {
13518 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
13519};
13520
13521var pc2table = [
13522 // inL => outL
13523 14, 11, 17, 4, 27, 23, 25, 0,
13524 13, 22, 7, 18, 5, 9, 16, 24,
13525 2, 20, 12, 21, 1, 8, 15, 26,
13526
13527 // inR => outR
13528 15, 4, 25, 19, 9, 1, 26, 16,
13529 5, 11, 23, 8, 12, 7, 17, 0,
13530 22, 3, 10, 14, 6, 20, 27, 24
13531];
13532
13533exports.pc2 = function pc2(inL, inR, out, off) {
13534 var outL = 0;
13535 var outR = 0;
13536
13537 var len = pc2table.length >>> 1;
13538 for (var i = 0; i < len; i++) {
13539 outL <<= 1;
13540 outL |= (inL >>> pc2table[i]) & 0x1;
13541 }
13542 for (var i = len; i < pc2table.length; i++) {
13543 outR <<= 1;
13544 outR |= (inR >>> pc2table[i]) & 0x1;
13545 }
13546
13547 out[off + 0] = outL >>> 0;
13548 out[off + 1] = outR >>> 0;
13549};
13550
13551exports.expand = function expand(r, out, off) {
13552 var outL = 0;
13553 var outR = 0;
13554
13555 outL = ((r & 1) << 5) | (r >>> 27);
13556 for (var i = 23; i >= 15; i -= 4) {
13557 outL <<= 6;
13558 outL |= (r >>> i) & 0x3f;
13559 }
13560 for (var i = 11; i >= 3; i -= 4) {
13561 outR |= (r >>> i) & 0x3f;
13562 outR <<= 6;
13563 }
13564 outR |= ((r & 0x1f) << 1) | (r >>> 31);
13565
13566 out[off + 0] = outL >>> 0;
13567 out[off + 1] = outR >>> 0;
13568};
13569
13570var sTable = [
13571 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
13572 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
13573 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
13574 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
13575
13576 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
13577 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
13578 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
13579 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
13580
13581 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
13582 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
13583 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
13584 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
13585
13586 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
13587 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
13588 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
13589 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
13590
13591 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
13592 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
13593 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
13594 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
13595
13596 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
13597 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
13598 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
13599 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
13600
13601 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
13602 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
13603 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
13604 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
13605
13606 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
13607 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
13608 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
13609 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
13610];
13611
13612exports.substitute = function substitute(inL, inR) {
13613 var out = 0;
13614 for (var i = 0; i < 4; i++) {
13615 var b = (inL >>> (18 - i * 6)) & 0x3f;
13616 var sb = sTable[i * 0x40 + b];
13617
13618 out <<= 4;
13619 out |= sb;
13620 }
13621 for (var i = 0; i < 4; i++) {
13622 var b = (inR >>> (18 - i * 6)) & 0x3f;
13623 var sb = sTable[4 * 0x40 + i * 0x40 + b];
13624
13625 out <<= 4;
13626 out |= sb;
13627 }
13628 return out >>> 0;
13629};
13630
13631var permuteTable = [
13632 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
13633 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
13634];
13635
13636exports.permute = function permute(num) {
13637 var out = 0;
13638 for (var i = 0; i < permuteTable.length; i++) {
13639 out <<= 1;
13640 out |= (num >>> permuteTable[i]) & 0x1;
13641 }
13642 return out >>> 0;
13643};
13644
13645exports.padSplit = function padSplit(num, size, group) {
13646 var str = num.toString(2);
13647 while (str.length < size)
13648 str = '0' + str;
13649
13650 var out = [];
13651 for (var i = 0; i < size; i += group)
13652 out.push(str.slice(i, i + group));
13653 return out.join(' ');
13654};
13655
13656},{}],69:[function(require,module,exports){
13657(function (Buffer){
13658var generatePrime = require('./lib/generatePrime')
13659var primes = require('./lib/primes.json')
13660
13661var DH = require('./lib/dh')
13662
13663function getDiffieHellman (mod) {
13664 var prime = new Buffer(primes[mod].prime, 'hex')
13665 var gen = new Buffer(primes[mod].gen, 'hex')
13666
13667 return new DH(prime, gen)
13668}
13669
13670var ENCODINGS = {
13671 'binary': true, 'hex': true, 'base64': true
13672}
13673
13674function createDiffieHellman (prime, enc, generator, genc) {
13675 if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
13676 return createDiffieHellman(prime, 'binary', enc, generator)
13677 }
13678
13679 enc = enc || 'binary'
13680 genc = genc || 'binary'
13681 generator = generator || new Buffer([2])
13682
13683 if (!Buffer.isBuffer(generator)) {
13684 generator = new Buffer(generator, genc)
13685 }
13686
13687 if (typeof prime === 'number') {
13688 return new DH(generatePrime(prime, generator), generator, true)
13689 }
13690
13691 if (!Buffer.isBuffer(prime)) {
13692 prime = new Buffer(prime, enc)
13693 }
13694
13695 return new DH(prime, generator, true)
13696}
13697
13698exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
13699exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
13700
13701}).call(this,require("buffer").Buffer)
13702},{"./lib/dh":70,"./lib/generatePrime":71,"./lib/primes.json":72,"buffer":53}],70:[function(require,module,exports){
13703(function (Buffer){
13704var BN = require('bn.js');
13705var MillerRabin = require('miller-rabin');
13706var millerRabin = new MillerRabin();
13707var TWENTYFOUR = new BN(24);
13708var ELEVEN = new BN(11);
13709var TEN = new BN(10);
13710var THREE = new BN(3);
13711var SEVEN = new BN(7);
13712var primes = require('./generatePrime');
13713var randomBytes = require('randombytes');
13714module.exports = DH;
13715
13716function setPublicKey(pub, enc) {
13717 enc = enc || 'utf8';
13718 if (!Buffer.isBuffer(pub)) {
13719 pub = new Buffer(pub, enc);
13720 }
13721 this._pub = new BN(pub);
13722 return this;
13723}
13724
13725function setPrivateKey(priv, enc) {
13726 enc = enc || 'utf8';
13727 if (!Buffer.isBuffer(priv)) {
13728 priv = new Buffer(priv, enc);
13729 }
13730 this._priv = new BN(priv);
13731 return this;
13732}
13733
13734var primeCache = {};
13735function checkPrime(prime, generator) {
13736 var gen = generator.toString('hex');
13737 var hex = [gen, prime.toString(16)].join('_');
13738 if (hex in primeCache) {
13739 return primeCache[hex];
13740 }
13741 var error = 0;
13742
13743 if (prime.isEven() ||
13744 !primes.simpleSieve ||
13745 !primes.fermatTest(prime) ||
13746 !millerRabin.test(prime)) {
13747 //not a prime so +1
13748 error += 1;
13749
13750 if (gen === '02' || gen === '05') {
13751 // we'd be able to check the generator
13752 // it would fail so +8
13753 error += 8;
13754 } else {
13755 //we wouldn't be able to test the generator
13756 // so +4
13757 error += 4;
13758 }
13759 primeCache[hex] = error;
13760 return error;
13761 }
13762 if (!millerRabin.test(prime.shrn(1))) {
13763 //not a safe prime
13764 error += 2;
13765 }
13766 var rem;
13767 switch (gen) {
13768 case '02':
13769 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
13770 // unsuidable generator
13771 error += 8;
13772 }
13773 break;
13774 case '05':
13775 rem = prime.mod(TEN);
13776 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
13777 // prime mod 10 needs to equal 3 or 7
13778 error += 8;
13779 }
13780 break;
13781 default:
13782 error += 4;
13783 }
13784 primeCache[hex] = error;
13785 return error;
13786}
13787
13788function DH(prime, generator, malleable) {
13789 this.setGenerator(generator);
13790 this.__prime = new BN(prime);
13791 this._prime = BN.mont(this.__prime);
13792 this._primeLen = prime.length;
13793 this._pub = undefined;
13794 this._priv = undefined;
13795 this._primeCode = undefined;
13796 if (malleable) {
13797 this.setPublicKey = setPublicKey;
13798 this.setPrivateKey = setPrivateKey;
13799 } else {
13800 this._primeCode = 8;
13801 }
13802}
13803Object.defineProperty(DH.prototype, 'verifyError', {
13804 enumerable: true,
13805 get: function () {
13806 if (typeof this._primeCode !== 'number') {
13807 this._primeCode = checkPrime(this.__prime, this.__gen);
13808 }
13809 return this._primeCode;
13810 }
13811});
13812DH.prototype.generateKeys = function () {
13813 if (!this._priv) {
13814 this._priv = new BN(randomBytes(this._primeLen));
13815 }
13816 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
13817 return this.getPublicKey();
13818};
13819
13820DH.prototype.computeSecret = function (other) {
13821 other = new BN(other);
13822 other = other.toRed(this._prime);
13823 var secret = other.redPow(this._priv).fromRed();
13824 var out = new Buffer(secret.toArray());
13825 var prime = this.getPrime();
13826 if (out.length < prime.length) {
13827 var front = new Buffer(prime.length - out.length);
13828 front.fill(0);
13829 out = Buffer.concat([front, out]);
13830 }
13831 return out;
13832};
13833
13834DH.prototype.getPublicKey = function getPublicKey(enc) {
13835 return formatReturnValue(this._pub, enc);
13836};
13837
13838DH.prototype.getPrivateKey = function getPrivateKey(enc) {
13839 return formatReturnValue(this._priv, enc);
13840};
13841
13842DH.prototype.getPrime = function (enc) {
13843 return formatReturnValue(this.__prime, enc);
13844};
13845
13846DH.prototype.getGenerator = function (enc) {
13847 return formatReturnValue(this._gen, enc);
13848};
13849
13850DH.prototype.setGenerator = function (gen, enc) {
13851 enc = enc || 'utf8';
13852 if (!Buffer.isBuffer(gen)) {
13853 gen = new Buffer(gen, enc);
13854 }
13855 this.__gen = gen;
13856 this._gen = new BN(gen);
13857 return this;
13858};
13859
13860function formatReturnValue(bn, enc) {
13861 var buf = new Buffer(bn.toArray());
13862 if (!enc) {
13863 return buf;
13864 } else {
13865 return buf.toString(enc);
13866 }
13867}
13868
13869}).call(this,require("buffer").Buffer)
13870},{"./generatePrime":71,"bn.js":21,"buffer":53,"miller-rabin":119,"randombytes":140}],71:[function(require,module,exports){
13871var randomBytes = require('randombytes');
13872module.exports = findPrime;
13873findPrime.simpleSieve = simpleSieve;
13874findPrime.fermatTest = fermatTest;
13875var BN = require('bn.js');
13876var TWENTYFOUR = new BN(24);
13877var MillerRabin = require('miller-rabin');
13878var millerRabin = new MillerRabin();
13879var ONE = new BN(1);
13880var TWO = new BN(2);
13881var FIVE = new BN(5);
13882var SIXTEEN = new BN(16);
13883var EIGHT = new BN(8);
13884var TEN = new BN(10);
13885var THREE = new BN(3);
13886var SEVEN = new BN(7);
13887var ELEVEN = new BN(11);
13888var FOUR = new BN(4);
13889var TWELVE = new BN(12);
13890var primes = null;
13891
13892function _getPrimes() {
13893 if (primes !== null)
13894 return primes;
13895
13896 var limit = 0x100000;
13897 var res = [];
13898 res[0] = 2;
13899 for (var i = 1, k = 3; k < limit; k += 2) {
13900 var sqrt = Math.ceil(Math.sqrt(k));
13901 for (var j = 0; j < i && res[j] <= sqrt; j++)
13902 if (k % res[j] === 0)
13903 break;
13904
13905 if (i !== j && res[j] <= sqrt)
13906 continue;
13907
13908 res[i++] = k;
13909 }
13910 primes = res;
13911 return res;
13912}
13913
13914function simpleSieve(p) {
13915 var primes = _getPrimes();
13916
13917 for (var i = 0; i < primes.length; i++)
13918 if (p.modn(primes[i]) === 0) {
13919 if (p.cmpn(primes[i]) === 0) {
13920 return true;
13921 } else {
13922 return false;
13923 }
13924 }
13925
13926 return true;
13927}
13928
13929function fermatTest(p) {
13930 var red = BN.mont(p);
13931 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
13932}
13933
13934function findPrime(bits, gen) {
13935 if (bits < 16) {
13936 // this is what openssl does
13937 if (gen === 2 || gen === 5) {
13938 return new BN([0x8c, 0x7b]);
13939 } else {
13940 return new BN([0x8c, 0x27]);
13941 }
13942 }
13943 gen = new BN(gen);
13944
13945 var num, n2;
13946
13947 while (true) {
13948 num = new BN(randomBytes(Math.ceil(bits / 8)));
13949 while (num.bitLength() > bits) {
13950 num.ishrn(1);
13951 }
13952 if (num.isEven()) {
13953 num.iadd(ONE);
13954 }
13955 if (!num.testn(1)) {
13956 num.iadd(TWO);
13957 }
13958 if (!gen.cmp(TWO)) {
13959 while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
13960 num.iadd(FOUR);
13961 }
13962 } else if (!gen.cmp(FIVE)) {
13963 while (num.mod(TEN).cmp(THREE)) {
13964 num.iadd(FOUR);
13965 }
13966 }
13967 n2 = num.shrn(1);
13968 if (simpleSieve(n2) && simpleSieve(num) &&
13969 fermatTest(n2) && fermatTest(num) &&
13970 millerRabin.test(n2) && millerRabin.test(num)) {
13971 return num;
13972 }
13973 }
13974
13975}
13976
13977},{"bn.js":21,"miller-rabin":119,"randombytes":140}],72:[function(require,module,exports){
13978module.exports={
13979 "modp1": {
13980 "gen": "02",
13981 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
13982 },
13983 "modp2": {
13984 "gen": "02",
13985 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
13986 },
13987 "modp5": {
13988 "gen": "02",
13989 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
13990 },
13991 "modp14": {
13992 "gen": "02",
13993 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
13994 },
13995 "modp15": {
13996 "gen": "02",
13997 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
13998 },
13999 "modp16": {
14000 "gen": "02",
14001 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
14002 },
14003 "modp17": {
14004 "gen": "02",
14005 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
14006 },
14007 "modp18": {
14008 "gen": "02",
14009 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
14010 }
14011}
14012},{}],73:[function(require,module,exports){
14013'use strict';
14014
14015var elliptic = exports;
14016
14017elliptic.version = require('../package.json').version;
14018elliptic.utils = require('./elliptic/utils');
14019elliptic.rand = require('brorand');
14020elliptic.curve = require('./elliptic/curve');
14021elliptic.curves = require('./elliptic/curves');
14022
14023// Protocols
14024elliptic.ec = require('./elliptic/ec');
14025elliptic.eddsa = require('./elliptic/eddsa');
14026
14027},{"../package.json":88,"./elliptic/curve":76,"./elliptic/curves":79,"./elliptic/ec":80,"./elliptic/eddsa":83,"./elliptic/utils":87,"brorand":22}],74:[function(require,module,exports){
14028'use strict';
14029
14030var BN = require('bn.js');
14031var elliptic = require('../../elliptic');
14032var utils = elliptic.utils;
14033var getNAF = utils.getNAF;
14034var getJSF = utils.getJSF;
14035var assert = utils.assert;
14036
14037function BaseCurve(type, conf) {
14038 this.type = type;
14039 this.p = new BN(conf.p, 16);
14040
14041 // Use Montgomery, when there is no fast reduction for the prime
14042 this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
14043
14044 // Useful for many curves
14045 this.zero = new BN(0).toRed(this.red);
14046 this.one = new BN(1).toRed(this.red);
14047 this.two = new BN(2).toRed(this.red);
14048
14049 // Curve configuration, optional
14050 this.n = conf.n && new BN(conf.n, 16);
14051 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
14052
14053 // Temporary arrays
14054 this._wnafT1 = new Array(4);
14055 this._wnafT2 = new Array(4);
14056 this._wnafT3 = new Array(4);
14057 this._wnafT4 = new Array(4);
14058
14059 // Generalized Greg Maxwell's trick
14060 var adjustCount = this.n && this.p.div(this.n);
14061 if (!adjustCount || adjustCount.cmpn(100) > 0) {
14062 this.redN = null;
14063 } else {
14064 this._maxwellTrick = true;
14065 this.redN = this.n.toRed(this.red);
14066 }
14067}
14068module.exports = BaseCurve;
14069
14070BaseCurve.prototype.point = function point() {
14071 throw new Error('Not implemented');
14072};
14073
14074BaseCurve.prototype.validate = function validate() {
14075 throw new Error('Not implemented');
14076};
14077
14078BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
14079 assert(p.precomputed);
14080 var doubles = p._getDoubles();
14081
14082 var naf = getNAF(k, 1);
14083 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
14084 I /= 3;
14085
14086 // Translate into more windowed form
14087 var repr = [];
14088 for (var j = 0; j < naf.length; j += doubles.step) {
14089 var nafW = 0;
14090 for (var k = j + doubles.step - 1; k >= j; k--)
14091 nafW = (nafW << 1) + naf[k];
14092 repr.push(nafW);
14093 }
14094
14095 var a = this.jpoint(null, null, null);
14096 var b = this.jpoint(null, null, null);
14097 for (var i = I; i > 0; i--) {
14098 for (var j = 0; j < repr.length; j++) {
14099 var nafW = repr[j];
14100 if (nafW === i)
14101 b = b.mixedAdd(doubles.points[j]);
14102 else if (nafW === -i)
14103 b = b.mixedAdd(doubles.points[j].neg());
14104 }
14105 a = a.add(b);
14106 }
14107 return a.toP();
14108};
14109
14110BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
14111 var w = 4;
14112
14113 // Precompute window
14114 var nafPoints = p._getNAFPoints(w);
14115 w = nafPoints.wnd;
14116 var wnd = nafPoints.points;
14117
14118 // Get NAF form
14119 var naf = getNAF(k, w);
14120
14121 // Add `this`*(N+1) for every w-NAF index
14122 var acc = this.jpoint(null, null, null);
14123 for (var i = naf.length - 1; i >= 0; i--) {
14124 // Count zeroes
14125 for (var k = 0; i >= 0 && naf[i] === 0; i--)
14126 k++;
14127 if (i >= 0)
14128 k++;
14129 acc = acc.dblp(k);
14130
14131 if (i < 0)
14132 break;
14133 var z = naf[i];
14134 assert(z !== 0);
14135 if (p.type === 'affine') {
14136 // J +- P
14137 if (z > 0)
14138 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
14139 else
14140 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
14141 } else {
14142 // J +- J
14143 if (z > 0)
14144 acc = acc.add(wnd[(z - 1) >> 1]);
14145 else
14146 acc = acc.add(wnd[(-z - 1) >> 1].neg());
14147 }
14148 }
14149 return p.type === 'affine' ? acc.toP() : acc;
14150};
14151
14152BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
14153 points,
14154 coeffs,
14155 len,
14156 jacobianResult) {
14157 var wndWidth = this._wnafT1;
14158 var wnd = this._wnafT2;
14159 var naf = this._wnafT3;
14160
14161 // Fill all arrays
14162 var max = 0;
14163 for (var i = 0; i < len; i++) {
14164 var p = points[i];
14165 var nafPoints = p._getNAFPoints(defW);
14166 wndWidth[i] = nafPoints.wnd;
14167 wnd[i] = nafPoints.points;
14168 }
14169
14170 // Comb small window NAFs
14171 for (var i = len - 1; i >= 1; i -= 2) {
14172 var a = i - 1;
14173 var b = i;
14174 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
14175 naf[a] = getNAF(coeffs[a], wndWidth[a]);
14176 naf[b] = getNAF(coeffs[b], wndWidth[b]);
14177 max = Math.max(naf[a].length, max);
14178 max = Math.max(naf[b].length, max);
14179 continue;
14180 }
14181
14182 var comb = [
14183 points[a], /* 1 */
14184 null, /* 3 */
14185 null, /* 5 */
14186 points[b] /* 7 */
14187 ];
14188
14189 // Try to avoid Projective points, if possible
14190 if (points[a].y.cmp(points[b].y) === 0) {
14191 comb[1] = points[a].add(points[b]);
14192 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
14193 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
14194 comb[1] = points[a].toJ().mixedAdd(points[b]);
14195 comb[2] = points[a].add(points[b].neg());
14196 } else {
14197 comb[1] = points[a].toJ().mixedAdd(points[b]);
14198 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
14199 }
14200
14201 var index = [
14202 -3, /* -1 -1 */
14203 -1, /* -1 0 */
14204 -5, /* -1 1 */
14205 -7, /* 0 -1 */
14206 0, /* 0 0 */
14207 7, /* 0 1 */
14208 5, /* 1 -1 */
14209 1, /* 1 0 */
14210 3 /* 1 1 */
14211 ];
14212
14213 var jsf = getJSF(coeffs[a], coeffs[b]);
14214 max = Math.max(jsf[0].length, max);
14215 naf[a] = new Array(max);
14216 naf[b] = new Array(max);
14217 for (var j = 0; j < max; j++) {
14218 var ja = jsf[0][j] | 0;
14219 var jb = jsf[1][j] | 0;
14220
14221 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
14222 naf[b][j] = 0;
14223 wnd[a] = comb;
14224 }
14225 }
14226
14227 var acc = this.jpoint(null, null, null);
14228 var tmp = this._wnafT4;
14229 for (var i = max; i >= 0; i--) {
14230 var k = 0;
14231
14232 while (i >= 0) {
14233 var zero = true;
14234 for (var j = 0; j < len; j++) {
14235 tmp[j] = naf[j][i] | 0;
14236 if (tmp[j] !== 0)
14237 zero = false;
14238 }
14239 if (!zero)
14240 break;
14241 k++;
14242 i--;
14243 }
14244 if (i >= 0)
14245 k++;
14246 acc = acc.dblp(k);
14247 if (i < 0)
14248 break;
14249
14250 for (var j = 0; j < len; j++) {
14251 var z = tmp[j];
14252 var p;
14253 if (z === 0)
14254 continue;
14255 else if (z > 0)
14256 p = wnd[j][(z - 1) >> 1];
14257 else if (z < 0)
14258 p = wnd[j][(-z - 1) >> 1].neg();
14259
14260 if (p.type === 'affine')
14261 acc = acc.mixedAdd(p);
14262 else
14263 acc = acc.add(p);
14264 }
14265 }
14266 // Zeroify references
14267 for (var i = 0; i < len; i++)
14268 wnd[i] = null;
14269
14270 if (jacobianResult)
14271 return acc;
14272 else
14273 return acc.toP();
14274};
14275
14276function BasePoint(curve, type) {
14277 this.curve = curve;
14278 this.type = type;
14279 this.precomputed = null;
14280}
14281BaseCurve.BasePoint = BasePoint;
14282
14283BasePoint.prototype.eq = function eq(/*other*/) {
14284 throw new Error('Not implemented');
14285};
14286
14287BasePoint.prototype.validate = function validate() {
14288 return this.curve.validate(this);
14289};
14290
14291BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
14292 bytes = utils.toArray(bytes, enc);
14293
14294 var len = this.p.byteLength();
14295
14296 // uncompressed, hybrid-odd, hybrid-even
14297 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
14298 bytes.length - 1 === 2 * len) {
14299 if (bytes[0] === 0x06)
14300 assert(bytes[bytes.length - 1] % 2 === 0);
14301 else if (bytes[0] === 0x07)
14302 assert(bytes[bytes.length - 1] % 2 === 1);
14303
14304 var res = this.point(bytes.slice(1, 1 + len),
14305 bytes.slice(1 + len, 1 + 2 * len));
14306
14307 return res;
14308 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
14309 bytes.length - 1 === len) {
14310 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
14311 }
14312 throw new Error('Unknown point format');
14313};
14314
14315BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
14316 return this.encode(enc, true);
14317};
14318
14319BasePoint.prototype._encode = function _encode(compact) {
14320 var len = this.curve.p.byteLength();
14321 var x = this.getX().toArray('be', len);
14322
14323 if (compact)
14324 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
14325
14326 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
14327};
14328
14329BasePoint.prototype.encode = function encode(enc, compact) {
14330 return utils.encode(this._encode(compact), enc);
14331};
14332
14333BasePoint.prototype.precompute = function precompute(power) {
14334 if (this.precomputed)
14335 return this;
14336
14337 var precomputed = {
14338 doubles: null,
14339 naf: null,
14340 beta: null
14341 };
14342 precomputed.naf = this._getNAFPoints(8);
14343 precomputed.doubles = this._getDoubles(4, power);
14344 precomputed.beta = this._getBeta();
14345 this.precomputed = precomputed;
14346
14347 return this;
14348};
14349
14350BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
14351 if (!this.precomputed)
14352 return false;
14353
14354 var doubles = this.precomputed.doubles;
14355 if (!doubles)
14356 return false;
14357
14358 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
14359};
14360
14361BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
14362 if (this.precomputed && this.precomputed.doubles)
14363 return this.precomputed.doubles;
14364
14365 var doubles = [ this ];
14366 var acc = this;
14367 for (var i = 0; i < power; i += step) {
14368 for (var j = 0; j < step; j++)
14369 acc = acc.dbl();
14370 doubles.push(acc);
14371 }
14372 return {
14373 step: step,
14374 points: doubles
14375 };
14376};
14377
14378BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
14379 if (this.precomputed && this.precomputed.naf)
14380 return this.precomputed.naf;
14381
14382 var res = [ this ];
14383 var max = (1 << wnd) - 1;
14384 var dbl = max === 1 ? null : this.dbl();
14385 for (var i = 1; i < max; i++)
14386 res[i] = res[i - 1].add(dbl);
14387 return {
14388 wnd: wnd,
14389 points: res
14390 };
14391};
14392
14393BasePoint.prototype._getBeta = function _getBeta() {
14394 return null;
14395};
14396
14397BasePoint.prototype.dblp = function dblp(k) {
14398 var r = this;
14399 for (var i = 0; i < k; i++)
14400 r = r.dbl();
14401 return r;
14402};
14403
14404},{"../../elliptic":73,"bn.js":21}],75:[function(require,module,exports){
14405'use strict';
14406
14407var curve = require('../curve');
14408var elliptic = require('../../elliptic');
14409var BN = require('bn.js');
14410var inherits = require('inherits');
14411var Base = curve.base;
14412
14413var assert = elliptic.utils.assert;
14414
14415function EdwardsCurve(conf) {
14416 // NOTE: Important as we are creating point in Base.call()
14417 this.twisted = (conf.a | 0) !== 1;
14418 this.mOneA = this.twisted && (conf.a | 0) === -1;
14419 this.extended = this.mOneA;
14420
14421 Base.call(this, 'edwards', conf);
14422
14423 this.a = new BN(conf.a, 16).umod(this.red.m);
14424 this.a = this.a.toRed(this.red);
14425 this.c = new BN(conf.c, 16).toRed(this.red);
14426 this.c2 = this.c.redSqr();
14427 this.d = new BN(conf.d, 16).toRed(this.red);
14428 this.dd = this.d.redAdd(this.d);
14429
14430 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
14431 this.oneC = (conf.c | 0) === 1;
14432}
14433inherits(EdwardsCurve, Base);
14434module.exports = EdwardsCurve;
14435
14436EdwardsCurve.prototype._mulA = function _mulA(num) {
14437 if (this.mOneA)
14438 return num.redNeg();
14439 else
14440 return this.a.redMul(num);
14441};
14442
14443EdwardsCurve.prototype._mulC = function _mulC(num) {
14444 if (this.oneC)
14445 return num;
14446 else
14447 return this.c.redMul(num);
14448};
14449
14450// Just for compatibility with Short curve
14451EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
14452 return this.point(x, y, z, t);
14453};
14454
14455EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
14456 x = new BN(x, 16);
14457 if (!x.red)
14458 x = x.toRed(this.red);
14459
14460 var x2 = x.redSqr();
14461 var rhs = this.c2.redSub(this.a.redMul(x2));
14462 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
14463
14464 var y2 = rhs.redMul(lhs.redInvm());
14465 var y = y2.redSqrt();
14466 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
14467 throw new Error('invalid point');
14468
14469 var isOdd = y.fromRed().isOdd();
14470 if (odd && !isOdd || !odd && isOdd)
14471 y = y.redNeg();
14472
14473 return this.point(x, y);
14474};
14475
14476EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
14477 y = new BN(y, 16);
14478 if (!y.red)
14479 y = y.toRed(this.red);
14480
14481 // x^2 = (y^2 - 1) / (d y^2 + 1)
14482 var y2 = y.redSqr();
14483 var lhs = y2.redSub(this.one);
14484 var rhs = y2.redMul(this.d).redAdd(this.one);
14485 var x2 = lhs.redMul(rhs.redInvm());
14486
14487 if (x2.cmp(this.zero) === 0) {
14488 if (odd)
14489 throw new Error('invalid point');
14490 else
14491 return this.point(this.zero, y);
14492 }
14493
14494 var x = x2.redSqrt();
14495 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
14496 throw new Error('invalid point');
14497
14498 if (x.isOdd() !== odd)
14499 x = x.redNeg();
14500
14501 return this.point(x, y);
14502};
14503
14504EdwardsCurve.prototype.validate = function validate(point) {
14505 if (point.isInfinity())
14506 return true;
14507
14508 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
14509 point.normalize();
14510
14511 var x2 = point.x.redSqr();
14512 var y2 = point.y.redSqr();
14513 var lhs = x2.redMul(this.a).redAdd(y2);
14514 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
14515
14516 return lhs.cmp(rhs) === 0;
14517};
14518
14519function Point(curve, x, y, z, t) {
14520 Base.BasePoint.call(this, curve, 'projective');
14521 if (x === null && y === null && z === null) {
14522 this.x = this.curve.zero;
14523 this.y = this.curve.one;
14524 this.z = this.curve.one;
14525 this.t = this.curve.zero;
14526 this.zOne = true;
14527 } else {
14528 this.x = new BN(x, 16);
14529 this.y = new BN(y, 16);
14530 this.z = z ? new BN(z, 16) : this.curve.one;
14531 this.t = t && new BN(t, 16);
14532 if (!this.x.red)
14533 this.x = this.x.toRed(this.curve.red);
14534 if (!this.y.red)
14535 this.y = this.y.toRed(this.curve.red);
14536 if (!this.z.red)
14537 this.z = this.z.toRed(this.curve.red);
14538 if (this.t && !this.t.red)
14539 this.t = this.t.toRed(this.curve.red);
14540 this.zOne = this.z === this.curve.one;
14541
14542 // Use extended coordinates
14543 if (this.curve.extended && !this.t) {
14544 this.t = this.x.redMul(this.y);
14545 if (!this.zOne)
14546 this.t = this.t.redMul(this.z.redInvm());
14547 }
14548 }
14549}
14550inherits(Point, Base.BasePoint);
14551
14552EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
14553 return Point.fromJSON(this, obj);
14554};
14555
14556EdwardsCurve.prototype.point = function point(x, y, z, t) {
14557 return new Point(this, x, y, z, t);
14558};
14559
14560Point.fromJSON = function fromJSON(curve, obj) {
14561 return new Point(curve, obj[0], obj[1], obj[2]);
14562};
14563
14564Point.prototype.inspect = function inspect() {
14565 if (this.isInfinity())
14566 return '<EC Point Infinity>';
14567 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
14568 ' y: ' + this.y.fromRed().toString(16, 2) +
14569 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
14570};
14571
14572Point.prototype.isInfinity = function isInfinity() {
14573 // XXX This code assumes that zero is always zero in red
14574 return this.x.cmpn(0) === 0 &&
14575 this.y.cmp(this.z) === 0;
14576};
14577
14578Point.prototype._extDbl = function _extDbl() {
14579 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
14580 // #doubling-dbl-2008-hwcd
14581 // 4M + 4S
14582
14583 // A = X1^2
14584 var a = this.x.redSqr();
14585 // B = Y1^2
14586 var b = this.y.redSqr();
14587 // C = 2 * Z1^2
14588 var c = this.z.redSqr();
14589 c = c.redIAdd(c);
14590 // D = a * A
14591 var d = this.curve._mulA(a);
14592 // E = (X1 + Y1)^2 - A - B
14593 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
14594 // G = D + B
14595 var g = d.redAdd(b);
14596 // F = G - C
14597 var f = g.redSub(c);
14598 // H = D - B
14599 var h = d.redSub(b);
14600 // X3 = E * F
14601 var nx = e.redMul(f);
14602 // Y3 = G * H
14603 var ny = g.redMul(h);
14604 // T3 = E * H
14605 var nt = e.redMul(h);
14606 // Z3 = F * G
14607 var nz = f.redMul(g);
14608 return this.curve.point(nx, ny, nz, nt);
14609};
14610
14611Point.prototype._projDbl = function _projDbl() {
14612 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
14613 // #doubling-dbl-2008-bbjlp
14614 // #doubling-dbl-2007-bl
14615 // and others
14616 // Generally 3M + 4S or 2M + 4S
14617
14618 // B = (X1 + Y1)^2
14619 var b = this.x.redAdd(this.y).redSqr();
14620 // C = X1^2
14621 var c = this.x.redSqr();
14622 // D = Y1^2
14623 var d = this.y.redSqr();
14624
14625 var nx;
14626 var ny;
14627 var nz;
14628 if (this.curve.twisted) {
14629 // E = a * C
14630 var e = this.curve._mulA(c);
14631 // F = E + D
14632 var f = e.redAdd(d);
14633 if (this.zOne) {
14634 // X3 = (B - C - D) * (F - 2)
14635 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
14636 // Y3 = F * (E - D)
14637 ny = f.redMul(e.redSub(d));
14638 // Z3 = F^2 - 2 * F
14639 nz = f.redSqr().redSub(f).redSub(f);
14640 } else {
14641 // H = Z1^2
14642 var h = this.z.redSqr();
14643 // J = F - 2 * H
14644 var j = f.redSub(h).redISub(h);
14645 // X3 = (B-C-D)*J
14646 nx = b.redSub(c).redISub(d).redMul(j);
14647 // Y3 = F * (E - D)
14648 ny = f.redMul(e.redSub(d));
14649 // Z3 = F * J
14650 nz = f.redMul(j);
14651 }
14652 } else {
14653 // E = C + D
14654 var e = c.redAdd(d);
14655 // H = (c * Z1)^2
14656 var h = this.curve._mulC(this.c.redMul(this.z)).redSqr();
14657 // J = E - 2 * H
14658 var j = e.redSub(h).redSub(h);
14659 // X3 = c * (B - E) * J
14660 nx = this.curve._mulC(b.redISub(e)).redMul(j);
14661 // Y3 = c * E * (C - D)
14662 ny = this.curve._mulC(e).redMul(c.redISub(d));
14663 // Z3 = E * J
14664 nz = e.redMul(j);
14665 }
14666 return this.curve.point(nx, ny, nz);
14667};
14668
14669Point.prototype.dbl = function dbl() {
14670 if (this.isInfinity())
14671 return this;
14672
14673 // Double in extended coordinates
14674 if (this.curve.extended)
14675 return this._extDbl();
14676 else
14677 return this._projDbl();
14678};
14679
14680Point.prototype._extAdd = function _extAdd(p) {
14681 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
14682 // #addition-add-2008-hwcd-3
14683 // 8M
14684
14685 // A = (Y1 - X1) * (Y2 - X2)
14686 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
14687 // B = (Y1 + X1) * (Y2 + X2)
14688 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
14689 // C = T1 * k * T2
14690 var c = this.t.redMul(this.curve.dd).redMul(p.t);
14691 // D = Z1 * 2 * Z2
14692 var d = this.z.redMul(p.z.redAdd(p.z));
14693 // E = B - A
14694 var e = b.redSub(a);
14695 // F = D - C
14696 var f = d.redSub(c);
14697 // G = D + C
14698 var g = d.redAdd(c);
14699 // H = B + A
14700 var h = b.redAdd(a);
14701 // X3 = E * F
14702 var nx = e.redMul(f);
14703 // Y3 = G * H
14704 var ny = g.redMul(h);
14705 // T3 = E * H
14706 var nt = e.redMul(h);
14707 // Z3 = F * G
14708 var nz = f.redMul(g);
14709 return this.curve.point(nx, ny, nz, nt);
14710};
14711
14712Point.prototype._projAdd = function _projAdd(p) {
14713 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
14714 // #addition-add-2008-bbjlp
14715 // #addition-add-2007-bl
14716 // 10M + 1S
14717
14718 // A = Z1 * Z2
14719 var a = this.z.redMul(p.z);
14720 // B = A^2
14721 var b = a.redSqr();
14722 // C = X1 * X2
14723 var c = this.x.redMul(p.x);
14724 // D = Y1 * Y2
14725 var d = this.y.redMul(p.y);
14726 // E = d * C * D
14727 var e = this.curve.d.redMul(c).redMul(d);
14728 // F = B - E
14729 var f = b.redSub(e);
14730 // G = B + E
14731 var g = b.redAdd(e);
14732 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
14733 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
14734 var nx = a.redMul(f).redMul(tmp);
14735 var ny;
14736 var nz;
14737 if (this.curve.twisted) {
14738 // Y3 = A * G * (D - a * C)
14739 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
14740 // Z3 = F * G
14741 nz = f.redMul(g);
14742 } else {
14743 // Y3 = A * G * (D - C)
14744 ny = a.redMul(g).redMul(d.redSub(c));
14745 // Z3 = c * F * G
14746 nz = this.curve._mulC(f).redMul(g);
14747 }
14748 return this.curve.point(nx, ny, nz);
14749};
14750
14751Point.prototype.add = function add(p) {
14752 if (this.isInfinity())
14753 return p;
14754 if (p.isInfinity())
14755 return this;
14756
14757 if (this.curve.extended)
14758 return this._extAdd(p);
14759 else
14760 return this._projAdd(p);
14761};
14762
14763Point.prototype.mul = function mul(k) {
14764 if (this._hasDoubles(k))
14765 return this.curve._fixedNafMul(this, k);
14766 else
14767 return this.curve._wnafMul(this, k);
14768};
14769
14770Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
14771 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
14772};
14773
14774Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
14775 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
14776};
14777
14778Point.prototype.normalize = function normalize() {
14779 if (this.zOne)
14780 return this;
14781
14782 // Normalize coordinates
14783 var zi = this.z.redInvm();
14784 this.x = this.x.redMul(zi);
14785 this.y = this.y.redMul(zi);
14786 if (this.t)
14787 this.t = this.t.redMul(zi);
14788 this.z = this.curve.one;
14789 this.zOne = true;
14790 return this;
14791};
14792
14793Point.prototype.neg = function neg() {
14794 return this.curve.point(this.x.redNeg(),
14795 this.y,
14796 this.z,
14797 this.t && this.t.redNeg());
14798};
14799
14800Point.prototype.getX = function getX() {
14801 this.normalize();
14802 return this.x.fromRed();
14803};
14804
14805Point.prototype.getY = function getY() {
14806 this.normalize();
14807 return this.y.fromRed();
14808};
14809
14810Point.prototype.eq = function eq(other) {
14811 return this === other ||
14812 this.getX().cmp(other.getX()) === 0 &&
14813 this.getY().cmp(other.getY()) === 0;
14814};
14815
14816Point.prototype.eqXToP = function eqXToP(x) {
14817 var rx = x.toRed(this.curve.red).redMul(this.z);
14818 if (this.x.cmp(rx) === 0)
14819 return true;
14820
14821 var xc = x.clone();
14822 var t = this.curve.redN.redMul(this.z);
14823 for (;;) {
14824 xc.iadd(this.curve.n);
14825 if (xc.cmp(this.curve.p) >= 0)
14826 return false;
14827
14828 rx.redIAdd(t);
14829 if (this.x.cmp(rx) === 0)
14830 return true;
14831 }
14832 return false;
14833};
14834
14835// Compatibility with BaseCurve
14836Point.prototype.toP = Point.prototype.normalize;
14837Point.prototype.mixedAdd = Point.prototype.add;
14838
14839},{"../../elliptic":73,"../curve":76,"bn.js":21,"inherits":107}],76:[function(require,module,exports){
14840'use strict';
14841
14842var curve = exports;
14843
14844curve.base = require('./base');
14845curve.short = require('./short');
14846curve.mont = require('./mont');
14847curve.edwards = require('./edwards');
14848
14849},{"./base":74,"./edwards":75,"./mont":77,"./short":78}],77:[function(require,module,exports){
14850'use strict';
14851
14852var curve = require('../curve');
14853var BN = require('bn.js');
14854var inherits = require('inherits');
14855var Base = curve.base;
14856
14857var elliptic = require('../../elliptic');
14858var utils = elliptic.utils;
14859
14860function MontCurve(conf) {
14861 Base.call(this, 'mont', conf);
14862
14863 this.a = new BN(conf.a, 16).toRed(this.red);
14864 this.b = new BN(conf.b, 16).toRed(this.red);
14865 this.i4 = new BN(4).toRed(this.red).redInvm();
14866 this.two = new BN(2).toRed(this.red);
14867 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
14868}
14869inherits(MontCurve, Base);
14870module.exports = MontCurve;
14871
14872MontCurve.prototype.validate = function validate(point) {
14873 var x = point.normalize().x;
14874 var x2 = x.redSqr();
14875 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
14876 var y = rhs.redSqrt();
14877
14878 return y.redSqr().cmp(rhs) === 0;
14879};
14880
14881function Point(curve, x, z) {
14882 Base.BasePoint.call(this, curve, 'projective');
14883 if (x === null && z === null) {
14884 this.x = this.curve.one;
14885 this.z = this.curve.zero;
14886 } else {
14887 this.x = new BN(x, 16);
14888 this.z = new BN(z, 16);
14889 if (!this.x.red)
14890 this.x = this.x.toRed(this.curve.red);
14891 if (!this.z.red)
14892 this.z = this.z.toRed(this.curve.red);
14893 }
14894}
14895inherits(Point, Base.BasePoint);
14896
14897MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
14898 return this.point(utils.toArray(bytes, enc), 1);
14899};
14900
14901MontCurve.prototype.point = function point(x, z) {
14902 return new Point(this, x, z);
14903};
14904
14905MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
14906 return Point.fromJSON(this, obj);
14907};
14908
14909Point.prototype.precompute = function precompute() {
14910 // No-op
14911};
14912
14913Point.prototype._encode = function _encode() {
14914 return this.getX().toArray('be', this.curve.p.byteLength());
14915};
14916
14917Point.fromJSON = function fromJSON(curve, obj) {
14918 return new Point(curve, obj[0], obj[1] || curve.one);
14919};
14920
14921Point.prototype.inspect = function inspect() {
14922 if (this.isInfinity())
14923 return '<EC Point Infinity>';
14924 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
14925 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
14926};
14927
14928Point.prototype.isInfinity = function isInfinity() {
14929 // XXX This code assumes that zero is always zero in red
14930 return this.z.cmpn(0) === 0;
14931};
14932
14933Point.prototype.dbl = function dbl() {
14934 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
14935 // 2M + 2S + 4A
14936
14937 // A = X1 + Z1
14938 var a = this.x.redAdd(this.z);
14939 // AA = A^2
14940 var aa = a.redSqr();
14941 // B = X1 - Z1
14942 var b = this.x.redSub(this.z);
14943 // BB = B^2
14944 var bb = b.redSqr();
14945 // C = AA - BB
14946 var c = aa.redSub(bb);
14947 // X3 = AA * BB
14948 var nx = aa.redMul(bb);
14949 // Z3 = C * (BB + A24 * C)
14950 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
14951 return this.curve.point(nx, nz);
14952};
14953
14954Point.prototype.add = function add() {
14955 throw new Error('Not supported on Montgomery curve');
14956};
14957
14958Point.prototype.diffAdd = function diffAdd(p, diff) {
14959 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
14960 // 4M + 2S + 6A
14961
14962 // A = X2 + Z2
14963 var a = this.x.redAdd(this.z);
14964 // B = X2 - Z2
14965 var b = this.x.redSub(this.z);
14966 // C = X3 + Z3
14967 var c = p.x.redAdd(p.z);
14968 // D = X3 - Z3
14969 var d = p.x.redSub(p.z);
14970 // DA = D * A
14971 var da = d.redMul(a);
14972 // CB = C * B
14973 var cb = c.redMul(b);
14974 // X5 = Z1 * (DA + CB)^2
14975 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
14976 // Z5 = X1 * (DA - CB)^2
14977 var nz = diff.x.redMul(da.redISub(cb).redSqr());
14978 return this.curve.point(nx, nz);
14979};
14980
14981Point.prototype.mul = function mul(k) {
14982 var t = k.clone();
14983 var a = this; // (N / 2) * Q + Q
14984 var b = this.curve.point(null, null); // (N / 2) * Q
14985 var c = this; // Q
14986
14987 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
14988 bits.push(t.andln(1));
14989
14990 for (var i = bits.length - 1; i >= 0; i--) {
14991 if (bits[i] === 0) {
14992 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
14993 a = a.diffAdd(b, c);
14994 // N * Q = 2 * ((N / 2) * Q + Q))
14995 b = b.dbl();
14996 } else {
14997 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
14998 b = a.diffAdd(b, c);
14999 // N * Q + Q = 2 * ((N / 2) * Q + Q)
15000 a = a.dbl();
15001 }
15002 }
15003 return b;
15004};
15005
15006Point.prototype.mulAdd = function mulAdd() {
15007 throw new Error('Not supported on Montgomery curve');
15008};
15009
15010Point.prototype.jumlAdd = function jumlAdd() {
15011 throw new Error('Not supported on Montgomery curve');
15012};
15013
15014Point.prototype.eq = function eq(other) {
15015 return this.getX().cmp(other.getX()) === 0;
15016};
15017
15018Point.prototype.normalize = function normalize() {
15019 this.x = this.x.redMul(this.z.redInvm());
15020 this.z = this.curve.one;
15021 return this;
15022};
15023
15024Point.prototype.getX = function getX() {
15025 // Normalize coordinates
15026 this.normalize();
15027
15028 return this.x.fromRed();
15029};
15030
15031},{"../../elliptic":73,"../curve":76,"bn.js":21,"inherits":107}],78:[function(require,module,exports){
15032'use strict';
15033
15034var curve = require('../curve');
15035var elliptic = require('../../elliptic');
15036var BN = require('bn.js');
15037var inherits = require('inherits');
15038var Base = curve.base;
15039
15040var assert = elliptic.utils.assert;
15041
15042function ShortCurve(conf) {
15043 Base.call(this, 'short', conf);
15044
15045 this.a = new BN(conf.a, 16).toRed(this.red);
15046 this.b = new BN(conf.b, 16).toRed(this.red);
15047 this.tinv = this.two.redInvm();
15048
15049 this.zeroA = this.a.fromRed().cmpn(0) === 0;
15050 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
15051
15052 // If the curve is endomorphic, precalculate beta and lambda
15053 this.endo = this._getEndomorphism(conf);
15054 this._endoWnafT1 = new Array(4);
15055 this._endoWnafT2 = new Array(4);
15056}
15057inherits(ShortCurve, Base);
15058module.exports = ShortCurve;
15059
15060ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
15061 // No efficient endomorphism
15062 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
15063 return;
15064
15065 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
15066 var beta;
15067 var lambda;
15068 if (conf.beta) {
15069 beta = new BN(conf.beta, 16).toRed(this.red);
15070 } else {
15071 var betas = this._getEndoRoots(this.p);
15072 // Choose the smallest beta
15073 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
15074 beta = beta.toRed(this.red);
15075 }
15076 if (conf.lambda) {
15077 lambda = new BN(conf.lambda, 16);
15078 } else {
15079 // Choose the lambda that is matching selected beta
15080 var lambdas = this._getEndoRoots(this.n);
15081 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
15082 lambda = lambdas[0];
15083 } else {
15084 lambda = lambdas[1];
15085 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
15086 }
15087 }
15088
15089 // Get basis vectors, used for balanced length-two representation
15090 var basis;
15091 if (conf.basis) {
15092 basis = conf.basis.map(function(vec) {
15093 return {
15094 a: new BN(vec.a, 16),
15095 b: new BN(vec.b, 16)
15096 };
15097 });
15098 } else {
15099 basis = this._getEndoBasis(lambda);
15100 }
15101
15102 return {
15103 beta: beta,
15104 lambda: lambda,
15105 basis: basis
15106 };
15107};
15108
15109ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
15110 // Find roots of for x^2 + x + 1 in F
15111 // Root = (-1 +- Sqrt(-3)) / 2
15112 //
15113 var red = num === this.p ? this.red : BN.mont(num);
15114 var tinv = new BN(2).toRed(red).redInvm();
15115 var ntinv = tinv.redNeg();
15116
15117 var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
15118
15119 var l1 = ntinv.redAdd(s).fromRed();
15120 var l2 = ntinv.redSub(s).fromRed();
15121 return [ l1, l2 ];
15122};
15123
15124ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
15125 // aprxSqrt >= sqrt(this.n)
15126 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
15127
15128 // 3.74
15129 // Run EGCD, until r(L + 1) < aprxSqrt
15130 var u = lambda;
15131 var v = this.n.clone();
15132 var x1 = new BN(1);
15133 var y1 = new BN(0);
15134 var x2 = new BN(0);
15135 var y2 = new BN(1);
15136
15137 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
15138 var a0;
15139 var b0;
15140 // First vector
15141 var a1;
15142 var b1;
15143 // Second vector
15144 var a2;
15145 var b2;
15146
15147 var prevR;
15148 var i = 0;
15149 var r;
15150 var x;
15151 while (u.cmpn(0) !== 0) {
15152 var q = v.div(u);
15153 r = v.sub(q.mul(u));
15154 x = x2.sub(q.mul(x1));
15155 var y = y2.sub(q.mul(y1));
15156
15157 if (!a1 && r.cmp(aprxSqrt) < 0) {
15158 a0 = prevR.neg();
15159 b0 = x1;
15160 a1 = r.neg();
15161 b1 = x;
15162 } else if (a1 && ++i === 2) {
15163 break;
15164 }
15165 prevR = r;
15166
15167 v = u;
15168 u = r;
15169 x2 = x1;
15170 x1 = x;
15171 y2 = y1;
15172 y1 = y;
15173 }
15174 a2 = r.neg();
15175 b2 = x;
15176
15177 var len1 = a1.sqr().add(b1.sqr());
15178 var len2 = a2.sqr().add(b2.sqr());
15179 if (len2.cmp(len1) >= 0) {
15180 a2 = a0;
15181 b2 = b0;
15182 }
15183
15184 // Normalize signs
15185 if (a1.negative) {
15186 a1 = a1.neg();
15187 b1 = b1.neg();
15188 }
15189 if (a2.negative) {
15190 a2 = a2.neg();
15191 b2 = b2.neg();
15192 }
15193
15194 return [
15195 { a: a1, b: b1 },
15196 { a: a2, b: b2 }
15197 ];
15198};
15199
15200ShortCurve.prototype._endoSplit = function _endoSplit(k) {
15201 var basis = this.endo.basis;
15202 var v1 = basis[0];
15203 var v2 = basis[1];
15204
15205 var c1 = v2.b.mul(k).divRound(this.n);
15206 var c2 = v1.b.neg().mul(k).divRound(this.n);
15207
15208 var p1 = c1.mul(v1.a);
15209 var p2 = c2.mul(v2.a);
15210 var q1 = c1.mul(v1.b);
15211 var q2 = c2.mul(v2.b);
15212
15213 // Calculate answer
15214 var k1 = k.sub(p1).sub(p2);
15215 var k2 = q1.add(q2).neg();
15216 return { k1: k1, k2: k2 };
15217};
15218
15219ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
15220 x = new BN(x, 16);
15221 if (!x.red)
15222 x = x.toRed(this.red);
15223
15224 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
15225 var y = y2.redSqrt();
15226 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
15227 throw new Error('invalid point');
15228
15229 // XXX Is there any way to tell if the number is odd without converting it
15230 // to non-red form?
15231 var isOdd = y.fromRed().isOdd();
15232 if (odd && !isOdd || !odd && isOdd)
15233 y = y.redNeg();
15234
15235 return this.point(x, y);
15236};
15237
15238ShortCurve.prototype.validate = function validate(point) {
15239 if (point.inf)
15240 return true;
15241
15242 var x = point.x;
15243 var y = point.y;
15244
15245 var ax = this.a.redMul(x);
15246 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
15247 return y.redSqr().redISub(rhs).cmpn(0) === 0;
15248};
15249
15250ShortCurve.prototype._endoWnafMulAdd =
15251 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
15252 var npoints = this._endoWnafT1;
15253 var ncoeffs = this._endoWnafT2;
15254 for (var i = 0; i < points.length; i++) {
15255 var split = this._endoSplit(coeffs[i]);
15256 var p = points[i];
15257 var beta = p._getBeta();
15258
15259 if (split.k1.negative) {
15260 split.k1.ineg();
15261 p = p.neg(true);
15262 }
15263 if (split.k2.negative) {
15264 split.k2.ineg();
15265 beta = beta.neg(true);
15266 }
15267
15268 npoints[i * 2] = p;
15269 npoints[i * 2 + 1] = beta;
15270 ncoeffs[i * 2] = split.k1;
15271 ncoeffs[i * 2 + 1] = split.k2;
15272 }
15273 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
15274
15275 // Clean-up references to points and coefficients
15276 for (var j = 0; j < i * 2; j++) {
15277 npoints[j] = null;
15278 ncoeffs[j] = null;
15279 }
15280 return res;
15281};
15282
15283function Point(curve, x, y, isRed) {
15284 Base.BasePoint.call(this, curve, 'affine');
15285 if (x === null && y === null) {
15286 this.x = null;
15287 this.y = null;
15288 this.inf = true;
15289 } else {
15290 this.x = new BN(x, 16);
15291 this.y = new BN(y, 16);
15292 // Force redgomery representation when loading from JSON
15293 if (isRed) {
15294 this.x.forceRed(this.curve.red);
15295 this.y.forceRed(this.curve.red);
15296 }
15297 if (!this.x.red)
15298 this.x = this.x.toRed(this.curve.red);
15299 if (!this.y.red)
15300 this.y = this.y.toRed(this.curve.red);
15301 this.inf = false;
15302 }
15303}
15304inherits(Point, Base.BasePoint);
15305
15306ShortCurve.prototype.point = function point(x, y, isRed) {
15307 return new Point(this, x, y, isRed);
15308};
15309
15310ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
15311 return Point.fromJSON(this, obj, red);
15312};
15313
15314Point.prototype._getBeta = function _getBeta() {
15315 if (!this.curve.endo)
15316 return;
15317
15318 var pre = this.precomputed;
15319 if (pre && pre.beta)
15320 return pre.beta;
15321
15322 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
15323 if (pre) {
15324 var curve = this.curve;
15325 var endoMul = function(p) {
15326 return curve.point(p.x.redMul(curve.endo.beta), p.y);
15327 };
15328 pre.beta = beta;
15329 beta.precomputed = {
15330 beta: null,
15331 naf: pre.naf && {
15332 wnd: pre.naf.wnd,
15333 points: pre.naf.points.map(endoMul)
15334 },
15335 doubles: pre.doubles && {
15336 step: pre.doubles.step,
15337 points: pre.doubles.points.map(endoMul)
15338 }
15339 };
15340 }
15341 return beta;
15342};
15343
15344Point.prototype.toJSON = function toJSON() {
15345 if (!this.precomputed)
15346 return [ this.x, this.y ];
15347
15348 return [ this.x, this.y, this.precomputed && {
15349 doubles: this.precomputed.doubles && {
15350 step: this.precomputed.doubles.step,
15351 points: this.precomputed.doubles.points.slice(1)
15352 },
15353 naf: this.precomputed.naf && {
15354 wnd: this.precomputed.naf.wnd,
15355 points: this.precomputed.naf.points.slice(1)
15356 }
15357 } ];
15358};
15359
15360Point.fromJSON = function fromJSON(curve, obj, red) {
15361 if (typeof obj === 'string')
15362 obj = JSON.parse(obj);
15363 var res = curve.point(obj[0], obj[1], red);
15364 if (!obj[2])
15365 return res;
15366
15367 function obj2point(obj) {
15368 return curve.point(obj[0], obj[1], red);
15369 }
15370
15371 var pre = obj[2];
15372 res.precomputed = {
15373 beta: null,
15374 doubles: pre.doubles && {
15375 step: pre.doubles.step,
15376 points: [ res ].concat(pre.doubles.points.map(obj2point))
15377 },
15378 naf: pre.naf && {
15379 wnd: pre.naf.wnd,
15380 points: [ res ].concat(pre.naf.points.map(obj2point))
15381 }
15382 };
15383 return res;
15384};
15385
15386Point.prototype.inspect = function inspect() {
15387 if (this.isInfinity())
15388 return '<EC Point Infinity>';
15389 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
15390 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
15391};
15392
15393Point.prototype.isInfinity = function isInfinity() {
15394 return this.inf;
15395};
15396
15397Point.prototype.add = function add(p) {
15398 // O + P = P
15399 if (this.inf)
15400 return p;
15401
15402 // P + O = P
15403 if (p.inf)
15404 return this;
15405
15406 // P + P = 2P
15407 if (this.eq(p))
15408 return this.dbl();
15409
15410 // P + (-P) = O
15411 if (this.neg().eq(p))
15412 return this.curve.point(null, null);
15413
15414 // P + Q = O
15415 if (this.x.cmp(p.x) === 0)
15416 return this.curve.point(null, null);
15417
15418 var c = this.y.redSub(p.y);
15419 if (c.cmpn(0) !== 0)
15420 c = c.redMul(this.x.redSub(p.x).redInvm());
15421 var nx = c.redSqr().redISub(this.x).redISub(p.x);
15422 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
15423 return this.curve.point(nx, ny);
15424};
15425
15426Point.prototype.dbl = function dbl() {
15427 if (this.inf)
15428 return this;
15429
15430 // 2P = O
15431 var ys1 = this.y.redAdd(this.y);
15432 if (ys1.cmpn(0) === 0)
15433 return this.curve.point(null, null);
15434
15435 var a = this.curve.a;
15436
15437 var x2 = this.x.redSqr();
15438 var dyinv = ys1.redInvm();
15439 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
15440
15441 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
15442 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
15443 return this.curve.point(nx, ny);
15444};
15445
15446Point.prototype.getX = function getX() {
15447 return this.x.fromRed();
15448};
15449
15450Point.prototype.getY = function getY() {
15451 return this.y.fromRed();
15452};
15453
15454Point.prototype.mul = function mul(k) {
15455 k = new BN(k, 16);
15456
15457 if (this._hasDoubles(k))
15458 return this.curve._fixedNafMul(this, k);
15459 else if (this.curve.endo)
15460 return this.curve._endoWnafMulAdd([ this ], [ k ]);
15461 else
15462 return this.curve._wnafMul(this, k);
15463};
15464
15465Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
15466 var points = [ this, p2 ];
15467 var coeffs = [ k1, k2 ];
15468 if (this.curve.endo)
15469 return this.curve._endoWnafMulAdd(points, coeffs);
15470 else
15471 return this.curve._wnafMulAdd(1, points, coeffs, 2);
15472};
15473
15474Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
15475 var points = [ this, p2 ];
15476 var coeffs = [ k1, k2 ];
15477 if (this.curve.endo)
15478 return this.curve._endoWnafMulAdd(points, coeffs, true);
15479 else
15480 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
15481};
15482
15483Point.prototype.eq = function eq(p) {
15484 return this === p ||
15485 this.inf === p.inf &&
15486 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
15487};
15488
15489Point.prototype.neg = function neg(_precompute) {
15490 if (this.inf)
15491 return this;
15492
15493 var res = this.curve.point(this.x, this.y.redNeg());
15494 if (_precompute && this.precomputed) {
15495 var pre = this.precomputed;
15496 var negate = function(p) {
15497 return p.neg();
15498 };
15499 res.precomputed = {
15500 naf: pre.naf && {
15501 wnd: pre.naf.wnd,
15502 points: pre.naf.points.map(negate)
15503 },
15504 doubles: pre.doubles && {
15505 step: pre.doubles.step,
15506 points: pre.doubles.points.map(negate)
15507 }
15508 };
15509 }
15510 return res;
15511};
15512
15513Point.prototype.toJ = function toJ() {
15514 if (this.inf)
15515 return this.curve.jpoint(null, null, null);
15516
15517 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
15518 return res;
15519};
15520
15521function JPoint(curve, x, y, z) {
15522 Base.BasePoint.call(this, curve, 'jacobian');
15523 if (x === null && y === null && z === null) {
15524 this.x = this.curve.one;
15525 this.y = this.curve.one;
15526 this.z = new BN(0);
15527 } else {
15528 this.x = new BN(x, 16);
15529 this.y = new BN(y, 16);
15530 this.z = new BN(z, 16);
15531 }
15532 if (!this.x.red)
15533 this.x = this.x.toRed(this.curve.red);
15534 if (!this.y.red)
15535 this.y = this.y.toRed(this.curve.red);
15536 if (!this.z.red)
15537 this.z = this.z.toRed(this.curve.red);
15538
15539 this.zOne = this.z === this.curve.one;
15540}
15541inherits(JPoint, Base.BasePoint);
15542
15543ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
15544 return new JPoint(this, x, y, z);
15545};
15546
15547JPoint.prototype.toP = function toP() {
15548 if (this.isInfinity())
15549 return this.curve.point(null, null);
15550
15551 var zinv = this.z.redInvm();
15552 var zinv2 = zinv.redSqr();
15553 var ax = this.x.redMul(zinv2);
15554 var ay = this.y.redMul(zinv2).redMul(zinv);
15555
15556 return this.curve.point(ax, ay);
15557};
15558
15559JPoint.prototype.neg = function neg() {
15560 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
15561};
15562
15563JPoint.prototype.add = function add(p) {
15564 // O + P = P
15565 if (this.isInfinity())
15566 return p;
15567
15568 // P + O = P
15569 if (p.isInfinity())
15570 return this;
15571
15572 // 12M + 4S + 7A
15573 var pz2 = p.z.redSqr();
15574 var z2 = this.z.redSqr();
15575 var u1 = this.x.redMul(pz2);
15576 var u2 = p.x.redMul(z2);
15577 var s1 = this.y.redMul(pz2.redMul(p.z));
15578 var s2 = p.y.redMul(z2.redMul(this.z));
15579
15580 var h = u1.redSub(u2);
15581 var r = s1.redSub(s2);
15582 if (h.cmpn(0) === 0) {
15583 if (r.cmpn(0) !== 0)
15584 return this.curve.jpoint(null, null, null);
15585 else
15586 return this.dbl();
15587 }
15588
15589 var h2 = h.redSqr();
15590 var h3 = h2.redMul(h);
15591 var v = u1.redMul(h2);
15592
15593 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
15594 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
15595 var nz = this.z.redMul(p.z).redMul(h);
15596
15597 return this.curve.jpoint(nx, ny, nz);
15598};
15599
15600JPoint.prototype.mixedAdd = function mixedAdd(p) {
15601 // O + P = P
15602 if (this.isInfinity())
15603 return p.toJ();
15604
15605 // P + O = P
15606 if (p.isInfinity())
15607 return this;
15608
15609 // 8M + 3S + 7A
15610 var z2 = this.z.redSqr();
15611 var u1 = this.x;
15612 var u2 = p.x.redMul(z2);
15613 var s1 = this.y;
15614 var s2 = p.y.redMul(z2).redMul(this.z);
15615
15616 var h = u1.redSub(u2);
15617 var r = s1.redSub(s2);
15618 if (h.cmpn(0) === 0) {
15619 if (r.cmpn(0) !== 0)
15620 return this.curve.jpoint(null, null, null);
15621 else
15622 return this.dbl();
15623 }
15624
15625 var h2 = h.redSqr();
15626 var h3 = h2.redMul(h);
15627 var v = u1.redMul(h2);
15628
15629 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
15630 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
15631 var nz = this.z.redMul(h);
15632
15633 return this.curve.jpoint(nx, ny, nz);
15634};
15635
15636JPoint.prototype.dblp = function dblp(pow) {
15637 if (pow === 0)
15638 return this;
15639 if (this.isInfinity())
15640 return this;
15641 if (!pow)
15642 return this.dbl();
15643
15644 if (this.curve.zeroA || this.curve.threeA) {
15645 var r = this;
15646 for (var i = 0; i < pow; i++)
15647 r = r.dbl();
15648 return r;
15649 }
15650
15651 // 1M + 2S + 1A + N * (4S + 5M + 8A)
15652 // N = 1 => 6M + 6S + 9A
15653 var a = this.curve.a;
15654 var tinv = this.curve.tinv;
15655
15656 var jx = this.x;
15657 var jy = this.y;
15658 var jz = this.z;
15659 var jz4 = jz.redSqr().redSqr();
15660
15661 // Reuse results
15662 var jyd = jy.redAdd(jy);
15663 for (var i = 0; i < pow; i++) {
15664 var jx2 = jx.redSqr();
15665 var jyd2 = jyd.redSqr();
15666 var jyd4 = jyd2.redSqr();
15667 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
15668
15669 var t1 = jx.redMul(jyd2);
15670 var nx = c.redSqr().redISub(t1.redAdd(t1));
15671 var t2 = t1.redISub(nx);
15672 var dny = c.redMul(t2);
15673 dny = dny.redIAdd(dny).redISub(jyd4);
15674 var nz = jyd.redMul(jz);
15675 if (i + 1 < pow)
15676 jz4 = jz4.redMul(jyd4);
15677
15678 jx = nx;
15679 jz = nz;
15680 jyd = dny;
15681 }
15682
15683 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
15684};
15685
15686JPoint.prototype.dbl = function dbl() {
15687 if (this.isInfinity())
15688 return this;
15689
15690 if (this.curve.zeroA)
15691 return this._zeroDbl();
15692 else if (this.curve.threeA)
15693 return this._threeDbl();
15694 else
15695 return this._dbl();
15696};
15697
15698JPoint.prototype._zeroDbl = function _zeroDbl() {
15699 var nx;
15700 var ny;
15701 var nz;
15702 // Z = 1
15703 if (this.zOne) {
15704 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
15705 // #doubling-mdbl-2007-bl
15706 // 1M + 5S + 14A
15707
15708 // XX = X1^2
15709 var xx = this.x.redSqr();
15710 // YY = Y1^2
15711 var yy = this.y.redSqr();
15712 // YYYY = YY^2
15713 var yyyy = yy.redSqr();
15714 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
15715 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
15716 s = s.redIAdd(s);
15717 // M = 3 * XX + a; a = 0
15718 var m = xx.redAdd(xx).redIAdd(xx);
15719 // T = M ^ 2 - 2*S
15720 var t = m.redSqr().redISub(s).redISub(s);
15721
15722 // 8 * YYYY
15723 var yyyy8 = yyyy.redIAdd(yyyy);
15724 yyyy8 = yyyy8.redIAdd(yyyy8);
15725 yyyy8 = yyyy8.redIAdd(yyyy8);
15726
15727 // X3 = T
15728 nx = t;
15729 // Y3 = M * (S - T) - 8 * YYYY
15730 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
15731 // Z3 = 2*Y1
15732 nz = this.y.redAdd(this.y);
15733 } else {
15734 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
15735 // #doubling-dbl-2009-l
15736 // 2M + 5S + 13A
15737
15738 // A = X1^2
15739 var a = this.x.redSqr();
15740 // B = Y1^2
15741 var b = this.y.redSqr();
15742 // C = B^2
15743 var c = b.redSqr();
15744 // D = 2 * ((X1 + B)^2 - A - C)
15745 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
15746 d = d.redIAdd(d);
15747 // E = 3 * A
15748 var e = a.redAdd(a).redIAdd(a);
15749 // F = E^2
15750 var f = e.redSqr();
15751
15752 // 8 * C
15753 var c8 = c.redIAdd(c);
15754 c8 = c8.redIAdd(c8);
15755 c8 = c8.redIAdd(c8);
15756
15757 // X3 = F - 2 * D
15758 nx = f.redISub(d).redISub(d);
15759 // Y3 = E * (D - X3) - 8 * C
15760 ny = e.redMul(d.redISub(nx)).redISub(c8);
15761 // Z3 = 2 * Y1 * Z1
15762 nz = this.y.redMul(this.z);
15763 nz = nz.redIAdd(nz);
15764 }
15765
15766 return this.curve.jpoint(nx, ny, nz);
15767};
15768
15769JPoint.prototype._threeDbl = function _threeDbl() {
15770 var nx;
15771 var ny;
15772 var nz;
15773 // Z = 1
15774 if (this.zOne) {
15775 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
15776 // #doubling-mdbl-2007-bl
15777 // 1M + 5S + 15A
15778
15779 // XX = X1^2
15780 var xx = this.x.redSqr();
15781 // YY = Y1^2
15782 var yy = this.y.redSqr();
15783 // YYYY = YY^2
15784 var yyyy = yy.redSqr();
15785 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
15786 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
15787 s = s.redIAdd(s);
15788 // M = 3 * XX + a
15789 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
15790 // T = M^2 - 2 * S
15791 var t = m.redSqr().redISub(s).redISub(s);
15792 // X3 = T
15793 nx = t;
15794 // Y3 = M * (S - T) - 8 * YYYY
15795 var yyyy8 = yyyy.redIAdd(yyyy);
15796 yyyy8 = yyyy8.redIAdd(yyyy8);
15797 yyyy8 = yyyy8.redIAdd(yyyy8);
15798 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
15799 // Z3 = 2 * Y1
15800 nz = this.y.redAdd(this.y);
15801 } else {
15802 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
15803 // 3M + 5S
15804
15805 // delta = Z1^2
15806 var delta = this.z.redSqr();
15807 // gamma = Y1^2
15808 var gamma = this.y.redSqr();
15809 // beta = X1 * gamma
15810 var beta = this.x.redMul(gamma);
15811 // alpha = 3 * (X1 - delta) * (X1 + delta)
15812 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
15813 alpha = alpha.redAdd(alpha).redIAdd(alpha);
15814 // X3 = alpha^2 - 8 * beta
15815 var beta4 = beta.redIAdd(beta);
15816 beta4 = beta4.redIAdd(beta4);
15817 var beta8 = beta4.redAdd(beta4);
15818 nx = alpha.redSqr().redISub(beta8);
15819 // Z3 = (Y1 + Z1)^2 - gamma - delta
15820 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
15821 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
15822 var ggamma8 = gamma.redSqr();
15823 ggamma8 = ggamma8.redIAdd(ggamma8);
15824 ggamma8 = ggamma8.redIAdd(ggamma8);
15825 ggamma8 = ggamma8.redIAdd(ggamma8);
15826 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
15827 }
15828
15829 return this.curve.jpoint(nx, ny, nz);
15830};
15831
15832JPoint.prototype._dbl = function _dbl() {
15833 var a = this.curve.a;
15834
15835 // 4M + 6S + 10A
15836 var jx = this.x;
15837 var jy = this.y;
15838 var jz = this.z;
15839 var jz4 = jz.redSqr().redSqr();
15840
15841 var jx2 = jx.redSqr();
15842 var jy2 = jy.redSqr();
15843
15844 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
15845
15846 var jxd4 = jx.redAdd(jx);
15847 jxd4 = jxd4.redIAdd(jxd4);
15848 var t1 = jxd4.redMul(jy2);
15849 var nx = c.redSqr().redISub(t1.redAdd(t1));
15850 var t2 = t1.redISub(nx);
15851
15852 var jyd8 = jy2.redSqr();
15853 jyd8 = jyd8.redIAdd(jyd8);
15854 jyd8 = jyd8.redIAdd(jyd8);
15855 jyd8 = jyd8.redIAdd(jyd8);
15856 var ny = c.redMul(t2).redISub(jyd8);
15857 var nz = jy.redAdd(jy).redMul(jz);
15858
15859 return this.curve.jpoint(nx, ny, nz);
15860};
15861
15862JPoint.prototype.trpl = function trpl() {
15863 if (!this.curve.zeroA)
15864 return this.dbl().add(this);
15865
15866 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
15867 // 5M + 10S + ...
15868
15869 // XX = X1^2
15870 var xx = this.x.redSqr();
15871 // YY = Y1^2
15872 var yy = this.y.redSqr();
15873 // ZZ = Z1^2
15874 var zz = this.z.redSqr();
15875 // YYYY = YY^2
15876 var yyyy = yy.redSqr();
15877 // M = 3 * XX + a * ZZ2; a = 0
15878 var m = xx.redAdd(xx).redIAdd(xx);
15879 // MM = M^2
15880 var mm = m.redSqr();
15881 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
15882 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
15883 e = e.redIAdd(e);
15884 e = e.redAdd(e).redIAdd(e);
15885 e = e.redISub(mm);
15886 // EE = E^2
15887 var ee = e.redSqr();
15888 // T = 16*YYYY
15889 var t = yyyy.redIAdd(yyyy);
15890 t = t.redIAdd(t);
15891 t = t.redIAdd(t);
15892 t = t.redIAdd(t);
15893 // U = (M + E)^2 - MM - EE - T
15894 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
15895 // X3 = 4 * (X1 * EE - 4 * YY * U)
15896 var yyu4 = yy.redMul(u);
15897 yyu4 = yyu4.redIAdd(yyu4);
15898 yyu4 = yyu4.redIAdd(yyu4);
15899 var nx = this.x.redMul(ee).redISub(yyu4);
15900 nx = nx.redIAdd(nx);
15901 nx = nx.redIAdd(nx);
15902 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
15903 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
15904 ny = ny.redIAdd(ny);
15905 ny = ny.redIAdd(ny);
15906 ny = ny.redIAdd(ny);
15907 // Z3 = (Z1 + E)^2 - ZZ - EE
15908 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
15909
15910 return this.curve.jpoint(nx, ny, nz);
15911};
15912
15913JPoint.prototype.mul = function mul(k, kbase) {
15914 k = new BN(k, kbase);
15915
15916 return this.curve._wnafMul(this, k);
15917};
15918
15919JPoint.prototype.eq = function eq(p) {
15920 if (p.type === 'affine')
15921 return this.eq(p.toJ());
15922
15923 if (this === p)
15924 return true;
15925
15926 // x1 * z2^2 == x2 * z1^2
15927 var z2 = this.z.redSqr();
15928 var pz2 = p.z.redSqr();
15929 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
15930 return false;
15931
15932 // y1 * z2^3 == y2 * z1^3
15933 var z3 = z2.redMul(this.z);
15934 var pz3 = pz2.redMul(p.z);
15935 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
15936};
15937
15938JPoint.prototype.eqXToP = function eqXToP(x) {
15939 var zs = this.z.redSqr();
15940 var rx = x.toRed(this.curve.red).redMul(zs);
15941 if (this.x.cmp(rx) === 0)
15942 return true;
15943
15944 var xc = x.clone();
15945 var t = this.curve.redN.redMul(zs);
15946 for (;;) {
15947 xc.iadd(this.curve.n);
15948 if (xc.cmp(this.curve.p) >= 0)
15949 return false;
15950
15951 rx.redIAdd(t);
15952 if (this.x.cmp(rx) === 0)
15953 return true;
15954 }
15955 return false;
15956};
15957
15958JPoint.prototype.inspect = function inspect() {
15959 if (this.isInfinity())
15960 return '<EC JPoint Infinity>';
15961 return '<EC JPoint x: ' + this.x.toString(16, 2) +
15962 ' y: ' + this.y.toString(16, 2) +
15963 ' z: ' + this.z.toString(16, 2) + '>';
15964};
15965
15966JPoint.prototype.isInfinity = function isInfinity() {
15967 // XXX This code assumes that zero is always zero in red
15968 return this.z.cmpn(0) === 0;
15969};
15970
15971},{"../../elliptic":73,"../curve":76,"bn.js":21,"inherits":107}],79:[function(require,module,exports){
15972'use strict';
15973
15974var curves = exports;
15975
15976var hash = require('hash.js');
15977var elliptic = require('../elliptic');
15978
15979var assert = elliptic.utils.assert;
15980
15981function PresetCurve(options) {
15982 if (options.type === 'short')
15983 this.curve = new elliptic.curve.short(options);
15984 else if (options.type === 'edwards')
15985 this.curve = new elliptic.curve.edwards(options);
15986 else
15987 this.curve = new elliptic.curve.mont(options);
15988 this.g = this.curve.g;
15989 this.n = this.curve.n;
15990 this.hash = options.hash;
15991
15992 assert(this.g.validate(), 'Invalid curve');
15993 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
15994}
15995curves.PresetCurve = PresetCurve;
15996
15997function defineCurve(name, options) {
15998 Object.defineProperty(curves, name, {
15999 configurable: true,
16000 enumerable: true,
16001 get: function() {
16002 var curve = new PresetCurve(options);
16003 Object.defineProperty(curves, name, {
16004 configurable: true,
16005 enumerable: true,
16006 value: curve
16007 });
16008 return curve;
16009 }
16010 });
16011}
16012
16013defineCurve('p192', {
16014 type: 'short',
16015 prime: 'p192',
16016 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
16017 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
16018 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
16019 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
16020 hash: hash.sha256,
16021 gRed: false,
16022 g: [
16023 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
16024 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
16025 ]
16026});
16027
16028defineCurve('p224', {
16029 type: 'short',
16030 prime: 'p224',
16031 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
16032 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
16033 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
16034 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
16035 hash: hash.sha256,
16036 gRed: false,
16037 g: [
16038 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
16039 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
16040 ]
16041});
16042
16043defineCurve('p256', {
16044 type: 'short',
16045 prime: null,
16046 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
16047 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
16048 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
16049 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
16050 hash: hash.sha256,
16051 gRed: false,
16052 g: [
16053 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
16054 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
16055 ]
16056});
16057
16058defineCurve('p384', {
16059 type: 'short',
16060 prime: null,
16061 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16062 'fffffffe ffffffff 00000000 00000000 ffffffff',
16063 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16064 'fffffffe ffffffff 00000000 00000000 fffffffc',
16065 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
16066 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
16067 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
16068 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
16069 hash: hash.sha384,
16070 gRed: false,
16071 g: [
16072 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
16073 '5502f25d bf55296c 3a545e38 72760ab7',
16074 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
16075 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
16076 ]
16077});
16078
16079defineCurve('p521', {
16080 type: 'short',
16081 prime: null,
16082 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16083 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16084 'ffffffff ffffffff ffffffff ffffffff ffffffff',
16085 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16086 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16087 'ffffffff ffffffff ffffffff ffffffff fffffffc',
16088 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
16089 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
16090 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
16091 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16092 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
16093 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
16094 hash: hash.sha512,
16095 gRed: false,
16096 g: [
16097 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
16098 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
16099 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
16100 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
16101 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
16102 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
16103 ]
16104});
16105
16106defineCurve('curve25519', {
16107 type: 'mont',
16108 prime: 'p25519',
16109 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
16110 a: '76d06',
16111 b: '1',
16112 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
16113 hash: hash.sha256,
16114 gRed: false,
16115 g: [
16116 '9'
16117 ]
16118});
16119
16120defineCurve('ed25519', {
16121 type: 'edwards',
16122 prime: 'p25519',
16123 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
16124 a: '-1',
16125 c: '1',
16126 // -121665 * (121666^(-1)) (mod P)
16127 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
16128 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
16129 hash: hash.sha256,
16130 gRed: false,
16131 g: [
16132 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
16133
16134 // 4/5
16135 '6666666666666666666666666666666666666666666666666666666666666658'
16136 ]
16137});
16138
16139var pre;
16140try {
16141 pre = require('./precomputed/secp256k1');
16142} catch (e) {
16143 pre = undefined;
16144}
16145
16146defineCurve('secp256k1', {
16147 type: 'short',
16148 prime: 'k256',
16149 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
16150 a: '0',
16151 b: '7',
16152 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
16153 h: '1',
16154 hash: hash.sha256,
16155
16156 // Precomputed endomorphism
16157 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
16158 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
16159 basis: [
16160 {
16161 a: '3086d221a7d46bcde86c90e49284eb15',
16162 b: '-e4437ed6010e88286f547fa90abfe4c3'
16163 },
16164 {
16165 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
16166 b: '3086d221a7d46bcde86c90e49284eb15'
16167 }
16168 ],
16169
16170 gRed: false,
16171 g: [
16172 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
16173 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
16174 pre
16175 ]
16176});
16177
16178},{"../elliptic":73,"./precomputed/secp256k1":86,"hash.js":92}],80:[function(require,module,exports){
16179'use strict';
16180
16181var BN = require('bn.js');
16182var HmacDRBG = require('hmac-drbg');
16183var elliptic = require('../../elliptic');
16184var utils = elliptic.utils;
16185var assert = utils.assert;
16186
16187var KeyPair = require('./key');
16188var Signature = require('./signature');
16189
16190function EC(options) {
16191 if (!(this instanceof EC))
16192 return new EC(options);
16193
16194 // Shortcut `elliptic.ec(curve-name)`
16195 if (typeof options === 'string') {
16196 assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
16197
16198 options = elliptic.curves[options];
16199 }
16200
16201 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
16202 if (options instanceof elliptic.curves.PresetCurve)
16203 options = { curve: options };
16204
16205 this.curve = options.curve.curve;
16206 this.n = this.curve.n;
16207 this.nh = this.n.ushrn(1);
16208 this.g = this.curve.g;
16209
16210 // Point on curve
16211 this.g = options.curve.g;
16212 this.g.precompute(options.curve.n.bitLength() + 1);
16213
16214 // Hash for function for DRBG
16215 this.hash = options.hash || options.curve.hash;
16216}
16217module.exports = EC;
16218
16219EC.prototype.keyPair = function keyPair(options) {
16220 return new KeyPair(this, options);
16221};
16222
16223EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
16224 return KeyPair.fromPrivate(this, priv, enc);
16225};
16226
16227EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
16228 return KeyPair.fromPublic(this, pub, enc);
16229};
16230
16231EC.prototype.genKeyPair = function genKeyPair(options) {
16232 if (!options)
16233 options = {};
16234
16235 // Instantiate Hmac_DRBG
16236 var drbg = new HmacDRBG({
16237 hash: this.hash,
16238 pers: options.pers,
16239 persEnc: options.persEnc || 'utf8',
16240 entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
16241 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
16242 nonce: this.n.toArray()
16243 });
16244
16245 var bytes = this.n.byteLength();
16246 var ns2 = this.n.sub(new BN(2));
16247 do {
16248 var priv = new BN(drbg.generate(bytes));
16249 if (priv.cmp(ns2) > 0)
16250 continue;
16251
16252 priv.iaddn(1);
16253 return this.keyFromPrivate(priv);
16254 } while (true);
16255};
16256
16257EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
16258 var delta = msg.byteLength() * 8 - this.n.bitLength();
16259 if (delta > 0)
16260 msg = msg.ushrn(delta);
16261 if (!truncOnly && msg.cmp(this.n) >= 0)
16262 return msg.sub(this.n);
16263 else
16264 return msg;
16265};
16266
16267EC.prototype.sign = function sign(msg, key, enc, options) {
16268 if (typeof enc === 'object') {
16269 options = enc;
16270 enc = null;
16271 }
16272 if (!options)
16273 options = {};
16274
16275 key = this.keyFromPrivate(key, enc);
16276 msg = this._truncateToN(new BN(msg, 16));
16277
16278 // Zero-extend key to provide enough entropy
16279 var bytes = this.n.byteLength();
16280 var bkey = key.getPrivate().toArray('be', bytes);
16281
16282 // Zero-extend nonce to have the same byte size as N
16283 var nonce = msg.toArray('be', bytes);
16284
16285 // Instantiate Hmac_DRBG
16286 var drbg = new HmacDRBG({
16287 hash: this.hash,
16288 entropy: bkey,
16289 nonce: nonce,
16290 pers: options.pers,
16291 persEnc: options.persEnc || 'utf8'
16292 });
16293
16294 // Number of bytes to generate
16295 var ns1 = this.n.sub(new BN(1));
16296
16297 for (var iter = 0; true; iter++) {
16298 var k = options.k ?
16299 options.k(iter) :
16300 new BN(drbg.generate(this.n.byteLength()));
16301 k = this._truncateToN(k, true);
16302 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
16303 continue;
16304
16305 var kp = this.g.mul(k);
16306 if (kp.isInfinity())
16307 continue;
16308
16309 var kpX = kp.getX();
16310 var r = kpX.umod(this.n);
16311 if (r.cmpn(0) === 0)
16312 continue;
16313
16314 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
16315 s = s.umod(this.n);
16316 if (s.cmpn(0) === 0)
16317 continue;
16318
16319 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
16320 (kpX.cmp(r) !== 0 ? 2 : 0);
16321
16322 // Use complement of `s`, if it is > `n / 2`
16323 if (options.canonical && s.cmp(this.nh) > 0) {
16324 s = this.n.sub(s);
16325 recoveryParam ^= 1;
16326 }
16327
16328 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
16329 }
16330};
16331
16332EC.prototype.verify = function verify(msg, signature, key, enc) {
16333 msg = this._truncateToN(new BN(msg, 16));
16334 key = this.keyFromPublic(key, enc);
16335 signature = new Signature(signature, 'hex');
16336
16337 // Perform primitive values validation
16338 var r = signature.r;
16339 var s = signature.s;
16340 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
16341 return false;
16342 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
16343 return false;
16344
16345 // Validate signature
16346 var sinv = s.invm(this.n);
16347 var u1 = sinv.mul(msg).umod(this.n);
16348 var u2 = sinv.mul(r).umod(this.n);
16349
16350 if (!this.curve._maxwellTrick) {
16351 var p = this.g.mulAdd(u1, key.getPublic(), u2);
16352 if (p.isInfinity())
16353 return false;
16354
16355 return p.getX().umod(this.n).cmp(r) === 0;
16356 }
16357
16358 // NOTE: Greg Maxwell's trick, inspired by:
16359 // https://git.io/vad3K
16360
16361 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
16362 if (p.isInfinity())
16363 return false;
16364
16365 // Compare `p.x` of Jacobian point with `r`,
16366 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
16367 // inverse of `p.z^2`
16368 return p.eqXToP(r);
16369};
16370
16371EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
16372 assert((3 & j) === j, 'The recovery param is more than two bits');
16373 signature = new Signature(signature, enc);
16374
16375 var n = this.n;
16376 var e = new BN(msg);
16377 var r = signature.r;
16378 var s = signature.s;
16379
16380 // A set LSB signifies that the y-coordinate is odd
16381 var isYOdd = j & 1;
16382 var isSecondKey = j >> 1;
16383 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
16384 throw new Error('Unable to find sencond key candinate');
16385
16386 // 1.1. Let x = r + jn.
16387 if (isSecondKey)
16388 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
16389 else
16390 r = this.curve.pointFromX(r, isYOdd);
16391
16392 var rInv = signature.r.invm(n);
16393 var s1 = n.sub(e).mul(rInv).umod(n);
16394 var s2 = s.mul(rInv).umod(n);
16395
16396 // 1.6.1 Compute Q = r^-1 (sR - eG)
16397 // Q = r^-1 (sR + -eG)
16398 return this.g.mulAdd(s1, r, s2);
16399};
16400
16401EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
16402 signature = new Signature(signature, enc);
16403 if (signature.recoveryParam !== null)
16404 return signature.recoveryParam;
16405
16406 for (var i = 0; i < 4; i++) {
16407 var Qprime;
16408 try {
16409 Qprime = this.recoverPubKey(e, signature, i);
16410 } catch (e) {
16411 continue;
16412 }
16413
16414 if (Qprime.eq(Q))
16415 return i;
16416 }
16417 throw new Error('Unable to find valid recovery factor');
16418};
16419
16420},{"../../elliptic":73,"./key":81,"./signature":82,"bn.js":21,"hmac-drbg":104}],81:[function(require,module,exports){
16421'use strict';
16422
16423var BN = require('bn.js');
16424var elliptic = require('../../elliptic');
16425var utils = elliptic.utils;
16426var assert = utils.assert;
16427
16428function KeyPair(ec, options) {
16429 this.ec = ec;
16430 this.priv = null;
16431 this.pub = null;
16432
16433 // KeyPair(ec, { priv: ..., pub: ... })
16434 if (options.priv)
16435 this._importPrivate(options.priv, options.privEnc);
16436 if (options.pub)
16437 this._importPublic(options.pub, options.pubEnc);
16438}
16439module.exports = KeyPair;
16440
16441KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
16442 if (pub instanceof KeyPair)
16443 return pub;
16444
16445 return new KeyPair(ec, {
16446 pub: pub,
16447 pubEnc: enc
16448 });
16449};
16450
16451KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
16452 if (priv instanceof KeyPair)
16453 return priv;
16454
16455 return new KeyPair(ec, {
16456 priv: priv,
16457 privEnc: enc
16458 });
16459};
16460
16461KeyPair.prototype.validate = function validate() {
16462 var pub = this.getPublic();
16463
16464 if (pub.isInfinity())
16465 return { result: false, reason: 'Invalid public key' };
16466 if (!pub.validate())
16467 return { result: false, reason: 'Public key is not a point' };
16468 if (!pub.mul(this.ec.curve.n).isInfinity())
16469 return { result: false, reason: 'Public key * N != O' };
16470
16471 return { result: true, reason: null };
16472};
16473
16474KeyPair.prototype.getPublic = function getPublic(compact, enc) {
16475 // compact is optional argument
16476 if (typeof compact === 'string') {
16477 enc = compact;
16478 compact = null;
16479 }
16480
16481 if (!this.pub)
16482 this.pub = this.ec.g.mul(this.priv);
16483
16484 if (!enc)
16485 return this.pub;
16486
16487 return this.pub.encode(enc, compact);
16488};
16489
16490KeyPair.prototype.getPrivate = function getPrivate(enc) {
16491 if (enc === 'hex')
16492 return this.priv.toString(16, 2);
16493 else
16494 return this.priv;
16495};
16496
16497KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
16498 this.priv = new BN(key, enc || 16);
16499
16500 // Ensure that the priv won't be bigger than n, otherwise we may fail
16501 // in fixed multiplication method
16502 this.priv = this.priv.umod(this.ec.curve.n);
16503};
16504
16505KeyPair.prototype._importPublic = function _importPublic(key, enc) {
16506 if (key.x || key.y) {
16507 // Montgomery points only have an `x` coordinate.
16508 // Weierstrass/Edwards points on the other hand have both `x` and
16509 // `y` coordinates.
16510 if (this.ec.curve.type === 'mont') {
16511 assert(key.x, 'Need x coordinate');
16512 } else if (this.ec.curve.type === 'short' ||
16513 this.ec.curve.type === 'edwards') {
16514 assert(key.x && key.y, 'Need both x and y coordinate');
16515 }
16516 this.pub = this.ec.curve.point(key.x, key.y);
16517 return;
16518 }
16519 this.pub = this.ec.curve.decodePoint(key, enc);
16520};
16521
16522// ECDH
16523KeyPair.prototype.derive = function derive(pub) {
16524 return pub.mul(this.priv).getX();
16525};
16526
16527// ECDSA
16528KeyPair.prototype.sign = function sign(msg, enc, options) {
16529 return this.ec.sign(msg, this, enc, options);
16530};
16531
16532KeyPair.prototype.verify = function verify(msg, signature) {
16533 return this.ec.verify(msg, signature, this);
16534};
16535
16536KeyPair.prototype.inspect = function inspect() {
16537 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
16538 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
16539};
16540
16541},{"../../elliptic":73,"bn.js":21}],82:[function(require,module,exports){
16542'use strict';
16543
16544var BN = require('bn.js');
16545
16546var elliptic = require('../../elliptic');
16547var utils = elliptic.utils;
16548var assert = utils.assert;
16549
16550function Signature(options, enc) {
16551 if (options instanceof Signature)
16552 return options;
16553
16554 if (this._importDER(options, enc))
16555 return;
16556
16557 assert(options.r && options.s, 'Signature without r or s');
16558 this.r = new BN(options.r, 16);
16559 this.s = new BN(options.s, 16);
16560 if (options.recoveryParam === undefined)
16561 this.recoveryParam = null;
16562 else
16563 this.recoveryParam = options.recoveryParam;
16564}
16565module.exports = Signature;
16566
16567function Position() {
16568 this.place = 0;
16569}
16570
16571function getLength(buf, p) {
16572 var initial = buf[p.place++];
16573 if (!(initial & 0x80)) {
16574 return initial;
16575 }
16576 var octetLen = initial & 0xf;
16577 var val = 0;
16578 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
16579 val <<= 8;
16580 val |= buf[off];
16581 }
16582 p.place = off;
16583 return val;
16584}
16585
16586function rmPadding(buf) {
16587 var i = 0;
16588 var len = buf.length - 1;
16589 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
16590 i++;
16591 }
16592 if (i === 0) {
16593 return buf;
16594 }
16595 return buf.slice(i);
16596}
16597
16598Signature.prototype._importDER = function _importDER(data, enc) {
16599 data = utils.toArray(data, enc);
16600 var p = new Position();
16601 if (data[p.place++] !== 0x30) {
16602 return false;
16603 }
16604 var len = getLength(data, p);
16605 if ((len + p.place) !== data.length) {
16606 return false;
16607 }
16608 if (data[p.place++] !== 0x02) {
16609 return false;
16610 }
16611 var rlen = getLength(data, p);
16612 var r = data.slice(p.place, rlen + p.place);
16613 p.place += rlen;
16614 if (data[p.place++] !== 0x02) {
16615 return false;
16616 }
16617 var slen = getLength(data, p);
16618 if (data.length !== slen + p.place) {
16619 return false;
16620 }
16621 var s = data.slice(p.place, slen + p.place);
16622 if (r[0] === 0 && (r[1] & 0x80)) {
16623 r = r.slice(1);
16624 }
16625 if (s[0] === 0 && (s[1] & 0x80)) {
16626 s = s.slice(1);
16627 }
16628
16629 this.r = new BN(r);
16630 this.s = new BN(s);
16631 this.recoveryParam = null;
16632
16633 return true;
16634};
16635
16636function constructLength(arr, len) {
16637 if (len < 0x80) {
16638 arr.push(len);
16639 return;
16640 }
16641 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
16642 arr.push(octets | 0x80);
16643 while (--octets) {
16644 arr.push((len >>> (octets << 3)) & 0xff);
16645 }
16646 arr.push(len);
16647}
16648
16649Signature.prototype.toDER = function toDER(enc) {
16650 var r = this.r.toArray();
16651 var s = this.s.toArray();
16652
16653 // Pad values
16654 if (r[0] & 0x80)
16655 r = [ 0 ].concat(r);
16656 // Pad values
16657 if (s[0] & 0x80)
16658 s = [ 0 ].concat(s);
16659
16660 r = rmPadding(r);
16661 s = rmPadding(s);
16662
16663 while (!s[0] && !(s[1] & 0x80)) {
16664 s = s.slice(1);
16665 }
16666 var arr = [ 0x02 ];
16667 constructLength(arr, r.length);
16668 arr = arr.concat(r);
16669 arr.push(0x02);
16670 constructLength(arr, s.length);
16671 var backHalf = arr.concat(s);
16672 var res = [ 0x30 ];
16673 constructLength(res, backHalf.length);
16674 res = res.concat(backHalf);
16675 return utils.encode(res, enc);
16676};
16677
16678},{"../../elliptic":73,"bn.js":21}],83:[function(require,module,exports){
16679'use strict';
16680
16681var hash = require('hash.js');
16682var elliptic = require('../../elliptic');
16683var utils = elliptic.utils;
16684var assert = utils.assert;
16685var parseBytes = utils.parseBytes;
16686var KeyPair = require('./key');
16687var Signature = require('./signature');
16688
16689function EDDSA(curve) {
16690 assert(curve === 'ed25519', 'only tested with ed25519 so far');
16691
16692 if (!(this instanceof EDDSA))
16693 return new EDDSA(curve);
16694
16695 var curve = elliptic.curves[curve].curve;
16696 this.curve = curve;
16697 this.g = curve.g;
16698 this.g.precompute(curve.n.bitLength() + 1);
16699
16700 this.pointClass = curve.point().constructor;
16701 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
16702 this.hash = hash.sha512;
16703}
16704
16705module.exports = EDDSA;
16706
16707/**
16708* @param {Array|String} message - message bytes
16709* @param {Array|String|KeyPair} secret - secret bytes or a keypair
16710* @returns {Signature} - signature
16711*/
16712EDDSA.prototype.sign = function sign(message, secret) {
16713 message = parseBytes(message);
16714 var key = this.keyFromSecret(secret);
16715 var r = this.hashInt(key.messagePrefix(), message);
16716 var R = this.g.mul(r);
16717 var Rencoded = this.encodePoint(R);
16718 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
16719 .mul(key.priv());
16720 var S = r.add(s_).umod(this.curve.n);
16721 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
16722};
16723
16724/**
16725* @param {Array} message - message bytes
16726* @param {Array|String|Signature} sig - sig bytes
16727* @param {Array|String|Point|KeyPair} pub - public key
16728* @returns {Boolean} - true if public key matches sig of message
16729*/
16730EDDSA.prototype.verify = function verify(message, sig, pub) {
16731 message = parseBytes(message);
16732 sig = this.makeSignature(sig);
16733 var key = this.keyFromPublic(pub);
16734 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
16735 var SG = this.g.mul(sig.S());
16736 var RplusAh = sig.R().add(key.pub().mul(h));
16737 return RplusAh.eq(SG);
16738};
16739
16740EDDSA.prototype.hashInt = function hashInt() {
16741 var hash = this.hash();
16742 for (var i = 0; i < arguments.length; i++)
16743 hash.update(arguments[i]);
16744 return utils.intFromLE(hash.digest()).umod(this.curve.n);
16745};
16746
16747EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
16748 return KeyPair.fromPublic(this, pub);
16749};
16750
16751EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
16752 return KeyPair.fromSecret(this, secret);
16753};
16754
16755EDDSA.prototype.makeSignature = function makeSignature(sig) {
16756 if (sig instanceof Signature)
16757 return sig;
16758 return new Signature(this, sig);
16759};
16760
16761/**
16762* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
16763*
16764* EDDSA defines methods for encoding and decoding points and integers. These are
16765* helper convenience methods, that pass along to utility functions implied
16766* parameters.
16767*
16768*/
16769EDDSA.prototype.encodePoint = function encodePoint(point) {
16770 var enc = point.getY().toArray('le', this.encodingLength);
16771 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
16772 return enc;
16773};
16774
16775EDDSA.prototype.decodePoint = function decodePoint(bytes) {
16776 bytes = utils.parseBytes(bytes);
16777
16778 var lastIx = bytes.length - 1;
16779 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
16780 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
16781
16782 var y = utils.intFromLE(normed);
16783 return this.curve.pointFromY(y, xIsOdd);
16784};
16785
16786EDDSA.prototype.encodeInt = function encodeInt(num) {
16787 return num.toArray('le', this.encodingLength);
16788};
16789
16790EDDSA.prototype.decodeInt = function decodeInt(bytes) {
16791 return utils.intFromLE(bytes);
16792};
16793
16794EDDSA.prototype.isPoint = function isPoint(val) {
16795 return val instanceof this.pointClass;
16796};
16797
16798},{"../../elliptic":73,"./key":84,"./signature":85,"hash.js":92}],84:[function(require,module,exports){
16799'use strict';
16800
16801var elliptic = require('../../elliptic');
16802var utils = elliptic.utils;
16803var assert = utils.assert;
16804var parseBytes = utils.parseBytes;
16805var cachedProperty = utils.cachedProperty;
16806
16807/**
16808* @param {EDDSA} eddsa - instance
16809* @param {Object} params - public/private key parameters
16810*
16811* @param {Array<Byte>} [params.secret] - secret seed bytes
16812* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
16813* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
16814*
16815*/
16816function KeyPair(eddsa, params) {
16817 this.eddsa = eddsa;
16818 this._secret = parseBytes(params.secret);
16819 if (eddsa.isPoint(params.pub))
16820 this._pub = params.pub;
16821 else
16822 this._pubBytes = parseBytes(params.pub);
16823}
16824
16825KeyPair.fromPublic = function fromPublic(eddsa, pub) {
16826 if (pub instanceof KeyPair)
16827 return pub;
16828 return new KeyPair(eddsa, { pub: pub });
16829};
16830
16831KeyPair.fromSecret = function fromSecret(eddsa, secret) {
16832 if (secret instanceof KeyPair)
16833 return secret;
16834 return new KeyPair(eddsa, { secret: secret });
16835};
16836
16837KeyPair.prototype.secret = function secret() {
16838 return this._secret;
16839};
16840
16841cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
16842 return this.eddsa.encodePoint(this.pub());
16843});
16844
16845cachedProperty(KeyPair, 'pub', function pub() {
16846 if (this._pubBytes)
16847 return this.eddsa.decodePoint(this._pubBytes);
16848 return this.eddsa.g.mul(this.priv());
16849});
16850
16851cachedProperty(KeyPair, 'privBytes', function privBytes() {
16852 var eddsa = this.eddsa;
16853 var hash = this.hash();
16854 var lastIx = eddsa.encodingLength - 1;
16855
16856 var a = hash.slice(0, eddsa.encodingLength);
16857 a[0] &= 248;
16858 a[lastIx] &= 127;
16859 a[lastIx] |= 64;
16860
16861 return a;
16862});
16863
16864cachedProperty(KeyPair, 'priv', function priv() {
16865 return this.eddsa.decodeInt(this.privBytes());
16866});
16867
16868cachedProperty(KeyPair, 'hash', function hash() {
16869 return this.eddsa.hash().update(this.secret()).digest();
16870});
16871
16872cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
16873 return this.hash().slice(this.eddsa.encodingLength);
16874});
16875
16876KeyPair.prototype.sign = function sign(message) {
16877 assert(this._secret, 'KeyPair can only verify');
16878 return this.eddsa.sign(message, this);
16879};
16880
16881KeyPair.prototype.verify = function verify(message, sig) {
16882 return this.eddsa.verify(message, sig, this);
16883};
16884
16885KeyPair.prototype.getSecret = function getSecret(enc) {
16886 assert(this._secret, 'KeyPair is public only');
16887 return utils.encode(this.secret(), enc);
16888};
16889
16890KeyPair.prototype.getPublic = function getPublic(enc) {
16891 return utils.encode(this.pubBytes(), enc);
16892};
16893
16894module.exports = KeyPair;
16895
16896},{"../../elliptic":73}],85:[function(require,module,exports){
16897'use strict';
16898
16899var BN = require('bn.js');
16900var elliptic = require('../../elliptic');
16901var utils = elliptic.utils;
16902var assert = utils.assert;
16903var cachedProperty = utils.cachedProperty;
16904var parseBytes = utils.parseBytes;
16905
16906/**
16907* @param {EDDSA} eddsa - eddsa instance
16908* @param {Array<Bytes>|Object} sig -
16909* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
16910* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
16911* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
16912* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
16913*/
16914function Signature(eddsa, sig) {
16915 this.eddsa = eddsa;
16916
16917 if (typeof sig !== 'object')
16918 sig = parseBytes(sig);
16919
16920 if (Array.isArray(sig)) {
16921 sig = {
16922 R: sig.slice(0, eddsa.encodingLength),
16923 S: sig.slice(eddsa.encodingLength)
16924 };
16925 }
16926
16927 assert(sig.R && sig.S, 'Signature without R or S');
16928
16929 if (eddsa.isPoint(sig.R))
16930 this._R = sig.R;
16931 if (sig.S instanceof BN)
16932 this._S = sig.S;
16933
16934 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
16935 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
16936}
16937
16938cachedProperty(Signature, 'S', function S() {
16939 return this.eddsa.decodeInt(this.Sencoded());
16940});
16941
16942cachedProperty(Signature, 'R', function R() {
16943 return this.eddsa.decodePoint(this.Rencoded());
16944});
16945
16946cachedProperty(Signature, 'Rencoded', function Rencoded() {
16947 return this.eddsa.encodePoint(this.R());
16948});
16949
16950cachedProperty(Signature, 'Sencoded', function Sencoded() {
16951 return this.eddsa.encodeInt(this.S());
16952});
16953
16954Signature.prototype.toBytes = function toBytes() {
16955 return this.Rencoded().concat(this.Sencoded());
16956};
16957
16958Signature.prototype.toHex = function toHex() {
16959 return utils.encode(this.toBytes(), 'hex').toUpperCase();
16960};
16961
16962module.exports = Signature;
16963
16964},{"../../elliptic":73,"bn.js":21}],86:[function(require,module,exports){
16965module.exports = {
16966 doubles: {
16967 step: 4,
16968 points: [
16969 [
16970 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
16971 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
16972 ],
16973 [
16974 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
16975 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
16976 ],
16977 [
16978 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
16979 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
16980 ],
16981 [
16982 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
16983 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
16984 ],
16985 [
16986 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
16987 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
16988 ],
16989 [
16990 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
16991 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
16992 ],
16993 [
16994 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
16995 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
16996 ],
16997 [
16998 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
16999 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
17000 ],
17001 [
17002 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
17003 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
17004 ],
17005 [
17006 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
17007 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
17008 ],
17009 [
17010 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
17011 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
17012 ],
17013 [
17014 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
17015 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
17016 ],
17017 [
17018 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
17019 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
17020 ],
17021 [
17022 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
17023 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
17024 ],
17025 [
17026 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
17027 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
17028 ],
17029 [
17030 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
17031 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
17032 ],
17033 [
17034 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
17035 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
17036 ],
17037 [
17038 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
17039 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
17040 ],
17041 [
17042 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
17043 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
17044 ],
17045 [
17046 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
17047 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
17048 ],
17049 [
17050 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
17051 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
17052 ],
17053 [
17054 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
17055 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
17056 ],
17057 [
17058 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
17059 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
17060 ],
17061 [
17062 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
17063 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
17064 ],
17065 [
17066 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
17067 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
17068 ],
17069 [
17070 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
17071 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
17072 ],
17073 [
17074 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
17075 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
17076 ],
17077 [
17078 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
17079 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
17080 ],
17081 [
17082 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
17083 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
17084 ],
17085 [
17086 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
17087 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
17088 ],
17089 [
17090 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
17091 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
17092 ],
17093 [
17094 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
17095 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
17096 ],
17097 [
17098 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
17099 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
17100 ],
17101 [
17102 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
17103 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
17104 ],
17105 [
17106 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
17107 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
17108 ],
17109 [
17110 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
17111 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
17112 ],
17113 [
17114 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
17115 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
17116 ],
17117 [
17118 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
17119 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
17120 ],
17121 [
17122 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
17123 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
17124 ],
17125 [
17126 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
17127 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
17128 ],
17129 [
17130 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
17131 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
17132 ],
17133 [
17134 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
17135 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
17136 ],
17137 [
17138 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
17139 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
17140 ],
17141 [
17142 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
17143 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
17144 ],
17145 [
17146 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
17147 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
17148 ],
17149 [
17150 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
17151 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
17152 ],
17153 [
17154 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
17155 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
17156 ],
17157 [
17158 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
17159 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
17160 ],
17161 [
17162 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
17163 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
17164 ],
17165 [
17166 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
17167 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
17168 ],
17169 [
17170 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
17171 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
17172 ],
17173 [
17174 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
17175 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
17176 ],
17177 [
17178 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
17179 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
17180 ],
17181 [
17182 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
17183 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
17184 ],
17185 [
17186 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
17187 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
17188 ],
17189 [
17190 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
17191 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
17192 ],
17193 [
17194 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
17195 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
17196 ],
17197 [
17198 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
17199 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
17200 ],
17201 [
17202 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
17203 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
17204 ],
17205 [
17206 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
17207 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
17208 ],
17209 [
17210 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
17211 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
17212 ],
17213 [
17214 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
17215 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
17216 ],
17217 [
17218 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
17219 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
17220 ],
17221 [
17222 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
17223 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
17224 ],
17225 [
17226 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
17227 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
17228 ]
17229 ]
17230 },
17231 naf: {
17232 wnd: 7,
17233 points: [
17234 [
17235 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
17236 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
17237 ],
17238 [
17239 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
17240 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
17241 ],
17242 [
17243 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
17244 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
17245 ],
17246 [
17247 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
17248 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
17249 ],
17250 [
17251 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
17252 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
17253 ],
17254 [
17255 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
17256 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
17257 ],
17258 [
17259 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
17260 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
17261 ],
17262 [
17263 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
17264 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
17265 ],
17266 [
17267 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
17268 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
17269 ],
17270 [
17271 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
17272 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
17273 ],
17274 [
17275 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
17276 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
17277 ],
17278 [
17279 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
17280 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
17281 ],
17282 [
17283 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
17284 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
17285 ],
17286 [
17287 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
17288 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
17289 ],
17290 [
17291 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
17292 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
17293 ],
17294 [
17295 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
17296 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
17297 ],
17298 [
17299 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
17300 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
17301 ],
17302 [
17303 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
17304 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
17305 ],
17306 [
17307 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
17308 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
17309 ],
17310 [
17311 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
17312 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
17313 ],
17314 [
17315 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
17316 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
17317 ],
17318 [
17319 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
17320 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
17321 ],
17322 [
17323 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
17324 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
17325 ],
17326 [
17327 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
17328 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
17329 ],
17330 [
17331 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
17332 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
17333 ],
17334 [
17335 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
17336 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
17337 ],
17338 [
17339 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
17340 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
17341 ],
17342 [
17343 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
17344 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
17345 ],
17346 [
17347 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
17348 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
17349 ],
17350 [
17351 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
17352 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
17353 ],
17354 [
17355 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
17356 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
17357 ],
17358 [
17359 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
17360 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
17361 ],
17362 [
17363 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
17364 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
17365 ],
17366 [
17367 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
17368 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
17369 ],
17370 [
17371 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
17372 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
17373 ],
17374 [
17375 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
17376 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
17377 ],
17378 [
17379 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
17380 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
17381 ],
17382 [
17383 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
17384 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
17385 ],
17386 [
17387 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
17388 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
17389 ],
17390 [
17391 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
17392 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
17393 ],
17394 [
17395 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
17396 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
17397 ],
17398 [
17399 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
17400 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
17401 ],
17402 [
17403 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
17404 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
17405 ],
17406 [
17407 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
17408 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
17409 ],
17410 [
17411 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
17412 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
17413 ],
17414 [
17415 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
17416 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
17417 ],
17418 [
17419 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
17420 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
17421 ],
17422 [
17423 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
17424 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
17425 ],
17426 [
17427 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
17428 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
17429 ],
17430 [
17431 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
17432 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
17433 ],
17434 [
17435 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
17436 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
17437 ],
17438 [
17439 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
17440 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
17441 ],
17442 [
17443 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
17444 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
17445 ],
17446 [
17447 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
17448 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
17449 ],
17450 [
17451 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
17452 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
17453 ],
17454 [
17455 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
17456 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
17457 ],
17458 [
17459 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
17460 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
17461 ],
17462 [
17463 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
17464 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
17465 ],
17466 [
17467 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
17468 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
17469 ],
17470 [
17471 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
17472 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
17473 ],
17474 [
17475 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
17476 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
17477 ],
17478 [
17479 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
17480 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
17481 ],
17482 [
17483 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
17484 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
17485 ],
17486 [
17487 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
17488 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
17489 ],
17490 [
17491 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
17492 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
17493 ],
17494 [
17495 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
17496 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
17497 ],
17498 [
17499 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
17500 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
17501 ],
17502 [
17503 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
17504 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
17505 ],
17506 [
17507 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
17508 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
17509 ],
17510 [
17511 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
17512 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
17513 ],
17514 [
17515 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
17516 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
17517 ],
17518 [
17519 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
17520 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
17521 ],
17522 [
17523 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
17524 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
17525 ],
17526 [
17527 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
17528 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
17529 ],
17530 [
17531 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
17532 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
17533 ],
17534 [
17535 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
17536 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
17537 ],
17538 [
17539 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
17540 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
17541 ],
17542 [
17543 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
17544 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
17545 ],
17546 [
17547 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
17548 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
17549 ],
17550 [
17551 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
17552 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
17553 ],
17554 [
17555 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
17556 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
17557 ],
17558 [
17559 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
17560 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
17561 ],
17562 [
17563 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
17564 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
17565 ],
17566 [
17567 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
17568 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
17569 ],
17570 [
17571 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
17572 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
17573 ],
17574 [
17575 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
17576 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
17577 ],
17578 [
17579 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
17580 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
17581 ],
17582 [
17583 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
17584 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
17585 ],
17586 [
17587 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
17588 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
17589 ],
17590 [
17591 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
17592 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
17593 ],
17594 [
17595 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
17596 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
17597 ],
17598 [
17599 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
17600 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
17601 ],
17602 [
17603 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
17604 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
17605 ],
17606 [
17607 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
17608 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
17609 ],
17610 [
17611 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
17612 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
17613 ],
17614 [
17615 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
17616 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
17617 ],
17618 [
17619 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
17620 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
17621 ],
17622 [
17623 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
17624 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
17625 ],
17626 [
17627 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
17628 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
17629 ],
17630 [
17631 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
17632 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
17633 ],
17634 [
17635 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
17636 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
17637 ],
17638 [
17639 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
17640 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
17641 ],
17642 [
17643 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
17644 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
17645 ],
17646 [
17647 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
17648 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
17649 ],
17650 [
17651 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
17652 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
17653 ],
17654 [
17655 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
17656 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
17657 ],
17658 [
17659 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
17660 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
17661 ],
17662 [
17663 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
17664 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
17665 ],
17666 [
17667 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
17668 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
17669 ],
17670 [
17671 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
17672 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
17673 ],
17674 [
17675 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
17676 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
17677 ],
17678 [
17679 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
17680 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
17681 ],
17682 [
17683 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
17684 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
17685 ],
17686 [
17687 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
17688 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
17689 ],
17690 [
17691 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
17692 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
17693 ],
17694 [
17695 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
17696 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
17697 ],
17698 [
17699 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
17700 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
17701 ],
17702 [
17703 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
17704 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
17705 ],
17706 [
17707 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
17708 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
17709 ],
17710 [
17711 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
17712 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
17713 ],
17714 [
17715 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
17716 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
17717 ],
17718 [
17719 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
17720 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
17721 ],
17722 [
17723 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
17724 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
17725 ],
17726 [
17727 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
17728 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
17729 ],
17730 [
17731 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
17732 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
17733 ],
17734 [
17735 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
17736 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
17737 ],
17738 [
17739 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
17740 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
17741 ]
17742 ]
17743 }
17744};
17745
17746},{}],87:[function(require,module,exports){
17747'use strict';
17748
17749var utils = exports;
17750var BN = require('bn.js');
17751var minAssert = require('minimalistic-assert');
17752var minUtils = require('minimalistic-crypto-utils');
17753
17754utils.assert = minAssert;
17755utils.toArray = minUtils.toArray;
17756utils.zero2 = minUtils.zero2;
17757utils.toHex = minUtils.toHex;
17758utils.encode = minUtils.encode;
17759
17760// Represent num in a w-NAF form
17761function getNAF(num, w) {
17762 var naf = [];
17763 var ws = 1 << (w + 1);
17764 var k = num.clone();
17765 while (k.cmpn(1) >= 0) {
17766 var z;
17767 if (k.isOdd()) {
17768 var mod = k.andln(ws - 1);
17769 if (mod > (ws >> 1) - 1)
17770 z = (ws >> 1) - mod;
17771 else
17772 z = mod;
17773 k.isubn(z);
17774 } else {
17775 z = 0;
17776 }
17777 naf.push(z);
17778
17779 // Optimization, shift by word if possible
17780 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
17781 for (var i = 1; i < shift; i++)
17782 naf.push(0);
17783 k.iushrn(shift);
17784 }
17785
17786 return naf;
17787}
17788utils.getNAF = getNAF;
17789
17790// Represent k1, k2 in a Joint Sparse Form
17791function getJSF(k1, k2) {
17792 var jsf = [
17793 [],
17794 []
17795 ];
17796
17797 k1 = k1.clone();
17798 k2 = k2.clone();
17799 var d1 = 0;
17800 var d2 = 0;
17801 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
17802
17803 // First phase
17804 var m14 = (k1.andln(3) + d1) & 3;
17805 var m24 = (k2.andln(3) + d2) & 3;
17806 if (m14 === 3)
17807 m14 = -1;
17808 if (m24 === 3)
17809 m24 = -1;
17810 var u1;
17811 if ((m14 & 1) === 0) {
17812 u1 = 0;
17813 } else {
17814 var m8 = (k1.andln(7) + d1) & 7;
17815 if ((m8 === 3 || m8 === 5) && m24 === 2)
17816 u1 = -m14;
17817 else
17818 u1 = m14;
17819 }
17820 jsf[0].push(u1);
17821
17822 var u2;
17823 if ((m24 & 1) === 0) {
17824 u2 = 0;
17825 } else {
17826 var m8 = (k2.andln(7) + d2) & 7;
17827 if ((m8 === 3 || m8 === 5) && m14 === 2)
17828 u2 = -m24;
17829 else
17830 u2 = m24;
17831 }
17832 jsf[1].push(u2);
17833
17834 // Second phase
17835 if (2 * d1 === u1 + 1)
17836 d1 = 1 - d1;
17837 if (2 * d2 === u2 + 1)
17838 d2 = 1 - d2;
17839 k1.iushrn(1);
17840 k2.iushrn(1);
17841 }
17842
17843 return jsf;
17844}
17845utils.getJSF = getJSF;
17846
17847function cachedProperty(obj, name, computer) {
17848 var key = '_' + name;
17849 obj.prototype[name] = function cachedProperty() {
17850 return this[key] !== undefined ? this[key] :
17851 this[key] = computer.call(this);
17852 };
17853}
17854utils.cachedProperty = cachedProperty;
17855
17856function parseBytes(bytes) {
17857 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
17858 bytes;
17859}
17860utils.parseBytes = parseBytes;
17861
17862function intFromLE(bytes) {
17863 return new BN(bytes, 'hex', 'le');
17864}
17865utils.intFromLE = intFromLE;
17866
17867
17868},{"bn.js":21,"minimalistic-assert":120,"minimalistic-crypto-utils":121}],88:[function(require,module,exports){
17869module.exports={
17870 "_args": [
17871 [
17872 "elliptic@6.4.0",
17873 "/home/gleb/work/cryptocurrencies/nas-hardwallet/neb.js"
17874 ]
17875 ],
17876 "_from": "elliptic@6.4.0",
17877 "_id": "elliptic@6.4.0",
17878 "_inBundle": false,
17879 "_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",
17880 "_location": "/elliptic",
17881 "_phantomChildren": {},
17882 "_requested": {
17883 "type": "version",
17884 "registry": true,
17885 "raw": "elliptic@6.4.0",
17886 "name": "elliptic",
17887 "escapedName": "elliptic",
17888 "rawSpec": "6.4.0",
17889 "saveSpec": null,
17890 "fetchSpec": "6.4.0"
17891 },
17892 "_requiredBy": [
17893 "/browserify-sign",
17894 "/create-ecdh",
17895 "/secp256k1"
17896 ],
17897 "_resolved": "http://registry.npm.taobao.org/elliptic/download/elliptic-6.4.0.tgz",
17898 "_spec": "6.4.0",
17899 "_where": "/home/gleb/work/cryptocurrencies/nas-hardwallet/neb.js",
17900 "author": {
17901 "name": "Fedor Indutny",
17902 "email": "fedor@indutny.com"
17903 },
17904 "bugs": {
17905 "url": "https://github.com/indutny/elliptic/issues"
17906 },
17907 "dependencies": {
17908 "bn.js": "^4.4.0",
17909 "brorand": "^1.0.1",
17910 "hash.js": "^1.0.0",
17911 "hmac-drbg": "^1.0.0",
17912 "inherits": "^2.0.1",
17913 "minimalistic-assert": "^1.0.0",
17914 "minimalistic-crypto-utils": "^1.0.0"
17915 },
17916 "description": "EC cryptography",
17917 "devDependencies": {
17918 "brfs": "^1.4.3",
17919 "coveralls": "^2.11.3",
17920 "grunt": "^0.4.5",
17921 "grunt-browserify": "^5.0.0",
17922 "grunt-cli": "^1.2.0",
17923 "grunt-contrib-connect": "^1.0.0",
17924 "grunt-contrib-copy": "^1.0.0",
17925 "grunt-contrib-uglify": "^1.0.1",
17926 "grunt-mocha-istanbul": "^3.0.1",
17927 "grunt-saucelabs": "^8.6.2",
17928 "istanbul": "^0.4.2",
17929 "jscs": "^2.9.0",
17930 "jshint": "^2.6.0",
17931 "mocha": "^2.1.0"
17932 },
17933 "files": [
17934 "lib"
17935 ],
17936 "homepage": "https://github.com/indutny/elliptic",
17937 "keywords": [
17938 "EC",
17939 "Elliptic",
17940 "curve",
17941 "Cryptography"
17942 ],
17943 "license": "MIT",
17944 "main": "lib/elliptic.js",
17945 "name": "elliptic",
17946 "repository": {
17947 "type": "git",
17948 "url": "git+ssh://git@github.com/indutny/elliptic.git"
17949 },
17950 "scripts": {
17951 "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
17952 "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
17953 "lint": "npm run jscs && npm run jshint",
17954 "test": "npm run lint && npm run unit",
17955 "unit": "istanbul test _mocha --reporter=spec test/index.js",
17956 "version": "grunt dist && git add dist/"
17957 },
17958 "version": "6.4.0"
17959}
17960
17961},{}],89:[function(require,module,exports){
17962// Copyright Joyent, Inc. and other Node contributors.
17963//
17964// Permission is hereby granted, free of charge, to any person obtaining a
17965// copy of this software and associated documentation files (the
17966// "Software"), to deal in the Software without restriction, including
17967// without limitation the rights to use, copy, modify, merge, publish,
17968// distribute, sublicense, and/or sell copies of the Software, and to permit
17969// persons to whom the Software is furnished to do so, subject to the
17970// following conditions:
17971//
17972// The above copyright notice and this permission notice shall be included
17973// in all copies or substantial portions of the Software.
17974//
17975// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17976// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17977// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17978// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17979// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17980// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
17981// USE OR OTHER DEALINGS IN THE SOFTWARE.
17982
17983function EventEmitter() {
17984 this._events = this._events || {};
17985 this._maxListeners = this._maxListeners || undefined;
17986}
17987module.exports = EventEmitter;
17988
17989// Backwards-compat with node 0.10.x
17990EventEmitter.EventEmitter = EventEmitter;
17991
17992EventEmitter.prototype._events = undefined;
17993EventEmitter.prototype._maxListeners = undefined;
17994
17995// By default EventEmitters will print a warning if more than 10 listeners are
17996// added to it. This is a useful default which helps finding memory leaks.
17997EventEmitter.defaultMaxListeners = 10;
17998
17999// Obviously not all Emitters should be limited to 10. This function allows
18000// that to be increased. Set to zero for unlimited.
18001EventEmitter.prototype.setMaxListeners = function(n) {
18002 if (!isNumber(n) || n < 0 || isNaN(n))
18003 throw TypeError('n must be a positive number');
18004 this._maxListeners = n;
18005 return this;
18006};
18007
18008EventEmitter.prototype.emit = function(type) {
18009 var er, handler, len, args, i, listeners;
18010
18011 if (!this._events)
18012 this._events = {};
18013
18014 // If there is no 'error' event listener then throw.
18015 if (type === 'error') {
18016 if (!this._events.error ||
18017 (isObject(this._events.error) && !this._events.error.length)) {
18018 er = arguments[1];
18019 if (er instanceof Error) {
18020 throw er; // Unhandled 'error' event
18021 } else {
18022 // At least give some kind of context to the user
18023 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
18024 err.context = er;
18025 throw err;
18026 }
18027 }
18028 }
18029
18030 handler = this._events[type];
18031
18032 if (isUndefined(handler))
18033 return false;
18034
18035 if (isFunction(handler)) {
18036 switch (arguments.length) {
18037 // fast cases
18038 case 1:
18039 handler.call(this);
18040 break;
18041 case 2:
18042 handler.call(this, arguments[1]);
18043 break;
18044 case 3:
18045 handler.call(this, arguments[1], arguments[2]);
18046 break;
18047 // slower
18048 default:
18049 args = Array.prototype.slice.call(arguments, 1);
18050 handler.apply(this, args);
18051 }
18052 } else if (isObject(handler)) {
18053 args = Array.prototype.slice.call(arguments, 1);
18054 listeners = handler.slice();
18055 len = listeners.length;
18056 for (i = 0; i < len; i++)
18057 listeners[i].apply(this, args);
18058 }
18059
18060 return true;
18061};
18062
18063EventEmitter.prototype.addListener = function(type, listener) {
18064 var m;
18065
18066 if (!isFunction(listener))
18067 throw TypeError('listener must be a function');
18068
18069 if (!this._events)
18070 this._events = {};
18071
18072 // To avoid recursion in the case that type === "newListener"! Before
18073 // adding it to the listeners, first emit "newListener".
18074 if (this._events.newListener)
18075 this.emit('newListener', type,
18076 isFunction(listener.listener) ?
18077 listener.listener : listener);
18078
18079 if (!this._events[type])
18080 // Optimize the case of one listener. Don't need the extra array object.
18081 this._events[type] = listener;
18082 else if (isObject(this._events[type]))
18083 // If we've already got an array, just append.
18084 this._events[type].push(listener);
18085 else
18086 // Adding the second element, need to change to array.
18087 this._events[type] = [this._events[type], listener];
18088
18089 // Check for listener leak
18090 if (isObject(this._events[type]) && !this._events[type].warned) {
18091 if (!isUndefined(this._maxListeners)) {
18092 m = this._maxListeners;
18093 } else {
18094 m = EventEmitter.defaultMaxListeners;
18095 }
18096
18097 if (m && m > 0 && this._events[type].length > m) {
18098 this._events[type].warned = true;
18099 console.error('(node) warning: possible EventEmitter memory ' +
18100 'leak detected. %d listeners added. ' +
18101 'Use emitter.setMaxListeners() to increase limit.',
18102 this._events[type].length);
18103 if (typeof console.trace === 'function') {
18104 // not supported in IE 10
18105 console.trace();
18106 }
18107 }
18108 }
18109
18110 return this;
18111};
18112
18113EventEmitter.prototype.on = EventEmitter.prototype.addListener;
18114
18115EventEmitter.prototype.once = function(type, listener) {
18116 if (!isFunction(listener))
18117 throw TypeError('listener must be a function');
18118
18119 var fired = false;
18120
18121 function g() {
18122 this.removeListener(type, g);
18123
18124 if (!fired) {
18125 fired = true;
18126 listener.apply(this, arguments);
18127 }
18128 }
18129
18130 g.listener = listener;
18131 this.on(type, g);
18132
18133 return this;
18134};
18135
18136// emits a 'removeListener' event iff the listener was removed
18137EventEmitter.prototype.removeListener = function(type, listener) {
18138 var list, position, length, i;
18139
18140 if (!isFunction(listener))
18141 throw TypeError('listener must be a function');
18142
18143 if (!this._events || !this._events[type])
18144 return this;
18145
18146 list = this._events[type];
18147 length = list.length;
18148 position = -1;
18149
18150 if (list === listener ||
18151 (isFunction(list.listener) && list.listener === listener)) {
18152 delete this._events[type];
18153 if (this._events.removeListener)
18154 this.emit('removeListener', type, listener);
18155
18156 } else if (isObject(list)) {
18157 for (i = length; i-- > 0;) {
18158 if (list[i] === listener ||
18159 (list[i].listener && list[i].listener === listener)) {
18160 position = i;
18161 break;
18162 }
18163 }
18164
18165 if (position < 0)
18166 return this;
18167
18168 if (list.length === 1) {
18169 list.length = 0;
18170 delete this._events[type];
18171 } else {
18172 list.splice(position, 1);
18173 }
18174
18175 if (this._events.removeListener)
18176 this.emit('removeListener', type, listener);
18177 }
18178
18179 return this;
18180};
18181
18182EventEmitter.prototype.removeAllListeners = function(type) {
18183 var key, listeners;
18184
18185 if (!this._events)
18186 return this;
18187
18188 // not listening for removeListener, no need to emit
18189 if (!this._events.removeListener) {
18190 if (arguments.length === 0)
18191 this._events = {};
18192 else if (this._events[type])
18193 delete this._events[type];
18194 return this;
18195 }
18196
18197 // emit removeListener for all listeners on all events
18198 if (arguments.length === 0) {
18199 for (key in this._events) {
18200 if (key === 'removeListener') continue;
18201 this.removeAllListeners(key);
18202 }
18203 this.removeAllListeners('removeListener');
18204 this._events = {};
18205 return this;
18206 }
18207
18208 listeners = this._events[type];
18209
18210 if (isFunction(listeners)) {
18211 this.removeListener(type, listeners);
18212 } else if (listeners) {
18213 // LIFO order
18214 while (listeners.length)
18215 this.removeListener(type, listeners[listeners.length - 1]);
18216 }
18217 delete this._events[type];
18218
18219 return this;
18220};
18221
18222EventEmitter.prototype.listeners = function(type) {
18223 var ret;
18224 if (!this._events || !this._events[type])
18225 ret = [];
18226 else if (isFunction(this._events[type]))
18227 ret = [this._events[type]];
18228 else
18229 ret = this._events[type].slice();
18230 return ret;
18231};
18232
18233EventEmitter.prototype.listenerCount = function(type) {
18234 if (this._events) {
18235 var evlistener = this._events[type];
18236
18237 if (isFunction(evlistener))
18238 return 1;
18239 else if (evlistener)
18240 return evlistener.length;
18241 }
18242 return 0;
18243};
18244
18245EventEmitter.listenerCount = function(emitter, type) {
18246 return emitter.listenerCount(type);
18247};
18248
18249function isFunction(arg) {
18250 return typeof arg === 'function';
18251}
18252
18253function isNumber(arg) {
18254 return typeof arg === 'number';
18255}
18256
18257function isObject(arg) {
18258 return typeof arg === 'object' && arg !== null;
18259}
18260
18261function isUndefined(arg) {
18262 return arg === void 0;
18263}
18264
18265},{}],90:[function(require,module,exports){
18266var Buffer = require('safe-buffer').Buffer
18267var MD5 = require('md5.js')
18268
18269/* eslint-disable camelcase */
18270function EVP_BytesToKey (password, salt, keyBits, ivLen) {
18271 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
18272 if (salt) {
18273 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
18274 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
18275 }
18276
18277 var keyLen = keyBits / 8
18278 var key = Buffer.alloc(keyLen)
18279 var iv = Buffer.alloc(ivLen || 0)
18280 var tmp = Buffer.alloc(0)
18281
18282 while (keyLen > 0 || ivLen > 0) {
18283 var hash = new MD5()
18284 hash.update(tmp)
18285 hash.update(password)
18286 if (salt) hash.update(salt)
18287 tmp = hash.digest()
18288
18289 var used = 0
18290
18291 if (keyLen > 0) {
18292 var keyStart = key.length - keyLen
18293 used = Math.min(keyLen, tmp.length)
18294 tmp.copy(key, keyStart, 0, used)
18295 keyLen -= used
18296 }
18297
18298 if (used < tmp.length && ivLen > 0) {
18299 var ivStart = iv.length - ivLen
18300 var length = Math.min(ivLen, tmp.length - used)
18301 tmp.copy(iv, ivStart, used, used + length)
18302 ivLen -= length
18303 }
18304 }
18305
18306 tmp.fill(0)
18307 return { key: key, iv: iv }
18308}
18309
18310module.exports = EVP_BytesToKey
18311
18312},{"md5.js":117,"safe-buffer":156}],91:[function(require,module,exports){
18313(function (Buffer){
18314'use strict'
18315var Transform = require('stream').Transform
18316var inherits = require('inherits')
18317
18318function HashBase (blockSize) {
18319 Transform.call(this)
18320
18321 this._block = new Buffer(blockSize)
18322 this._blockSize = blockSize
18323 this._blockOffset = 0
18324 this._length = [0, 0, 0, 0]
18325
18326 this._finalized = false
18327}
18328
18329inherits(HashBase, Transform)
18330
18331HashBase.prototype._transform = function (chunk, encoding, callback) {
18332 var error = null
18333 try {
18334 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
18335 this.update(chunk)
18336 } catch (err) {
18337 error = err
18338 }
18339
18340 callback(error)
18341}
18342
18343HashBase.prototype._flush = function (callback) {
18344 var error = null
18345 try {
18346 this.push(this._digest())
18347 } catch (err) {
18348 error = err
18349 }
18350
18351 callback(error)
18352}
18353
18354HashBase.prototype.update = function (data, encoding) {
18355 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
18356 if (this._finalized) throw new Error('Digest already called')
18357 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
18358
18359 // consume data
18360 var block = this._block
18361 var offset = 0
18362 while (this._blockOffset + data.length - offset >= this._blockSize) {
18363 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
18364 this._update()
18365 this._blockOffset = 0
18366 }
18367 while (offset < data.length) block[this._blockOffset++] = data[offset++]
18368
18369 // update length
18370 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
18371 this._length[j] += carry
18372 carry = (this._length[j] / 0x0100000000) | 0
18373 if (carry > 0) this._length[j] -= 0x0100000000 * carry
18374 }
18375
18376 return this
18377}
18378
18379HashBase.prototype._update = function (data) {
18380 throw new Error('_update is not implemented')
18381}
18382
18383HashBase.prototype.digest = function (encoding) {
18384 if (this._finalized) throw new Error('Digest already called')
18385 this._finalized = true
18386
18387 var digest = this._digest()
18388 if (encoding !== undefined) digest = digest.toString(encoding)
18389 return digest
18390}
18391
18392HashBase.prototype._digest = function () {
18393 throw new Error('_digest is not implemented')
18394}
18395
18396module.exports = HashBase
18397
18398}).call(this,require("buffer").Buffer)
18399},{"buffer":53,"inherits":107,"stream":172}],92:[function(require,module,exports){
18400var hash = exports;
18401
18402hash.utils = require('./hash/utils');
18403hash.common = require('./hash/common');
18404hash.sha = require('./hash/sha');
18405hash.ripemd = require('./hash/ripemd');
18406hash.hmac = require('./hash/hmac');
18407
18408// Proxy hash functions to the main object
18409hash.sha1 = hash.sha.sha1;
18410hash.sha256 = hash.sha.sha256;
18411hash.sha224 = hash.sha.sha224;
18412hash.sha384 = hash.sha.sha384;
18413hash.sha512 = hash.sha.sha512;
18414hash.ripemd160 = hash.ripemd.ripemd160;
18415
18416},{"./hash/common":93,"./hash/hmac":94,"./hash/ripemd":95,"./hash/sha":96,"./hash/utils":103}],93:[function(require,module,exports){
18417'use strict';
18418
18419var utils = require('./utils');
18420var assert = require('minimalistic-assert');
18421
18422function BlockHash() {
18423 this.pending = null;
18424 this.pendingTotal = 0;
18425 this.blockSize = this.constructor.blockSize;
18426 this.outSize = this.constructor.outSize;
18427 this.hmacStrength = this.constructor.hmacStrength;
18428 this.padLength = this.constructor.padLength / 8;
18429 this.endian = 'big';
18430
18431 this._delta8 = this.blockSize / 8;
18432 this._delta32 = this.blockSize / 32;
18433}
18434exports.BlockHash = BlockHash;
18435
18436BlockHash.prototype.update = function update(msg, enc) {
18437 // Convert message to array, pad it, and join into 32bit blocks
18438 msg = utils.toArray(msg, enc);
18439 if (!this.pending)
18440 this.pending = msg;
18441 else
18442 this.pending = this.pending.concat(msg);
18443 this.pendingTotal += msg.length;
18444
18445 // Enough data, try updating
18446 if (this.pending.length >= this._delta8) {
18447 msg = this.pending;
18448
18449 // Process pending data in blocks
18450 var r = msg.length % this._delta8;
18451 this.pending = msg.slice(msg.length - r, msg.length);
18452 if (this.pending.length === 0)
18453 this.pending = null;
18454
18455 msg = utils.join32(msg, 0, msg.length - r, this.endian);
18456 for (var i = 0; i < msg.length; i += this._delta32)
18457 this._update(msg, i, i + this._delta32);
18458 }
18459
18460 return this;
18461};
18462
18463BlockHash.prototype.digest = function digest(enc) {
18464 this.update(this._pad());
18465 assert(this.pending === null);
18466
18467 return this._digest(enc);
18468};
18469
18470BlockHash.prototype._pad = function pad() {
18471 var len = this.pendingTotal;
18472 var bytes = this._delta8;
18473 var k = bytes - ((len + this.padLength) % bytes);
18474 var res = new Array(k + this.padLength);
18475 res[0] = 0x80;
18476 for (var i = 1; i < k; i++)
18477 res[i] = 0;
18478
18479 // Append length
18480 len <<= 3;
18481 if (this.endian === 'big') {
18482 for (var t = 8; t < this.padLength; t++)
18483 res[i++] = 0;
18484
18485 res[i++] = 0;
18486 res[i++] = 0;
18487 res[i++] = 0;
18488 res[i++] = 0;
18489 res[i++] = (len >>> 24) & 0xff;
18490 res[i++] = (len >>> 16) & 0xff;
18491 res[i++] = (len >>> 8) & 0xff;
18492 res[i++] = len & 0xff;
18493 } else {
18494 res[i++] = len & 0xff;
18495 res[i++] = (len >>> 8) & 0xff;
18496 res[i++] = (len >>> 16) & 0xff;
18497 res[i++] = (len >>> 24) & 0xff;
18498 res[i++] = 0;
18499 res[i++] = 0;
18500 res[i++] = 0;
18501 res[i++] = 0;
18502
18503 for (t = 8; t < this.padLength; t++)
18504 res[i++] = 0;
18505 }
18506
18507 return res;
18508};
18509
18510},{"./utils":103,"minimalistic-assert":120}],94:[function(require,module,exports){
18511'use strict';
18512
18513var utils = require('./utils');
18514var assert = require('minimalistic-assert');
18515
18516function Hmac(hash, key, enc) {
18517 if (!(this instanceof Hmac))
18518 return new Hmac(hash, key, enc);
18519 this.Hash = hash;
18520 this.blockSize = hash.blockSize / 8;
18521 this.outSize = hash.outSize / 8;
18522 this.inner = null;
18523 this.outer = null;
18524
18525 this._init(utils.toArray(key, enc));
18526}
18527module.exports = Hmac;
18528
18529Hmac.prototype._init = function init(key) {
18530 // Shorten key, if needed
18531 if (key.length > this.blockSize)
18532 key = new this.Hash().update(key).digest();
18533 assert(key.length <= this.blockSize);
18534
18535 // Add padding to key
18536 for (var i = key.length; i < this.blockSize; i++)
18537 key.push(0);
18538
18539 for (i = 0; i < key.length; i++)
18540 key[i] ^= 0x36;
18541 this.inner = new this.Hash().update(key);
18542
18543 // 0x36 ^ 0x5c = 0x6a
18544 for (i = 0; i < key.length; i++)
18545 key[i] ^= 0x6a;
18546 this.outer = new this.Hash().update(key);
18547};
18548
18549Hmac.prototype.update = function update(msg, enc) {
18550 this.inner.update(msg, enc);
18551 return this;
18552};
18553
18554Hmac.prototype.digest = function digest(enc) {
18555 this.outer.update(this.inner.digest());
18556 return this.outer.digest(enc);
18557};
18558
18559},{"./utils":103,"minimalistic-assert":120}],95:[function(require,module,exports){
18560'use strict';
18561
18562var utils = require('./utils');
18563var common = require('./common');
18564
18565var rotl32 = utils.rotl32;
18566var sum32 = utils.sum32;
18567var sum32_3 = utils.sum32_3;
18568var sum32_4 = utils.sum32_4;
18569var BlockHash = common.BlockHash;
18570
18571function RIPEMD160() {
18572 if (!(this instanceof RIPEMD160))
18573 return new RIPEMD160();
18574
18575 BlockHash.call(this);
18576
18577 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
18578 this.endian = 'little';
18579}
18580utils.inherits(RIPEMD160, BlockHash);
18581exports.ripemd160 = RIPEMD160;
18582
18583RIPEMD160.blockSize = 512;
18584RIPEMD160.outSize = 160;
18585RIPEMD160.hmacStrength = 192;
18586RIPEMD160.padLength = 64;
18587
18588RIPEMD160.prototype._update = function update(msg, start) {
18589 var A = this.h[0];
18590 var B = this.h[1];
18591 var C = this.h[2];
18592 var D = this.h[3];
18593 var E = this.h[4];
18594 var Ah = A;
18595 var Bh = B;
18596 var Ch = C;
18597 var Dh = D;
18598 var Eh = E;
18599 for (var j = 0; j < 80; j++) {
18600 var T = sum32(
18601 rotl32(
18602 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
18603 s[j]),
18604 E);
18605 A = E;
18606 E = D;
18607 D = rotl32(C, 10);
18608 C = B;
18609 B = T;
18610 T = sum32(
18611 rotl32(
18612 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
18613 sh[j]),
18614 Eh);
18615 Ah = Eh;
18616 Eh = Dh;
18617 Dh = rotl32(Ch, 10);
18618 Ch = Bh;
18619 Bh = T;
18620 }
18621 T = sum32_3(this.h[1], C, Dh);
18622 this.h[1] = sum32_3(this.h[2], D, Eh);
18623 this.h[2] = sum32_3(this.h[3], E, Ah);
18624 this.h[3] = sum32_3(this.h[4], A, Bh);
18625 this.h[4] = sum32_3(this.h[0], B, Ch);
18626 this.h[0] = T;
18627};
18628
18629RIPEMD160.prototype._digest = function digest(enc) {
18630 if (enc === 'hex')
18631 return utils.toHex32(this.h, 'little');
18632 else
18633 return utils.split32(this.h, 'little');
18634};
18635
18636function f(j, x, y, z) {
18637 if (j <= 15)
18638 return x ^ y ^ z;
18639 else if (j <= 31)
18640 return (x & y) | ((~x) & z);
18641 else if (j <= 47)
18642 return (x | (~y)) ^ z;
18643 else if (j <= 63)
18644 return (x & z) | (y & (~z));
18645 else
18646 return x ^ (y | (~z));
18647}
18648
18649function K(j) {
18650 if (j <= 15)
18651 return 0x00000000;
18652 else if (j <= 31)
18653 return 0x5a827999;
18654 else if (j <= 47)
18655 return 0x6ed9eba1;
18656 else if (j <= 63)
18657 return 0x8f1bbcdc;
18658 else
18659 return 0xa953fd4e;
18660}
18661
18662function Kh(j) {
18663 if (j <= 15)
18664 return 0x50a28be6;
18665 else if (j <= 31)
18666 return 0x5c4dd124;
18667 else if (j <= 47)
18668 return 0x6d703ef3;
18669 else if (j <= 63)
18670 return 0x7a6d76e9;
18671 else
18672 return 0x00000000;
18673}
18674
18675var r = [
18676 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
18677 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
18678 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
18679 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
18680 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
18681];
18682
18683var rh = [
18684 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
18685 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
18686 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
18687 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
18688 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
18689];
18690
18691var s = [
18692 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
18693 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
18694 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
18695 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
18696 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
18697];
18698
18699var sh = [
18700 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
18701 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
18702 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
18703 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
18704 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
18705];
18706
18707},{"./common":93,"./utils":103}],96:[function(require,module,exports){
18708'use strict';
18709
18710exports.sha1 = require('./sha/1');
18711exports.sha224 = require('./sha/224');
18712exports.sha256 = require('./sha/256');
18713exports.sha384 = require('./sha/384');
18714exports.sha512 = require('./sha/512');
18715
18716},{"./sha/1":97,"./sha/224":98,"./sha/256":99,"./sha/384":100,"./sha/512":101}],97:[function(require,module,exports){
18717'use strict';
18718
18719var utils = require('../utils');
18720var common = require('../common');
18721var shaCommon = require('./common');
18722
18723var rotl32 = utils.rotl32;
18724var sum32 = utils.sum32;
18725var sum32_5 = utils.sum32_5;
18726var ft_1 = shaCommon.ft_1;
18727var BlockHash = common.BlockHash;
18728
18729var sha1_K = [
18730 0x5A827999, 0x6ED9EBA1,
18731 0x8F1BBCDC, 0xCA62C1D6
18732];
18733
18734function SHA1() {
18735 if (!(this instanceof SHA1))
18736 return new SHA1();
18737
18738 BlockHash.call(this);
18739 this.h = [
18740 0x67452301, 0xefcdab89, 0x98badcfe,
18741 0x10325476, 0xc3d2e1f0 ];
18742 this.W = new Array(80);
18743}
18744
18745utils.inherits(SHA1, BlockHash);
18746module.exports = SHA1;
18747
18748SHA1.blockSize = 512;
18749SHA1.outSize = 160;
18750SHA1.hmacStrength = 80;
18751SHA1.padLength = 64;
18752
18753SHA1.prototype._update = function _update(msg, start) {
18754 var W = this.W;
18755
18756 for (var i = 0; i < 16; i++)
18757 W[i] = msg[start + i];
18758
18759 for(; i < W.length; i++)
18760 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
18761
18762 var a = this.h[0];
18763 var b = this.h[1];
18764 var c = this.h[2];
18765 var d = this.h[3];
18766 var e = this.h[4];
18767
18768 for (i = 0; i < W.length; i++) {
18769 var s = ~~(i / 20);
18770 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
18771 e = d;
18772 d = c;
18773 c = rotl32(b, 30);
18774 b = a;
18775 a = t;
18776 }
18777
18778 this.h[0] = sum32(this.h[0], a);
18779 this.h[1] = sum32(this.h[1], b);
18780 this.h[2] = sum32(this.h[2], c);
18781 this.h[3] = sum32(this.h[3], d);
18782 this.h[4] = sum32(this.h[4], e);
18783};
18784
18785SHA1.prototype._digest = function digest(enc) {
18786 if (enc === 'hex')
18787 return utils.toHex32(this.h, 'big');
18788 else
18789 return utils.split32(this.h, 'big');
18790};
18791
18792},{"../common":93,"../utils":103,"./common":102}],98:[function(require,module,exports){
18793'use strict';
18794
18795var utils = require('../utils');
18796var SHA256 = require('./256');
18797
18798function SHA224() {
18799 if (!(this instanceof SHA224))
18800 return new SHA224();
18801
18802 SHA256.call(this);
18803 this.h = [
18804 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
18805 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
18806}
18807utils.inherits(SHA224, SHA256);
18808module.exports = SHA224;
18809
18810SHA224.blockSize = 512;
18811SHA224.outSize = 224;
18812SHA224.hmacStrength = 192;
18813SHA224.padLength = 64;
18814
18815SHA224.prototype._digest = function digest(enc) {
18816 // Just truncate output
18817 if (enc === 'hex')
18818 return utils.toHex32(this.h.slice(0, 7), 'big');
18819 else
18820 return utils.split32(this.h.slice(0, 7), 'big');
18821};
18822
18823
18824},{"../utils":103,"./256":99}],99:[function(require,module,exports){
18825'use strict';
18826
18827var utils = require('../utils');
18828var common = require('../common');
18829var shaCommon = require('./common');
18830var assert = require('minimalistic-assert');
18831
18832var sum32 = utils.sum32;
18833var sum32_4 = utils.sum32_4;
18834var sum32_5 = utils.sum32_5;
18835var ch32 = shaCommon.ch32;
18836var maj32 = shaCommon.maj32;
18837var s0_256 = shaCommon.s0_256;
18838var s1_256 = shaCommon.s1_256;
18839var g0_256 = shaCommon.g0_256;
18840var g1_256 = shaCommon.g1_256;
18841
18842var BlockHash = common.BlockHash;
18843
18844var sha256_K = [
18845 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
18846 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
18847 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
18848 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
18849 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
18850 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
18851 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
18852 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
18853 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
18854 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
18855 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
18856 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
18857 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
18858 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
18859 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
18860 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
18861];
18862
18863function SHA256() {
18864 if (!(this instanceof SHA256))
18865 return new SHA256();
18866
18867 BlockHash.call(this);
18868 this.h = [
18869 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
18870 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
18871 ];
18872 this.k = sha256_K;
18873 this.W = new Array(64);
18874}
18875utils.inherits(SHA256, BlockHash);
18876module.exports = SHA256;
18877
18878SHA256.blockSize = 512;
18879SHA256.outSize = 256;
18880SHA256.hmacStrength = 192;
18881SHA256.padLength = 64;
18882
18883SHA256.prototype._update = function _update(msg, start) {
18884 var W = this.W;
18885
18886 for (var i = 0; i < 16; i++)
18887 W[i] = msg[start + i];
18888 for (; i < W.length; i++)
18889 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
18890
18891 var a = this.h[0];
18892 var b = this.h[1];
18893 var c = this.h[2];
18894 var d = this.h[3];
18895 var e = this.h[4];
18896 var f = this.h[5];
18897 var g = this.h[6];
18898 var h = this.h[7];
18899
18900 assert(this.k.length === W.length);
18901 for (i = 0; i < W.length; i++) {
18902 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
18903 var T2 = sum32(s0_256(a), maj32(a, b, c));
18904 h = g;
18905 g = f;
18906 f = e;
18907 e = sum32(d, T1);
18908 d = c;
18909 c = b;
18910 b = a;
18911 a = sum32(T1, T2);
18912 }
18913
18914 this.h[0] = sum32(this.h[0], a);
18915 this.h[1] = sum32(this.h[1], b);
18916 this.h[2] = sum32(this.h[2], c);
18917 this.h[3] = sum32(this.h[3], d);
18918 this.h[4] = sum32(this.h[4], e);
18919 this.h[5] = sum32(this.h[5], f);
18920 this.h[6] = sum32(this.h[6], g);
18921 this.h[7] = sum32(this.h[7], h);
18922};
18923
18924SHA256.prototype._digest = function digest(enc) {
18925 if (enc === 'hex')
18926 return utils.toHex32(this.h, 'big');
18927 else
18928 return utils.split32(this.h, 'big');
18929};
18930
18931},{"../common":93,"../utils":103,"./common":102,"minimalistic-assert":120}],100:[function(require,module,exports){
18932'use strict';
18933
18934var utils = require('../utils');
18935
18936var SHA512 = require('./512');
18937
18938function SHA384() {
18939 if (!(this instanceof SHA384))
18940 return new SHA384();
18941
18942 SHA512.call(this);
18943 this.h = [
18944 0xcbbb9d5d, 0xc1059ed8,
18945 0x629a292a, 0x367cd507,
18946 0x9159015a, 0x3070dd17,
18947 0x152fecd8, 0xf70e5939,
18948 0x67332667, 0xffc00b31,
18949 0x8eb44a87, 0x68581511,
18950 0xdb0c2e0d, 0x64f98fa7,
18951 0x47b5481d, 0xbefa4fa4 ];
18952}
18953utils.inherits(SHA384, SHA512);
18954module.exports = SHA384;
18955
18956SHA384.blockSize = 1024;
18957SHA384.outSize = 384;
18958SHA384.hmacStrength = 192;
18959SHA384.padLength = 128;
18960
18961SHA384.prototype._digest = function digest(enc) {
18962 if (enc === 'hex')
18963 return utils.toHex32(this.h.slice(0, 12), 'big');
18964 else
18965 return utils.split32(this.h.slice(0, 12), 'big');
18966};
18967
18968},{"../utils":103,"./512":101}],101:[function(require,module,exports){
18969'use strict';
18970
18971var utils = require('../utils');
18972var common = require('../common');
18973var assert = require('minimalistic-assert');
18974
18975var rotr64_hi = utils.rotr64_hi;
18976var rotr64_lo = utils.rotr64_lo;
18977var shr64_hi = utils.shr64_hi;
18978var shr64_lo = utils.shr64_lo;
18979var sum64 = utils.sum64;
18980var sum64_hi = utils.sum64_hi;
18981var sum64_lo = utils.sum64_lo;
18982var sum64_4_hi = utils.sum64_4_hi;
18983var sum64_4_lo = utils.sum64_4_lo;
18984var sum64_5_hi = utils.sum64_5_hi;
18985var sum64_5_lo = utils.sum64_5_lo;
18986
18987var BlockHash = common.BlockHash;
18988
18989var sha512_K = [
18990 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
18991 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
18992 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
18993 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
18994 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
18995 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
18996 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
18997 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
18998 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
18999 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
19000 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
19001 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
19002 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
19003 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
19004 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
19005 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
19006 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
19007 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
19008 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
19009 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
19010 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
19011 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
19012 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
19013 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
19014 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
19015 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
19016 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
19017 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
19018 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
19019 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
19020 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
19021 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
19022 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
19023 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
19024 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
19025 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
19026 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
19027 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
19028 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
19029 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
19030];
19031
19032function SHA512() {
19033 if (!(this instanceof SHA512))
19034 return new SHA512();
19035
19036 BlockHash.call(this);
19037 this.h = [
19038 0x6a09e667, 0xf3bcc908,
19039 0xbb67ae85, 0x84caa73b,
19040 0x3c6ef372, 0xfe94f82b,
19041 0xa54ff53a, 0x5f1d36f1,
19042 0x510e527f, 0xade682d1,
19043 0x9b05688c, 0x2b3e6c1f,
19044 0x1f83d9ab, 0xfb41bd6b,
19045 0x5be0cd19, 0x137e2179 ];
19046 this.k = sha512_K;
19047 this.W = new Array(160);
19048}
19049utils.inherits(SHA512, BlockHash);
19050module.exports = SHA512;
19051
19052SHA512.blockSize = 1024;
19053SHA512.outSize = 512;
19054SHA512.hmacStrength = 192;
19055SHA512.padLength = 128;
19056
19057SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
19058 var W = this.W;
19059
19060 // 32 x 32bit words
19061 for (var i = 0; i < 32; i++)
19062 W[i] = msg[start + i];
19063 for (; i < W.length; i += 2) {
19064 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
19065 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
19066 var c1_hi = W[i - 14]; // i - 7
19067 var c1_lo = W[i - 13];
19068 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
19069 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
19070 var c3_hi = W[i - 32]; // i - 16
19071 var c3_lo = W[i - 31];
19072
19073 W[i] = sum64_4_hi(
19074 c0_hi, c0_lo,
19075 c1_hi, c1_lo,
19076 c2_hi, c2_lo,
19077 c3_hi, c3_lo);
19078 W[i + 1] = sum64_4_lo(
19079 c0_hi, c0_lo,
19080 c1_hi, c1_lo,
19081 c2_hi, c2_lo,
19082 c3_hi, c3_lo);
19083 }
19084};
19085
19086SHA512.prototype._update = function _update(msg, start) {
19087 this._prepareBlock(msg, start);
19088
19089 var W = this.W;
19090
19091 var ah = this.h[0];
19092 var al = this.h[1];
19093 var bh = this.h[2];
19094 var bl = this.h[3];
19095 var ch = this.h[4];
19096 var cl = this.h[5];
19097 var dh = this.h[6];
19098 var dl = this.h[7];
19099 var eh = this.h[8];
19100 var el = this.h[9];
19101 var fh = this.h[10];
19102 var fl = this.h[11];
19103 var gh = this.h[12];
19104 var gl = this.h[13];
19105 var hh = this.h[14];
19106 var hl = this.h[15];
19107
19108 assert(this.k.length === W.length);
19109 for (var i = 0; i < W.length; i += 2) {
19110 var c0_hi = hh;
19111 var c0_lo = hl;
19112 var c1_hi = s1_512_hi(eh, el);
19113 var c1_lo = s1_512_lo(eh, el);
19114 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
19115 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
19116 var c3_hi = this.k[i];
19117 var c3_lo = this.k[i + 1];
19118 var c4_hi = W[i];
19119 var c4_lo = W[i + 1];
19120
19121 var T1_hi = sum64_5_hi(
19122 c0_hi, c0_lo,
19123 c1_hi, c1_lo,
19124 c2_hi, c2_lo,
19125 c3_hi, c3_lo,
19126 c4_hi, c4_lo);
19127 var T1_lo = sum64_5_lo(
19128 c0_hi, c0_lo,
19129 c1_hi, c1_lo,
19130 c2_hi, c2_lo,
19131 c3_hi, c3_lo,
19132 c4_hi, c4_lo);
19133
19134 c0_hi = s0_512_hi(ah, al);
19135 c0_lo = s0_512_lo(ah, al);
19136 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
19137 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
19138
19139 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
19140 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
19141
19142 hh = gh;
19143 hl = gl;
19144
19145 gh = fh;
19146 gl = fl;
19147
19148 fh = eh;
19149 fl = el;
19150
19151 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
19152 el = sum64_lo(dl, dl, T1_hi, T1_lo);
19153
19154 dh = ch;
19155 dl = cl;
19156
19157 ch = bh;
19158 cl = bl;
19159
19160 bh = ah;
19161 bl = al;
19162
19163 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
19164 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
19165 }
19166
19167 sum64(this.h, 0, ah, al);
19168 sum64(this.h, 2, bh, bl);
19169 sum64(this.h, 4, ch, cl);
19170 sum64(this.h, 6, dh, dl);
19171 sum64(this.h, 8, eh, el);
19172 sum64(this.h, 10, fh, fl);
19173 sum64(this.h, 12, gh, gl);
19174 sum64(this.h, 14, hh, hl);
19175};
19176
19177SHA512.prototype._digest = function digest(enc) {
19178 if (enc === 'hex')
19179 return utils.toHex32(this.h, 'big');
19180 else
19181 return utils.split32(this.h, 'big');
19182};
19183
19184function ch64_hi(xh, xl, yh, yl, zh) {
19185 var r = (xh & yh) ^ ((~xh) & zh);
19186 if (r < 0)
19187 r += 0x100000000;
19188 return r;
19189}
19190
19191function ch64_lo(xh, xl, yh, yl, zh, zl) {
19192 var r = (xl & yl) ^ ((~xl) & zl);
19193 if (r < 0)
19194 r += 0x100000000;
19195 return r;
19196}
19197
19198function maj64_hi(xh, xl, yh, yl, zh) {
19199 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
19200 if (r < 0)
19201 r += 0x100000000;
19202 return r;
19203}
19204
19205function maj64_lo(xh, xl, yh, yl, zh, zl) {
19206 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
19207 if (r < 0)
19208 r += 0x100000000;
19209 return r;
19210}
19211
19212function s0_512_hi(xh, xl) {
19213 var c0_hi = rotr64_hi(xh, xl, 28);
19214 var c1_hi = rotr64_hi(xl, xh, 2); // 34
19215 var c2_hi = rotr64_hi(xl, xh, 7); // 39
19216
19217 var r = c0_hi ^ c1_hi ^ c2_hi;
19218 if (r < 0)
19219 r += 0x100000000;
19220 return r;
19221}
19222
19223function s0_512_lo(xh, xl) {
19224 var c0_lo = rotr64_lo(xh, xl, 28);
19225 var c1_lo = rotr64_lo(xl, xh, 2); // 34
19226 var c2_lo = rotr64_lo(xl, xh, 7); // 39
19227
19228 var r = c0_lo ^ c1_lo ^ c2_lo;
19229 if (r < 0)
19230 r += 0x100000000;
19231 return r;
19232}
19233
19234function s1_512_hi(xh, xl) {
19235 var c0_hi = rotr64_hi(xh, xl, 14);
19236 var c1_hi = rotr64_hi(xh, xl, 18);
19237 var c2_hi = rotr64_hi(xl, xh, 9); // 41
19238
19239 var r = c0_hi ^ c1_hi ^ c2_hi;
19240 if (r < 0)
19241 r += 0x100000000;
19242 return r;
19243}
19244
19245function s1_512_lo(xh, xl) {
19246 var c0_lo = rotr64_lo(xh, xl, 14);
19247 var c1_lo = rotr64_lo(xh, xl, 18);
19248 var c2_lo = rotr64_lo(xl, xh, 9); // 41
19249
19250 var r = c0_lo ^ c1_lo ^ c2_lo;
19251 if (r < 0)
19252 r += 0x100000000;
19253 return r;
19254}
19255
19256function g0_512_hi(xh, xl) {
19257 var c0_hi = rotr64_hi(xh, xl, 1);
19258 var c1_hi = rotr64_hi(xh, xl, 8);
19259 var c2_hi = shr64_hi(xh, xl, 7);
19260
19261 var r = c0_hi ^ c1_hi ^ c2_hi;
19262 if (r < 0)
19263 r += 0x100000000;
19264 return r;
19265}
19266
19267function g0_512_lo(xh, xl) {
19268 var c0_lo = rotr64_lo(xh, xl, 1);
19269 var c1_lo = rotr64_lo(xh, xl, 8);
19270 var c2_lo = shr64_lo(xh, xl, 7);
19271
19272 var r = c0_lo ^ c1_lo ^ c2_lo;
19273 if (r < 0)
19274 r += 0x100000000;
19275 return r;
19276}
19277
19278function g1_512_hi(xh, xl) {
19279 var c0_hi = rotr64_hi(xh, xl, 19);
19280 var c1_hi = rotr64_hi(xl, xh, 29); // 61
19281 var c2_hi = shr64_hi(xh, xl, 6);
19282
19283 var r = c0_hi ^ c1_hi ^ c2_hi;
19284 if (r < 0)
19285 r += 0x100000000;
19286 return r;
19287}
19288
19289function g1_512_lo(xh, xl) {
19290 var c0_lo = rotr64_lo(xh, xl, 19);
19291 var c1_lo = rotr64_lo(xl, xh, 29); // 61
19292 var c2_lo = shr64_lo(xh, xl, 6);
19293
19294 var r = c0_lo ^ c1_lo ^ c2_lo;
19295 if (r < 0)
19296 r += 0x100000000;
19297 return r;
19298}
19299
19300},{"../common":93,"../utils":103,"minimalistic-assert":120}],102:[function(require,module,exports){
19301'use strict';
19302
19303var utils = require('../utils');
19304var rotr32 = utils.rotr32;
19305
19306function ft_1(s, x, y, z) {
19307 if (s === 0)
19308 return ch32(x, y, z);
19309 if (s === 1 || s === 3)
19310 return p32(x, y, z);
19311 if (s === 2)
19312 return maj32(x, y, z);
19313}
19314exports.ft_1 = ft_1;
19315
19316function ch32(x, y, z) {
19317 return (x & y) ^ ((~x) & z);
19318}
19319exports.ch32 = ch32;
19320
19321function maj32(x, y, z) {
19322 return (x & y) ^ (x & z) ^ (y & z);
19323}
19324exports.maj32 = maj32;
19325
19326function p32(x, y, z) {
19327 return x ^ y ^ z;
19328}
19329exports.p32 = p32;
19330
19331function s0_256(x) {
19332 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
19333}
19334exports.s0_256 = s0_256;
19335
19336function s1_256(x) {
19337 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
19338}
19339exports.s1_256 = s1_256;
19340
19341function g0_256(x) {
19342 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
19343}
19344exports.g0_256 = g0_256;
19345
19346function g1_256(x) {
19347 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
19348}
19349exports.g1_256 = g1_256;
19350
19351},{"../utils":103}],103:[function(require,module,exports){
19352'use strict';
19353
19354var assert = require('minimalistic-assert');
19355var inherits = require('inherits');
19356
19357exports.inherits = inherits;
19358
19359function toArray(msg, enc) {
19360 if (Array.isArray(msg))
19361 return msg.slice();
19362 if (!msg)
19363 return [];
19364 var res = [];
19365 if (typeof msg === 'string') {
19366 if (!enc) {
19367 for (var i = 0; i < msg.length; i++) {
19368 var c = msg.charCodeAt(i);
19369 var hi = c >> 8;
19370 var lo = c & 0xff;
19371 if (hi)
19372 res.push(hi, lo);
19373 else
19374 res.push(lo);
19375 }
19376 } else if (enc === 'hex') {
19377 msg = msg.replace(/[^a-z0-9]+/ig, '');
19378 if (msg.length % 2 !== 0)
19379 msg = '0' + msg;
19380 for (i = 0; i < msg.length; i += 2)
19381 res.push(parseInt(msg[i] + msg[i + 1], 16));
19382 }
19383 } else {
19384 for (i = 0; i < msg.length; i++)
19385 res[i] = msg[i] | 0;
19386 }
19387 return res;
19388}
19389exports.toArray = toArray;
19390
19391function toHex(msg) {
19392 var res = '';
19393 for (var i = 0; i < msg.length; i++)
19394 res += zero2(msg[i].toString(16));
19395 return res;
19396}
19397exports.toHex = toHex;
19398
19399function htonl(w) {
19400 var res = (w >>> 24) |
19401 ((w >>> 8) & 0xff00) |
19402 ((w << 8) & 0xff0000) |
19403 ((w & 0xff) << 24);
19404 return res >>> 0;
19405}
19406exports.htonl = htonl;
19407
19408function toHex32(msg, endian) {
19409 var res = '';
19410 for (var i = 0; i < msg.length; i++) {
19411 var w = msg[i];
19412 if (endian === 'little')
19413 w = htonl(w);
19414 res += zero8(w.toString(16));
19415 }
19416 return res;
19417}
19418exports.toHex32 = toHex32;
19419
19420function zero2(word) {
19421 if (word.length === 1)
19422 return '0' + word;
19423 else
19424 return word;
19425}
19426exports.zero2 = zero2;
19427
19428function zero8(word) {
19429 if (word.length === 7)
19430 return '0' + word;
19431 else if (word.length === 6)
19432 return '00' + word;
19433 else if (word.length === 5)
19434 return '000' + word;
19435 else if (word.length === 4)
19436 return '0000' + word;
19437 else if (word.length === 3)
19438 return '00000' + word;
19439 else if (word.length === 2)
19440 return '000000' + word;
19441 else if (word.length === 1)
19442 return '0000000' + word;
19443 else
19444 return word;
19445}
19446exports.zero8 = zero8;
19447
19448function join32(msg, start, end, endian) {
19449 var len = end - start;
19450 assert(len % 4 === 0);
19451 var res = new Array(len / 4);
19452 for (var i = 0, k = start; i < res.length; i++, k += 4) {
19453 var w;
19454 if (endian === 'big')
19455 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
19456 else
19457 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
19458 res[i] = w >>> 0;
19459 }
19460 return res;
19461}
19462exports.join32 = join32;
19463
19464function split32(msg, endian) {
19465 var res = new Array(msg.length * 4);
19466 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
19467 var m = msg[i];
19468 if (endian === 'big') {
19469 res[k] = m >>> 24;
19470 res[k + 1] = (m >>> 16) & 0xff;
19471 res[k + 2] = (m >>> 8) & 0xff;
19472 res[k + 3] = m & 0xff;
19473 } else {
19474 res[k + 3] = m >>> 24;
19475 res[k + 2] = (m >>> 16) & 0xff;
19476 res[k + 1] = (m >>> 8) & 0xff;
19477 res[k] = m & 0xff;
19478 }
19479 }
19480 return res;
19481}
19482exports.split32 = split32;
19483
19484function rotr32(w, b) {
19485 return (w >>> b) | (w << (32 - b));
19486}
19487exports.rotr32 = rotr32;
19488
19489function rotl32(w, b) {
19490 return (w << b) | (w >>> (32 - b));
19491}
19492exports.rotl32 = rotl32;
19493
19494function sum32(a, b) {
19495 return (a + b) >>> 0;
19496}
19497exports.sum32 = sum32;
19498
19499function sum32_3(a, b, c) {
19500 return (a + b + c) >>> 0;
19501}
19502exports.sum32_3 = sum32_3;
19503
19504function sum32_4(a, b, c, d) {
19505 return (a + b + c + d) >>> 0;
19506}
19507exports.sum32_4 = sum32_4;
19508
19509function sum32_5(a, b, c, d, e) {
19510 return (a + b + c + d + e) >>> 0;
19511}
19512exports.sum32_5 = sum32_5;
19513
19514function sum64(buf, pos, ah, al) {
19515 var bh = buf[pos];
19516 var bl = buf[pos + 1];
19517
19518 var lo = (al + bl) >>> 0;
19519 var hi = (lo < al ? 1 : 0) + ah + bh;
19520 buf[pos] = hi >>> 0;
19521 buf[pos + 1] = lo;
19522}
19523exports.sum64 = sum64;
19524
19525function sum64_hi(ah, al, bh, bl) {
19526 var lo = (al + bl) >>> 0;
19527 var hi = (lo < al ? 1 : 0) + ah + bh;
19528 return hi >>> 0;
19529}
19530exports.sum64_hi = sum64_hi;
19531
19532function sum64_lo(ah, al, bh, bl) {
19533 var lo = al + bl;
19534 return lo >>> 0;
19535}
19536exports.sum64_lo = sum64_lo;
19537
19538function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
19539 var carry = 0;
19540 var lo = al;
19541 lo = (lo + bl) >>> 0;
19542 carry += lo < al ? 1 : 0;
19543 lo = (lo + cl) >>> 0;
19544 carry += lo < cl ? 1 : 0;
19545 lo = (lo + dl) >>> 0;
19546 carry += lo < dl ? 1 : 0;
19547
19548 var hi = ah + bh + ch + dh + carry;
19549 return hi >>> 0;
19550}
19551exports.sum64_4_hi = sum64_4_hi;
19552
19553function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
19554 var lo = al + bl + cl + dl;
19555 return lo >>> 0;
19556}
19557exports.sum64_4_lo = sum64_4_lo;
19558
19559function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
19560 var carry = 0;
19561 var lo = al;
19562 lo = (lo + bl) >>> 0;
19563 carry += lo < al ? 1 : 0;
19564 lo = (lo + cl) >>> 0;
19565 carry += lo < cl ? 1 : 0;
19566 lo = (lo + dl) >>> 0;
19567 carry += lo < dl ? 1 : 0;
19568 lo = (lo + el) >>> 0;
19569 carry += lo < el ? 1 : 0;
19570
19571 var hi = ah + bh + ch + dh + eh + carry;
19572 return hi >>> 0;
19573}
19574exports.sum64_5_hi = sum64_5_hi;
19575
19576function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
19577 var lo = al + bl + cl + dl + el;
19578
19579 return lo >>> 0;
19580}
19581exports.sum64_5_lo = sum64_5_lo;
19582
19583function rotr64_hi(ah, al, num) {
19584 var r = (al << (32 - num)) | (ah >>> num);
19585 return r >>> 0;
19586}
19587exports.rotr64_hi = rotr64_hi;
19588
19589function rotr64_lo(ah, al, num) {
19590 var r = (ah << (32 - num)) | (al >>> num);
19591 return r >>> 0;
19592}
19593exports.rotr64_lo = rotr64_lo;
19594
19595function shr64_hi(ah, al, num) {
19596 return ah >>> num;
19597}
19598exports.shr64_hi = shr64_hi;
19599
19600function shr64_lo(ah, al, num) {
19601 var r = (ah << (32 - num)) | (al >>> num);
19602 return r >>> 0;
19603}
19604exports.shr64_lo = shr64_lo;
19605
19606},{"inherits":107,"minimalistic-assert":120}],104:[function(require,module,exports){
19607'use strict';
19608
19609var hash = require('hash.js');
19610var utils = require('minimalistic-crypto-utils');
19611var assert = require('minimalistic-assert');
19612
19613function HmacDRBG(options) {
19614 if (!(this instanceof HmacDRBG))
19615 return new HmacDRBG(options);
19616 this.hash = options.hash;
19617 this.predResist = !!options.predResist;
19618
19619 this.outLen = this.hash.outSize;
19620 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
19621
19622 this._reseed = null;
19623 this.reseedInterval = null;
19624 this.K = null;
19625 this.V = null;
19626
19627 var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
19628 var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
19629 var pers = utils.toArray(options.pers, options.persEnc || 'hex');
19630 assert(entropy.length >= (this.minEntropy / 8),
19631 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
19632 this._init(entropy, nonce, pers);
19633}
19634module.exports = HmacDRBG;
19635
19636HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
19637 var seed = entropy.concat(nonce).concat(pers);
19638
19639 this.K = new Array(this.outLen / 8);
19640 this.V = new Array(this.outLen / 8);
19641 for (var i = 0; i < this.V.length; i++) {
19642 this.K[i] = 0x00;
19643 this.V[i] = 0x01;
19644 }
19645
19646 this._update(seed);
19647 this._reseed = 1;
19648 this.reseedInterval = 0x1000000000000; // 2^48
19649};
19650
19651HmacDRBG.prototype._hmac = function hmac() {
19652 return new hash.hmac(this.hash, this.K);
19653};
19654
19655HmacDRBG.prototype._update = function update(seed) {
19656 var kmac = this._hmac()
19657 .update(this.V)
19658 .update([ 0x00 ]);
19659 if (seed)
19660 kmac = kmac.update(seed);
19661 this.K = kmac.digest();
19662 this.V = this._hmac().update(this.V).digest();
19663 if (!seed)
19664 return;
19665
19666 this.K = this._hmac()
19667 .update(this.V)
19668 .update([ 0x01 ])
19669 .update(seed)
19670 .digest();
19671 this.V = this._hmac().update(this.V).digest();
19672};
19673
19674HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
19675 // Optional entropy enc
19676 if (typeof entropyEnc !== 'string') {
19677 addEnc = add;
19678 add = entropyEnc;
19679 entropyEnc = null;
19680 }
19681
19682 entropy = utils.toArray(entropy, entropyEnc);
19683 add = utils.toArray(add, addEnc);
19684
19685 assert(entropy.length >= (this.minEntropy / 8),
19686 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
19687
19688 this._update(entropy.concat(add || []));
19689 this._reseed = 1;
19690};
19691
19692HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
19693 if (this._reseed > this.reseedInterval)
19694 throw new Error('Reseed is required');
19695
19696 // Optional encoding
19697 if (typeof enc !== 'string') {
19698 addEnc = add;
19699 add = enc;
19700 enc = null;
19701 }
19702
19703 // Optional additional data
19704 if (add) {
19705 add = utils.toArray(add, addEnc || 'hex');
19706 this._update(add);
19707 }
19708
19709 var temp = [];
19710 while (temp.length < len) {
19711 this.V = this._hmac().update(this.V).digest();
19712 temp = temp.concat(this.V);
19713 }
19714
19715 var res = temp.slice(0, len);
19716 this._update(add);
19717 this._reseed++;
19718 return utils.encode(res, enc);
19719};
19720
19721},{"hash.js":92,"minimalistic-assert":120,"minimalistic-crypto-utils":121}],105:[function(require,module,exports){
19722exports.read = function (buffer, offset, isLE, mLen, nBytes) {
19723 var e, m
19724 var eLen = nBytes * 8 - mLen - 1
19725 var eMax = (1 << eLen) - 1
19726 var eBias = eMax >> 1
19727 var nBits = -7
19728 var i = isLE ? (nBytes - 1) : 0
19729 var d = isLE ? -1 : 1
19730 var s = buffer[offset + i]
19731
19732 i += d
19733
19734 e = s & ((1 << (-nBits)) - 1)
19735 s >>= (-nBits)
19736 nBits += eLen
19737 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
19738
19739 m = e & ((1 << (-nBits)) - 1)
19740 e >>= (-nBits)
19741 nBits += mLen
19742 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
19743
19744 if (e === 0) {
19745 e = 1 - eBias
19746 } else if (e === eMax) {
19747 return m ? NaN : ((s ? -1 : 1) * Infinity)
19748 } else {
19749 m = m + Math.pow(2, mLen)
19750 e = e - eBias
19751 }
19752 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
19753}
19754
19755exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
19756 var e, m, c
19757 var eLen = nBytes * 8 - mLen - 1
19758 var eMax = (1 << eLen) - 1
19759 var eBias = eMax >> 1
19760 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
19761 var i = isLE ? 0 : (nBytes - 1)
19762 var d = isLE ? 1 : -1
19763 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
19764
19765 value = Math.abs(value)
19766
19767 if (isNaN(value) || value === Infinity) {
19768 m = isNaN(value) ? 1 : 0
19769 e = eMax
19770 } else {
19771 e = Math.floor(Math.log(value) / Math.LN2)
19772 if (value * (c = Math.pow(2, -e)) < 1) {
19773 e--
19774 c *= 2
19775 }
19776 if (e + eBias >= 1) {
19777 value += rt / c
19778 } else {
19779 value += rt * Math.pow(2, 1 - eBias)
19780 }
19781 if (value * c >= 2) {
19782 e++
19783 c /= 2
19784 }
19785
19786 if (e + eBias >= eMax) {
19787 m = 0
19788 e = eMax
19789 } else if (e + eBias >= 1) {
19790 m = (value * c - 1) * Math.pow(2, mLen)
19791 e = e + eBias
19792 } else {
19793 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
19794 e = 0
19795 }
19796 }
19797
19798 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
19799
19800 e = (e << mLen) | m
19801 eLen += mLen
19802 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
19803
19804 buffer[offset + i - d] |= s * 128
19805}
19806
19807},{}],106:[function(require,module,exports){
19808
19809var indexOf = [].indexOf;
19810
19811module.exports = function(arr, obj){
19812 if (indexOf) return arr.indexOf(obj);
19813 for (var i = 0; i < arr.length; ++i) {
19814 if (arr[i] === obj) return i;
19815 }
19816 return -1;
19817};
19818},{}],107:[function(require,module,exports){
19819if (typeof Object.create === 'function') {
19820 // implementation from standard node.js 'util' module
19821 module.exports = function inherits(ctor, superCtor) {
19822 ctor.super_ = superCtor
19823 ctor.prototype = Object.create(superCtor.prototype, {
19824 constructor: {
19825 value: ctor,
19826 enumerable: false,
19827 writable: true,
19828 configurable: true
19829 }
19830 });
19831 };
19832} else {
19833 // old school shim for old browsers
19834 module.exports = function inherits(ctor, superCtor) {
19835 ctor.super_ = superCtor
19836 var TempCtor = function () {}
19837 TempCtor.prototype = superCtor.prototype
19838 ctor.prototype = new TempCtor()
19839 ctor.prototype.constructor = ctor
19840 }
19841}
19842
19843},{}],108:[function(require,module,exports){
19844/*!
19845 * Determine if an object is a Buffer
19846 *
19847 * @author Feross Aboukhadijeh <https://feross.org>
19848 * @license MIT
19849 */
19850
19851// The _isBuffer check is for Safari 5-7 support, because it's missing
19852// Object.prototype.constructor. Remove this eventually
19853module.exports = function (obj) {
19854 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
19855}
19856
19857function isBuffer (obj) {
19858 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
19859}
19860
19861// For Node v0.10 support. Remove this eventually.
19862function isSlowBuffer (obj) {
19863 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
19864}
19865
19866},{}],109:[function(require,module,exports){
19867var toString = {}.toString;
19868
19869module.exports = Array.isArray || function (arr) {
19870 return toString.call(arr) == '[object Array]';
19871};
19872
19873},{}],110:[function(require,module,exports){
19874/*
19875 A JavaScript implementation of the SHA family of hashes, as
19876 defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding
19877 HMAC implementation as defined in FIPS PUB 198a
19878
19879 Copyright Brian Turek 2008-2017
19880 Distributed under the BSD License
19881 See http://caligatio.github.com/jsSHA/ for more information
19882
19883 Several functions taken from Paul Johnston
19884*/
19885'use strict';(function(Y){function C(c,a,b){var e=0,h=[],n=0,g,l,d,f,m,q,u,r,I=!1,v=[],w=[],t,y=!1,z=!1,x=-1;b=b||{};g=b.encoding||"UTF8";t=b.numRounds||1;if(t!==parseInt(t,10)||1>t)throw Error("numRounds must a integer >= 1");if("SHA-1"===c)m=512,q=K,u=Z,f=160,r=function(a){return a.slice()};else if(0===c.lastIndexOf("SHA-",0))if(q=function(a,b){return L(a,b,c)},u=function(a,b,h,e){var k,f;if("SHA-224"===c||"SHA-256"===c)k=(b+65>>>9<<4)+15,f=16;else if("SHA-384"===c||"SHA-512"===c)k=(b+129>>>10<<
198865)+31,f=32;else throw Error("Unexpected error in SHA-2 implementation");for(;a.length<=k;)a.push(0);a[b>>>5]|=128<<24-b%32;b=b+h;a[k]=b&4294967295;a[k-1]=b/4294967296|0;h=a.length;for(b=0;b<h;b+=f)e=L(a.slice(b,b+f),e,c);if("SHA-224"===c)a=[e[0],e[1],e[2],e[3],e[4],e[5],e[6]];else if("SHA-256"===c)a=e;else if("SHA-384"===c)a=[e[0].a,e[0].b,e[1].a,e[1].b,e[2].a,e[2].b,e[3].a,e[3].b,e[4].a,e[4].b,e[5].a,e[5].b];else if("SHA-512"===c)a=[e[0].a,e[0].b,e[1].a,e[1].b,e[2].a,e[2].b,e[3].a,e[3].b,e[4].a,
19887e[4].b,e[5].a,e[5].b,e[6].a,e[6].b,e[7].a,e[7].b];else throw Error("Unexpected error in SHA-2 implementation");return a},r=function(a){return a.slice()},"SHA-224"===c)m=512,f=224;else if("SHA-256"===c)m=512,f=256;else if("SHA-384"===c)m=1024,f=384;else if("SHA-512"===c)m=1024,f=512;else throw Error("Chosen SHA variant is not supported");else if(0===c.lastIndexOf("SHA3-",0)||0===c.lastIndexOf("SHAKE",0)){var F=6;q=D;r=function(a){var c=[],e;for(e=0;5>e;e+=1)c[e]=a[e].slice();return c};x=1;if("SHA3-224"===
19888c)m=1152,f=224;else if("SHA3-256"===c)m=1088,f=256;else if("SHA3-384"===c)m=832,f=384;else if("SHA3-512"===c)m=576,f=512;else if("SHAKE128"===c)m=1344,f=-1,F=31,z=!0;else if("SHAKE256"===c)m=1088,f=-1,F=31,z=!0;else throw Error("Chosen SHA variant is not supported");u=function(a,c,e,b,h){e=m;var k=F,f,g=[],n=e>>>5,l=0,d=c>>>5;for(f=0;f<d&&c>=e;f+=n)b=D(a.slice(f,f+n),b),c-=e;a=a.slice(f);for(c%=e;a.length<n;)a.push(0);f=c>>>3;a[f>>2]^=k<<f%4*8;a[n-1]^=2147483648;for(b=D(a,b);32*g.length<h;){a=b[l%
198895][l/5|0];g.push(a.b);if(32*g.length>=h)break;g.push(a.a);l+=1;0===64*l%e&&D(null,b)}return g}}else throw Error("Chosen SHA variant is not supported");d=M(a,g,x);l=A(c);this.setHMACKey=function(a,b,h){var k;if(!0===I)throw Error("HMAC key already set");if(!0===y)throw Error("Cannot set HMAC key after calling update");if(!0===z)throw Error("SHAKE is not supported for HMAC");g=(h||{}).encoding||"UTF8";b=M(b,g,x)(a);a=b.binLen;b=b.value;k=m>>>3;h=k/4-1;if(k<a/8){for(b=u(b,a,0,A(c),f);b.length<=h;)b.push(0);
19890b[h]&=4294967040}else if(k>a/8){for(;b.length<=h;)b.push(0);b[h]&=4294967040}for(a=0;a<=h;a+=1)v[a]=b[a]^909522486,w[a]=b[a]^1549556828;l=q(v,l);e=m;I=!0};this.update=function(a){var c,b,k,f=0,g=m>>>5;c=d(a,h,n);a=c.binLen;b=c.value;c=a>>>5;for(k=0;k<c;k+=g)f+m<=a&&(l=q(b.slice(k,k+g),l),f+=m);e+=f;h=b.slice(f>>>5);n=a%m;y=!0};this.getHash=function(a,b){var k,g,d,m;if(!0===I)throw Error("Cannot call getHash after setting HMAC key");d=N(b);if(!0===z){if(-1===d.shakeLen)throw Error("shakeLen must be specified in options");
19891f=d.shakeLen}switch(a){case "HEX":k=function(a){return O(a,f,x,d)};break;case "B64":k=function(a){return P(a,f,x,d)};break;case "BYTES":k=function(a){return Q(a,f,x)};break;case "ARRAYBUFFER":try{g=new ArrayBuffer(0)}catch(p){throw Error("ARRAYBUFFER not supported by this environment");}k=function(a){return R(a,f,x)};break;default:throw Error("format must be HEX, B64, BYTES, or ARRAYBUFFER");}m=u(h.slice(),n,e,r(l),f);for(g=1;g<t;g+=1)!0===z&&0!==f%32&&(m[m.length-1]&=16777215>>>24-f%32),m=u(m,f,
198920,A(c),f);return k(m)};this.getHMAC=function(a,b){var k,g,d,p;if(!1===I)throw Error("Cannot call getHMAC without first setting HMAC key");d=N(b);switch(a){case "HEX":k=function(a){return O(a,f,x,d)};break;case "B64":k=function(a){return P(a,f,x,d)};break;case "BYTES":k=function(a){return Q(a,f,x)};break;case "ARRAYBUFFER":try{k=new ArrayBuffer(0)}catch(v){throw Error("ARRAYBUFFER not supported by this environment");}k=function(a){return R(a,f,x)};break;default:throw Error("outputFormat must be HEX, B64, BYTES, or ARRAYBUFFER");
19893}g=u(h.slice(),n,e,r(l),f);p=q(w,A(c));p=u(g,f,m,p,f);return k(p)}}function b(c,a){this.a=c;this.b=a}function O(c,a,b,e){var h="";a/=8;var n,g,d;d=-1===b?3:0;for(n=0;n<a;n+=1)g=c[n>>>2]>>>8*(d+n%4*b),h+="0123456789abcdef".charAt(g>>>4&15)+"0123456789abcdef".charAt(g&15);return e.outputUpper?h.toUpperCase():h}function P(c,a,b,e){var h="",n=a/8,g,d,p,f;f=-1===b?3:0;for(g=0;g<n;g+=3)for(d=g+1<n?c[g+1>>>2]:0,p=g+2<n?c[g+2>>>2]:0,p=(c[g>>>2]>>>8*(f+g%4*b)&255)<<16|(d>>>8*(f+(g+1)%4*b)&255)<<8|p>>>8*(f+
19894(g+2)%4*b)&255,d=0;4>d;d+=1)8*g+6*d<=a?h+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(p>>>6*(3-d)&63):h+=e.b64Pad;return h}function Q(c,a,b){var e="";a/=8;var h,d,g;g=-1===b?3:0;for(h=0;h<a;h+=1)d=c[h>>>2]>>>8*(g+h%4*b)&255,e+=String.fromCharCode(d);return e}function R(c,a,b){a/=8;var e,h=new ArrayBuffer(a),d,g;g=new Uint8Array(h);d=-1===b?3:0;for(e=0;e<a;e+=1)g[e]=c[e>>>2]>>>8*(d+e%4*b)&255;return h}function N(c){var a={outputUpper:!1,b64Pad:"=",shakeLen:-1};c=c||{};
19895a.outputUpper=c.outputUpper||!1;!0===c.hasOwnProperty("b64Pad")&&(a.b64Pad=c.b64Pad);if(!0===c.hasOwnProperty("shakeLen")){if(0!==c.shakeLen%8)throw Error("shakeLen must be a multiple of 8");a.shakeLen=c.shakeLen}if("boolean"!==typeof a.outputUpper)throw Error("Invalid outputUpper formatting option");if("string"!==typeof a.b64Pad)throw Error("Invalid b64Pad formatting option");return a}function M(c,a,b){switch(a){case "UTF8":case "UTF16BE":case "UTF16LE":break;default:throw Error("encoding must be UTF8, UTF16BE, or UTF16LE");
19896}switch(c){case "HEX":c=function(a,c,d){var g=a.length,l,p,f,m,q,u;if(0!==g%2)throw Error("String of HEX type must be in byte increments");c=c||[0];d=d||0;q=d>>>3;u=-1===b?3:0;for(l=0;l<g;l+=2){p=parseInt(a.substr(l,2),16);if(isNaN(p))throw Error("String of HEX type contains invalid characters");m=(l>>>1)+q;for(f=m>>>2;c.length<=f;)c.push(0);c[f]|=p<<8*(u+m%4*b)}return{value:c,binLen:4*g+d}};break;case "TEXT":c=function(c,h,d){var g,l,p=0,f,m,q,u,r,t;h=h||[0];d=d||0;q=d>>>3;if("UTF8"===a)for(t=-1===
19897b?3:0,f=0;f<c.length;f+=1)for(g=c.charCodeAt(f),l=[],128>g?l.push(g):2048>g?(l.push(192|g>>>6),l.push(128|g&63)):55296>g||57344<=g?l.push(224|g>>>12,128|g>>>6&63,128|g&63):(f+=1,g=65536+((g&1023)<<10|c.charCodeAt(f)&1023),l.push(240|g>>>18,128|g>>>12&63,128|g>>>6&63,128|g&63)),m=0;m<l.length;m+=1){r=p+q;for(u=r>>>2;h.length<=u;)h.push(0);h[u]|=l[m]<<8*(t+r%4*b);p+=1}else if("UTF16BE"===a||"UTF16LE"===a)for(t=-1===b?2:0,l="UTF16LE"===a&&1!==b||"UTF16LE"!==a&&1===b,f=0;f<c.length;f+=1){g=c.charCodeAt(f);
19898!0===l&&(m=g&255,g=m<<8|g>>>8);r=p+q;for(u=r>>>2;h.length<=u;)h.push(0);h[u]|=g<<8*(t+r%4*b);p+=2}return{value:h,binLen:8*p+d}};break;case "B64":c=function(a,c,d){var g=0,l,p,f,m,q,u,r,t;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw Error("Invalid character in base-64 string");p=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==p&&p<a.length)throw Error("Invalid '=' found in base-64 string");c=c||[0];d=d||0;u=d>>>3;t=-1===b?3:0;for(p=0;p<a.length;p+=4){q=a.substr(p,4);for(f=m=0;f<q.length;f+=1)l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(q[f]),
19899m|=l<<18-6*f;for(f=0;f<q.length-1;f+=1){r=g+u;for(l=r>>>2;c.length<=l;)c.push(0);c[l]|=(m>>>16-8*f&255)<<8*(t+r%4*b);g+=1}}return{value:c,binLen:8*g+d}};break;case "BYTES":c=function(a,c,d){var g,l,p,f,m,q;c=c||[0];d=d||0;p=d>>>3;q=-1===b?3:0;for(l=0;l<a.length;l+=1)g=a.charCodeAt(l),m=l+p,f=m>>>2,c.length<=f&&c.push(0),c[f]|=g<<8*(q+m%4*b);return{value:c,binLen:8*a.length+d}};break;case "ARRAYBUFFER":try{c=new ArrayBuffer(0)}catch(e){throw Error("ARRAYBUFFER not supported by this environment");}c=
19900function(a,c,d){var g,l,p,f,m,q;c=c||[0];d=d||0;l=d>>>3;m=-1===b?3:0;q=new Uint8Array(a);for(g=0;g<a.byteLength;g+=1)f=g+l,p=f>>>2,c.length<=p&&c.push(0),c[p]|=q[g]<<8*(m+f%4*b);return{value:c,binLen:8*a.byteLength+d}};break;default:throw Error("format must be HEX, TEXT, B64, BYTES, or ARRAYBUFFER");}return c}function y(c,a){return c<<a|c>>>32-a}function S(c,a){return 32<a?(a-=32,new b(c.b<<a|c.a>>>32-a,c.a<<a|c.b>>>32-a)):0!==a?new b(c.a<<a|c.b>>>32-a,c.b<<a|c.a>>>32-a):c}function w(c,a){return c>>>
19901a|c<<32-a}function t(c,a){var k=null,k=new b(c.a,c.b);return k=32>=a?new b(k.a>>>a|k.b<<32-a&4294967295,k.b>>>a|k.a<<32-a&4294967295):new b(k.b>>>a-32|k.a<<64-a&4294967295,k.a>>>a-32|k.b<<64-a&4294967295)}function T(c,a){var k=null;return k=32>=a?new b(c.a>>>a,c.b>>>a|c.a<<32-a&4294967295):new b(0,c.a>>>a-32)}function aa(c,a,b){return c&a^~c&b}function ba(c,a,k){return new b(c.a&a.a^~c.a&k.a,c.b&a.b^~c.b&k.b)}function U(c,a,b){return c&a^c&b^a&b}function ca(c,a,k){return new b(c.a&a.a^c.a&k.a^a.a&
19902k.a,c.b&a.b^c.b&k.b^a.b&k.b)}function da(c){return w(c,2)^w(c,13)^w(c,22)}function ea(c){var a=t(c,28),k=t(c,34);c=t(c,39);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function fa(c){return w(c,6)^w(c,11)^w(c,25)}function ga(c){var a=t(c,14),k=t(c,18);c=t(c,41);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function ha(c){return w(c,7)^w(c,18)^c>>>3}function ia(c){var a=t(c,1),k=t(c,8);c=T(c,7);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function ja(c){return w(c,17)^w(c,19)^c>>>10}function ka(c){var a=t(c,19),k=t(c,61);
19903c=T(c,6);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function G(c,a){var b=(c&65535)+(a&65535);return((c>>>16)+(a>>>16)+(b>>>16)&65535)<<16|b&65535}function la(c,a,b,e){var h=(c&65535)+(a&65535)+(b&65535)+(e&65535);return((c>>>16)+(a>>>16)+(b>>>16)+(e>>>16)+(h>>>16)&65535)<<16|h&65535}function H(c,a,b,e,h){var d=(c&65535)+(a&65535)+(b&65535)+(e&65535)+(h&65535);return((c>>>16)+(a>>>16)+(b>>>16)+(e>>>16)+(h>>>16)+(d>>>16)&65535)<<16|d&65535}function ma(c,a){var d,e,h;d=(c.b&65535)+(a.b&65535);e=(c.b>>>16)+
19904(a.b>>>16)+(d>>>16);h=(e&65535)<<16|d&65535;d=(c.a&65535)+(a.a&65535)+(e>>>16);e=(c.a>>>16)+(a.a>>>16)+(d>>>16);return new b((e&65535)<<16|d&65535,h)}function na(c,a,d,e){var h,n,g;h=(c.b&65535)+(a.b&65535)+(d.b&65535)+(e.b&65535);n=(c.b>>>16)+(a.b>>>16)+(d.b>>>16)+(e.b>>>16)+(h>>>16);g=(n&65535)<<16|h&65535;h=(c.a&65535)+(a.a&65535)+(d.a&65535)+(e.a&65535)+(n>>>16);n=(c.a>>>16)+(a.a>>>16)+(d.a>>>16)+(e.a>>>16)+(h>>>16);return new b((n&65535)<<16|h&65535,g)}function oa(c,a,d,e,h){var n,g,l;n=(c.b&
1990565535)+(a.b&65535)+(d.b&65535)+(e.b&65535)+(h.b&65535);g=(c.b>>>16)+(a.b>>>16)+(d.b>>>16)+(e.b>>>16)+(h.b>>>16)+(n>>>16);l=(g&65535)<<16|n&65535;n=(c.a&65535)+(a.a&65535)+(d.a&65535)+(e.a&65535)+(h.a&65535)+(g>>>16);g=(c.a>>>16)+(a.a>>>16)+(d.a>>>16)+(e.a>>>16)+(h.a>>>16)+(n>>>16);return new b((g&65535)<<16|n&65535,l)}function B(c,a){return new b(c.a^a.a,c.b^a.b)}function A(c){var a=[],d;if("SHA-1"===c)a=[1732584193,4023233417,2562383102,271733878,3285377520];else if(0===c.lastIndexOf("SHA-",0))switch(a=
19906[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428],d=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],c){case "SHA-224":break;case "SHA-256":a=d;break;case "SHA-384":a=[new b(3418070365,a[0]),new b(1654270250,a[1]),new b(2438529370,a[2]),new b(355462360,a[3]),new b(1731405415,a[4]),new b(41048885895,a[5]),new b(3675008525,a[6]),new b(1203062813,a[7])];break;case "SHA-512":a=[new b(d[0],4089235720),new b(d[1],2227873595),
19907new b(d[2],4271175723),new b(d[3],1595750129),new b(d[4],2917565137),new b(d[5],725511199),new b(d[6],4215389547),new b(d[7],327033209)];break;default:throw Error("Unknown SHA variant");}else if(0===c.lastIndexOf("SHA3-",0)||0===c.lastIndexOf("SHAKE",0))for(c=0;5>c;c+=1)a[c]=[new b(0,0),new b(0,0),new b(0,0),new b(0,0),new b(0,0)];else throw Error("No SHA variants supported");return a}function K(c,a){var b=[],e,d,n,g,l,p,f;e=a[0];d=a[1];n=a[2];g=a[3];l=a[4];for(f=0;80>f;f+=1)b[f]=16>f?c[f]:y(b[f-
199083]^b[f-8]^b[f-14]^b[f-16],1),p=20>f?H(y(e,5),d&n^~d&g,l,1518500249,b[f]):40>f?H(y(e,5),d^n^g,l,1859775393,b[f]):60>f?H(y(e,5),U(d,n,g),l,2400959708,b[f]):H(y(e,5),d^n^g,l,3395469782,b[f]),l=g,g=n,n=y(d,30),d=e,e=p;a[0]=G(e,a[0]);a[1]=G(d,a[1]);a[2]=G(n,a[2]);a[3]=G(g,a[3]);a[4]=G(l,a[4]);return a}function Z(c,a,b,e){var d;for(d=(a+65>>>9<<4)+15;c.length<=d;)c.push(0);c[a>>>5]|=128<<24-a%32;a+=b;c[d]=a&4294967295;c[d-1]=a/4294967296|0;a=c.length;for(d=0;d<a;d+=16)e=K(c.slice(d,d+16),e);return e}function L(c,
19909a,k){var e,h,n,g,l,p,f,m,q,u,r,t,v,w,y,A,z,x,F,B,C,D,E=[],J;if("SHA-224"===k||"SHA-256"===k)u=64,t=1,D=Number,v=G,w=la,y=H,A=ha,z=ja,x=da,F=fa,C=U,B=aa,J=d;else if("SHA-384"===k||"SHA-512"===k)u=80,t=2,D=b,v=ma,w=na,y=oa,A=ia,z=ka,x=ea,F=ga,C=ca,B=ba,J=V;else throw Error("Unexpected error in SHA-2 implementation");k=a[0];e=a[1];h=a[2];n=a[3];g=a[4];l=a[5];p=a[6];f=a[7];for(r=0;r<u;r+=1)16>r?(q=r*t,m=c.length<=q?0:c[q],q=c.length<=q+1?0:c[q+1],E[r]=new D(m,q)):E[r]=w(z(E[r-2]),E[r-7],A(E[r-15]),E[r-
1991016]),m=y(f,F(g),B(g,l,p),J[r],E[r]),q=v(x(k),C(k,e,h)),f=p,p=l,l=g,g=v(n,m),n=h,h=e,e=k,k=v(m,q);a[0]=v(k,a[0]);a[1]=v(e,a[1]);a[2]=v(h,a[2]);a[3]=v(n,a[3]);a[4]=v(g,a[4]);a[5]=v(l,a[5]);a[6]=v(p,a[6]);a[7]=v(f,a[7]);return a}function D(c,a){var d,e,h,n,g=[],l=[];if(null!==c)for(e=0;e<c.length;e+=2)a[(e>>>1)%5][(e>>>1)/5|0]=B(a[(e>>>1)%5][(e>>>1)/5|0],new b(c[e+1],c[e]));for(d=0;24>d;d+=1){n=A("SHA3-");for(e=0;5>e;e+=1){h=a[e][0];var p=a[e][1],f=a[e][2],m=a[e][3],q=a[e][4];g[e]=new b(h.a^p.a^f.a^
19911m.a^q.a,h.b^p.b^f.b^m.b^q.b)}for(e=0;5>e;e+=1)l[e]=B(g[(e+4)%5],S(g[(e+1)%5],1));for(e=0;5>e;e+=1)for(h=0;5>h;h+=1)a[e][h]=B(a[e][h],l[e]);for(e=0;5>e;e+=1)for(h=0;5>h;h+=1)n[h][(2*e+3*h)%5]=S(a[e][h],W[e][h]);for(e=0;5>e;e+=1)for(h=0;5>h;h+=1)a[e][h]=B(n[e][h],new b(~n[(e+1)%5][h].a&n[(e+2)%5][h].a,~n[(e+1)%5][h].b&n[(e+2)%5][h].b));a[0][0]=B(a[0][0],X[d])}return a}var d,V,W,X;d=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,
199121426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,
199132227730452,2361852424,2428436474,2756734187,3204031479,3329325298];V=[new b(d[0],3609767458),new b(d[1],602891725),new b(d[2],3964484399),new b(d[3],2173295548),new b(d[4],4081628472),new b(d[5],3053834265),new b(d[6],2937671579),new b(d[7],3664609560),new b(d[8],2734883394),new b(d[9],1164996542),new b(d[10],1323610764),new b(d[11],3590304994),new b(d[12],4068182383),new b(d[13],991336113),new b(d[14],633803317),new b(d[15],3479774868),new b(d[16],2666613458),new b(d[17],944711139),new b(d[18],2341262773),
19914new b(d[19],2007800933),new b(d[20],1495990901),new b(d[21],1856431235),new b(d[22],3175218132),new b(d[23],2198950837),new b(d[24],3999719339),new b(d[25],766784016),new b(d[26],2566594879),new b(d[27],3203337956),new b(d[28],1034457026),new b(d[29],2466948901),new b(d[30],3758326383),new b(d[31],168717936),new b(d[32],1188179964),new b(d[33],1546045734),new b(d[34],1522805485),new b(d[35],2643833823),new b(d[36],2343527390),new b(d[37],1014477480),new b(d[38],1206759142),new b(d[39],344077627),
19915new b(d[40],1290863460),new b(d[41],3158454273),new b(d[42],3505952657),new b(d[43],106217008),new b(d[44],3606008344),new b(d[45],1432725776),new b(d[46],1467031594),new b(d[47],851169720),new b(d[48],3100823752),new b(d[49],1363258195),new b(d[50],3750685593),new b(d[51],3785050280),new b(d[52],3318307427),new b(d[53],3812723403),new b(d[54],2003034995),new b(d[55],3602036899),new b(d[56],1575990012),new b(d[57],1125592928),new b(d[58],2716904306),new b(d[59],442776044),new b(d[60],593698344),new b(d[61],
199163733110249),new b(d[62],2999351573),new b(d[63],3815920427),new b(3391569614,3928383900),new b(3515267271,566280711),new b(3940187606,3454069534),new b(4118630271,4000239992),new b(116418474,1914138554),new b(174292421,2731055270),new b(289380356,3203993006),new b(460393269,320620315),new b(685471733,587496836),new b(852142971,1086792851),new b(1017036298,365543100),new b(1126000580,2618297676),new b(1288033470,3409855158),new b(1501505948,4234509866),new b(1607167915,987167468),new b(1816402316,
199171246189591)];X=[new b(0,1),new b(0,32898),new b(2147483648,32906),new b(2147483648,2147516416),new b(0,32907),new b(0,2147483649),new b(2147483648,2147516545),new b(2147483648,32777),new b(0,138),new b(0,136),new b(0,2147516425),new b(0,2147483658),new b(0,2147516555),new b(2147483648,139),new b(2147483648,32905),new b(2147483648,32771),new b(2147483648,32770),new b(2147483648,128),new b(0,32778),new b(2147483648,2147483658),new b(2147483648,2147516545),new b(2147483648,32896),new b(0,2147483649),
19918new b(2147483648,2147516424)];W=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];"function"===typeof define&&define.amd?define(function(){return C}):"undefined"!==typeof exports?("undefined"!==typeof module&&module.exports&&(module.exports=C),exports=C):Y.jsSHA=C})(this);
19919
19920},{}],111:[function(require,module,exports){
19921'use strict'
19922module.exports = require('./lib/api')(require('./lib/keccak'))
19923
19924},{"./lib/api":112,"./lib/keccak":116}],112:[function(require,module,exports){
19925'use strict'
19926var createKeccak = require('./keccak')
19927var createShake = require('./shake')
19928
19929module.exports = function (KeccakState) {
19930 var Keccak = createKeccak(KeccakState)
19931 var Shake = createShake(KeccakState)
19932
19933 return function (algorithm, options) {
19934 var hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm
19935 switch (hash) {
19936 case 'keccak224': return new Keccak(1152, 448, null, 224, options)
19937 case 'keccak256': return new Keccak(1088, 512, null, 256, options)
19938 case 'keccak384': return new Keccak(832, 768, null, 384, options)
19939 case 'keccak512': return new Keccak(576, 1024, null, 512, options)
19940
19941 case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options)
19942 case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options)
19943 case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options)
19944 case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options)
19945
19946 case 'shake128': return new Shake(1344, 256, 0x1f, options)
19947 case 'shake256': return new Shake(1088, 512, 0x1f, options)
19948
19949 default: throw new Error('Invald algorithm: ' + algorithm)
19950 }
19951 }
19952}
19953
19954},{"./keccak":113,"./shake":114}],113:[function(require,module,exports){
19955'use strict'
19956var Buffer = require('safe-buffer').Buffer
19957var Transform = require('stream').Transform
19958var inherits = require('inherits')
19959
19960module.exports = function (KeccakState) {
19961 function Keccak (rate, capacity, delimitedSuffix, hashBitLength, options) {
19962 Transform.call(this, options)
19963
19964 this._rate = rate
19965 this._capacity = capacity
19966 this._delimitedSuffix = delimitedSuffix
19967 this._hashBitLength = hashBitLength
19968 this._options = options
19969
19970 this._state = new KeccakState()
19971 this._state.initialize(rate, capacity)
19972 this._finalized = false
19973 }
19974
19975 inherits(Keccak, Transform)
19976
19977 Keccak.prototype._transform = function (chunk, encoding, callback) {
19978 var error = null
19979 try {
19980 this.update(chunk, encoding)
19981 } catch (err) {
19982 error = err
19983 }
19984
19985 callback(error)
19986 }
19987
19988 Keccak.prototype._flush = function (callback) {
19989 var error = null
19990 try {
19991 this.push(this.digest())
19992 } catch (err) {
19993 error = err
19994 }
19995
19996 callback(error)
19997 }
19998
19999 Keccak.prototype.update = function (data, encoding) {
20000 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
20001 if (this._finalized) throw new Error('Digest already called')
20002 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
20003
20004 this._state.absorb(data)
20005
20006 return this
20007 }
20008
20009 Keccak.prototype.digest = function (encoding) {
20010 if (this._finalized) throw new Error('Digest already called')
20011 this._finalized = true
20012
20013 if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix)
20014 var digest = this._state.squeeze(this._hashBitLength / 8)
20015 if (encoding !== undefined) digest = digest.toString(encoding)
20016
20017 this._resetState()
20018
20019 return digest
20020 }
20021
20022 // remove result from memory
20023 Keccak.prototype._resetState = function () {
20024 this._state.initialize(this._rate, this._capacity)
20025 return this
20026 }
20027
20028 // because sometimes we need hash right now and little later
20029 Keccak.prototype._clone = function () {
20030 var clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options)
20031 this._state.copy(clone._state)
20032 clone._finalized = this._finalized
20033
20034 return clone
20035 }
20036
20037 return Keccak
20038}
20039
20040},{"inherits":107,"safe-buffer":156,"stream":172}],114:[function(require,module,exports){
20041'use strict'
20042var Buffer = require('safe-buffer').Buffer
20043var Transform = require('stream').Transform
20044var inherits = require('inherits')
20045
20046module.exports = function (KeccakState) {
20047 function Shake (rate, capacity, delimitedSuffix, options) {
20048 Transform.call(this, options)
20049
20050 this._rate = rate
20051 this._capacity = capacity
20052 this._delimitedSuffix = delimitedSuffix
20053 this._options = options
20054
20055 this._state = new KeccakState()
20056 this._state.initialize(rate, capacity)
20057 this._finalized = false
20058 }
20059
20060 inherits(Shake, Transform)
20061
20062 Shake.prototype._transform = function (chunk, encoding, callback) {
20063 var error = null
20064 try {
20065 this.update(chunk, encoding)
20066 } catch (err) {
20067 error = err
20068 }
20069
20070 callback(error)
20071 }
20072
20073 Shake.prototype._flush = function () {}
20074
20075 Shake.prototype._read = function (size) {
20076 this.push(this.squeeze(size))
20077 }
20078
20079 Shake.prototype.update = function (data, encoding) {
20080 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
20081 if (this._finalized) throw new Error('Squeeze already called')
20082 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
20083
20084 this._state.absorb(data)
20085
20086 return this
20087 }
20088
20089 Shake.prototype.squeeze = function (dataByteLength, encoding) {
20090 if (!this._finalized) {
20091 this._finalized = true
20092 this._state.absorbLastFewBits(this._delimitedSuffix)
20093 }
20094
20095 var data = this._state.squeeze(dataByteLength)
20096 if (encoding !== undefined) data = data.toString(encoding)
20097
20098 return data
20099 }
20100
20101 Shake.prototype._resetState = function () {
20102 this._state.initialize(this._rate, this._capacity)
20103 return this
20104 }
20105
20106 Shake.prototype._clone = function () {
20107 var clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options)
20108 this._state.copy(clone._state)
20109 clone._finalized = this._finalized
20110
20111 return clone
20112 }
20113
20114 return Shake
20115}
20116
20117},{"inherits":107,"safe-buffer":156,"stream":172}],115:[function(require,module,exports){
20118'use strict'
20119var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]
20120
20121exports.p1600 = function (s) {
20122 for (var round = 0; round < 24; ++round) {
20123 // theta
20124 var lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]
20125 var hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]
20126 var lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]
20127 var hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]
20128 var lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]
20129 var hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]
20130 var lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]
20131 var hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]
20132 var lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]
20133 var hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]
20134
20135 var lo = lo4 ^ (lo1 << 1 | hi1 >>> 31)
20136 var hi = hi4 ^ (hi1 << 1 | lo1 >>> 31)
20137 var t1slo0 = s[0] ^ lo
20138 var t1shi0 = s[1] ^ hi
20139 var t1slo5 = s[10] ^ lo
20140 var t1shi5 = s[11] ^ hi
20141 var t1slo10 = s[20] ^ lo
20142 var t1shi10 = s[21] ^ hi
20143 var t1slo15 = s[30] ^ lo
20144 var t1shi15 = s[31] ^ hi
20145 var t1slo20 = s[40] ^ lo
20146 var t1shi20 = s[41] ^ hi
20147 lo = lo0 ^ (lo2 << 1 | hi2 >>> 31)
20148 hi = hi0 ^ (hi2 << 1 | lo2 >>> 31)
20149 var t1slo1 = s[2] ^ lo
20150 var t1shi1 = s[3] ^ hi
20151 var t1slo6 = s[12] ^ lo
20152 var t1shi6 = s[13] ^ hi
20153 var t1slo11 = s[22] ^ lo
20154 var t1shi11 = s[23] ^ hi
20155 var t1slo16 = s[32] ^ lo
20156 var t1shi16 = s[33] ^ hi
20157 var t1slo21 = s[42] ^ lo
20158 var t1shi21 = s[43] ^ hi
20159 lo = lo1 ^ (lo3 << 1 | hi3 >>> 31)
20160 hi = hi1 ^ (hi3 << 1 | lo3 >>> 31)
20161 var t1slo2 = s[4] ^ lo
20162 var t1shi2 = s[5] ^ hi
20163 var t1slo7 = s[14] ^ lo
20164 var t1shi7 = s[15] ^ hi
20165 var t1slo12 = s[24] ^ lo
20166 var t1shi12 = s[25] ^ hi
20167 var t1slo17 = s[34] ^ lo
20168 var t1shi17 = s[35] ^ hi
20169 var t1slo22 = s[44] ^ lo
20170 var t1shi22 = s[45] ^ hi
20171 lo = lo2 ^ (lo4 << 1 | hi4 >>> 31)
20172 hi = hi2 ^ (hi4 << 1 | lo4 >>> 31)
20173 var t1slo3 = s[6] ^ lo
20174 var t1shi3 = s[7] ^ hi
20175 var t1slo8 = s[16] ^ lo
20176 var t1shi8 = s[17] ^ hi
20177 var t1slo13 = s[26] ^ lo
20178 var t1shi13 = s[27] ^ hi
20179 var t1slo18 = s[36] ^ lo
20180 var t1shi18 = s[37] ^ hi
20181 var t1slo23 = s[46] ^ lo
20182 var t1shi23 = s[47] ^ hi
20183 lo = lo3 ^ (lo0 << 1 | hi0 >>> 31)
20184 hi = hi3 ^ (hi0 << 1 | lo0 >>> 31)
20185 var t1slo4 = s[8] ^ lo
20186 var t1shi4 = s[9] ^ hi
20187 var t1slo9 = s[18] ^ lo
20188 var t1shi9 = s[19] ^ hi
20189 var t1slo14 = s[28] ^ lo
20190 var t1shi14 = s[29] ^ hi
20191 var t1slo19 = s[38] ^ lo
20192 var t1shi19 = s[39] ^ hi
20193 var t1slo24 = s[48] ^ lo
20194 var t1shi24 = s[49] ^ hi
20195
20196 // rho & pi
20197 var t2slo0 = t1slo0
20198 var t2shi0 = t1shi0
20199 var t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28)
20200 var t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28)
20201 var t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29)
20202 var t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29)
20203 var t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23)
20204 var t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23)
20205 var t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14)
20206 var t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14)
20207 var t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31)
20208 var t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31)
20209 var t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20)
20210 var t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20)
20211 var t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22)
20212 var t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22)
20213 var t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19)
20214 var t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19)
20215 var t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30)
20216 var t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30)
20217 var t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2)
20218 var t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2)
20219 var t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26)
20220 var t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26)
20221 var t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21)
20222 var t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21)
20223 var t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17)
20224 var t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17)
20225 var t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3)
20226 var t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3)
20227 var t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4)
20228 var t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4)
20229 var t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9)
20230 var t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9)
20231 var t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7)
20232 var t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7)
20233 var t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11)
20234 var t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11)
20235 var t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8)
20236 var t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8)
20237 var t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5)
20238 var t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5)
20239 var t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12)
20240 var t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12)
20241 var t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25)
20242 var t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25)
20243 var t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24)
20244 var t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24)
20245 var t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18)
20246 var t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18)
20247
20248 // chi
20249 s[0] = t2slo0 ^ (~t2slo1 & t2slo2)
20250 s[1] = t2shi0 ^ (~t2shi1 & t2shi2)
20251 s[10] = t2slo5 ^ (~t2slo6 & t2slo7)
20252 s[11] = t2shi5 ^ (~t2shi6 & t2shi7)
20253 s[20] = t2slo10 ^ (~t2slo11 & t2slo12)
20254 s[21] = t2shi10 ^ (~t2shi11 & t2shi12)
20255 s[30] = t2slo15 ^ (~t2slo16 & t2slo17)
20256 s[31] = t2shi15 ^ (~t2shi16 & t2shi17)
20257 s[40] = t2slo20 ^ (~t2slo21 & t2slo22)
20258 s[41] = t2shi20 ^ (~t2shi21 & t2shi22)
20259 s[2] = t2slo1 ^ (~t2slo2 & t2slo3)
20260 s[3] = t2shi1 ^ (~t2shi2 & t2shi3)
20261 s[12] = t2slo6 ^ (~t2slo7 & t2slo8)
20262 s[13] = t2shi6 ^ (~t2shi7 & t2shi8)
20263 s[22] = t2slo11 ^ (~t2slo12 & t2slo13)
20264 s[23] = t2shi11 ^ (~t2shi12 & t2shi13)
20265 s[32] = t2slo16 ^ (~t2slo17 & t2slo18)
20266 s[33] = t2shi16 ^ (~t2shi17 & t2shi18)
20267 s[42] = t2slo21 ^ (~t2slo22 & t2slo23)
20268 s[43] = t2shi21 ^ (~t2shi22 & t2shi23)
20269 s[4] = t2slo2 ^ (~t2slo3 & t2slo4)
20270 s[5] = t2shi2 ^ (~t2shi3 & t2shi4)
20271 s[14] = t2slo7 ^ (~t2slo8 & t2slo9)
20272 s[15] = t2shi7 ^ (~t2shi8 & t2shi9)
20273 s[24] = t2slo12 ^ (~t2slo13 & t2slo14)
20274 s[25] = t2shi12 ^ (~t2shi13 & t2shi14)
20275 s[34] = t2slo17 ^ (~t2slo18 & t2slo19)
20276 s[35] = t2shi17 ^ (~t2shi18 & t2shi19)
20277 s[44] = t2slo22 ^ (~t2slo23 & t2slo24)
20278 s[45] = t2shi22 ^ (~t2shi23 & t2shi24)
20279 s[6] = t2slo3 ^ (~t2slo4 & t2slo0)
20280 s[7] = t2shi3 ^ (~t2shi4 & t2shi0)
20281 s[16] = t2slo8 ^ (~t2slo9 & t2slo5)
20282 s[17] = t2shi8 ^ (~t2shi9 & t2shi5)
20283 s[26] = t2slo13 ^ (~t2slo14 & t2slo10)
20284 s[27] = t2shi13 ^ (~t2shi14 & t2shi10)
20285 s[36] = t2slo18 ^ (~t2slo19 & t2slo15)
20286 s[37] = t2shi18 ^ (~t2shi19 & t2shi15)
20287 s[46] = t2slo23 ^ (~t2slo24 & t2slo20)
20288 s[47] = t2shi23 ^ (~t2shi24 & t2shi20)
20289 s[8] = t2slo4 ^ (~t2slo0 & t2slo1)
20290 s[9] = t2shi4 ^ (~t2shi0 & t2shi1)
20291 s[18] = t2slo9 ^ (~t2slo5 & t2slo6)
20292 s[19] = t2shi9 ^ (~t2shi5 & t2shi6)
20293 s[28] = t2slo14 ^ (~t2slo10 & t2slo11)
20294 s[29] = t2shi14 ^ (~t2shi10 & t2shi11)
20295 s[38] = t2slo19 ^ (~t2slo15 & t2slo16)
20296 s[39] = t2shi19 ^ (~t2shi15 & t2shi16)
20297 s[48] = t2slo24 ^ (~t2slo20 & t2slo21)
20298 s[49] = t2shi24 ^ (~t2shi20 & t2shi21)
20299
20300 // iota
20301 s[0] ^= P1600_ROUND_CONSTANTS[round * 2]
20302 s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]
20303 }
20304}
20305
20306},{}],116:[function(require,module,exports){
20307'use strict'
20308var Buffer = require('safe-buffer').Buffer
20309var keccakState = require('./keccak-state-unroll')
20310
20311function Keccak () {
20312 // much faster than `new Array(50)`
20313 this.state = [
20314 0, 0, 0, 0, 0,
20315 0, 0, 0, 0, 0,
20316 0, 0, 0, 0, 0,
20317 0, 0, 0, 0, 0,
20318 0, 0, 0, 0, 0
20319 ]
20320
20321 this.blockSize = null
20322 this.count = 0
20323 this.squeezing = false
20324}
20325
20326Keccak.prototype.initialize = function (rate, capacity) {
20327 for (var i = 0; i < 50; ++i) this.state[i] = 0
20328 this.blockSize = rate / 8
20329 this.count = 0
20330 this.squeezing = false
20331}
20332
20333Keccak.prototype.absorb = function (data) {
20334 for (var i = 0; i < data.length; ++i) {
20335 this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4))
20336 this.count += 1
20337 if (this.count === this.blockSize) {
20338 keccakState.p1600(this.state)
20339 this.count = 0
20340 }
20341 }
20342}
20343
20344Keccak.prototype.absorbLastFewBits = function (bits) {
20345 this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4))
20346 if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state)
20347 this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4))
20348 keccakState.p1600(this.state)
20349 this.count = 0
20350 this.squeezing = true
20351}
20352
20353Keccak.prototype.squeeze = function (length) {
20354 if (!this.squeezing) this.absorbLastFewBits(0x01)
20355
20356 var output = Buffer.alloc(length)
20357 for (var i = 0; i < length; ++i) {
20358 output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff
20359 this.count += 1
20360 if (this.count === this.blockSize) {
20361 keccakState.p1600(this.state)
20362 this.count = 0
20363 }
20364 }
20365
20366 return output
20367}
20368
20369Keccak.prototype.copy = function (dest) {
20370 for (var i = 0; i < 50; ++i) dest.state[i] = this.state[i]
20371 dest.blockSize = this.blockSize
20372 dest.count = this.count
20373 dest.squeezing = this.squeezing
20374}
20375
20376module.exports = Keccak
20377
20378},{"./keccak-state-unroll":115,"safe-buffer":156}],117:[function(require,module,exports){
20379(function (Buffer){
20380'use strict'
20381var inherits = require('inherits')
20382var HashBase = require('hash-base')
20383
20384var ARRAY16 = new Array(16)
20385
20386function MD5 () {
20387 HashBase.call(this, 64)
20388
20389 // state
20390 this._a = 0x67452301
20391 this._b = 0xefcdab89
20392 this._c = 0x98badcfe
20393 this._d = 0x10325476
20394}
20395
20396inherits(MD5, HashBase)
20397
20398MD5.prototype._update = function () {
20399 var M = ARRAY16
20400 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
20401
20402 var a = this._a
20403 var b = this._b
20404 var c = this._c
20405 var d = this._d
20406
20407 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
20408 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
20409 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
20410 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
20411 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
20412 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
20413 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
20414 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
20415 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
20416 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
20417 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
20418 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
20419 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
20420 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
20421 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
20422 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
20423
20424 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
20425 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
20426 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
20427 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
20428 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
20429 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
20430 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
20431 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
20432 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
20433 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
20434 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
20435 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
20436 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
20437 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
20438 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
20439 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
20440
20441 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
20442 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
20443 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
20444 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
20445 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
20446 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
20447 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
20448 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
20449 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
20450 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
20451 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
20452 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
20453 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
20454 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
20455 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
20456 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
20457
20458 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
20459 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
20460 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
20461 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
20462 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
20463 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
20464 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
20465 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
20466 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
20467 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
20468 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
20469 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
20470 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
20471 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
20472 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
20473 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
20474
20475 this._a = (this._a + a) | 0
20476 this._b = (this._b + b) | 0
20477 this._c = (this._c + c) | 0
20478 this._d = (this._d + d) | 0
20479}
20480
20481MD5.prototype._digest = function () {
20482 // create padding and handle blocks
20483 this._block[this._blockOffset++] = 0x80
20484 if (this._blockOffset > 56) {
20485 this._block.fill(0, this._blockOffset, 64)
20486 this._update()
20487 this._blockOffset = 0
20488 }
20489
20490 this._block.fill(0, this._blockOffset, 56)
20491 this._block.writeUInt32LE(this._length[0], 56)
20492 this._block.writeUInt32LE(this._length[1], 60)
20493 this._update()
20494
20495 // produce result
20496 var buffer = new Buffer(16)
20497 buffer.writeInt32LE(this._a, 0)
20498 buffer.writeInt32LE(this._b, 4)
20499 buffer.writeInt32LE(this._c, 8)
20500 buffer.writeInt32LE(this._d, 12)
20501 return buffer
20502}
20503
20504function rotl (x, n) {
20505 return (x << n) | (x >>> (32 - n))
20506}
20507
20508function fnF (a, b, c, d, m, k, s) {
20509 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
20510}
20511
20512function fnG (a, b, c, d, m, k, s) {
20513 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
20514}
20515
20516function fnH (a, b, c, d, m, k, s) {
20517 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
20518}
20519
20520function fnI (a, b, c, d, m, k, s) {
20521 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
20522}
20523
20524module.exports = MD5
20525
20526}).call(this,require("buffer").Buffer)
20527},{"buffer":53,"hash-base":118,"inherits":107}],118:[function(require,module,exports){
20528'use strict'
20529var Buffer = require('safe-buffer').Buffer
20530var Transform = require('stream').Transform
20531var inherits = require('inherits')
20532
20533function throwIfNotStringOrBuffer (val, prefix) {
20534 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
20535 throw new TypeError(prefix + ' must be a string or a buffer')
20536 }
20537}
20538
20539function HashBase (blockSize) {
20540 Transform.call(this)
20541
20542 this._block = Buffer.allocUnsafe(blockSize)
20543 this._blockSize = blockSize
20544 this._blockOffset = 0
20545 this._length = [0, 0, 0, 0]
20546
20547 this._finalized = false
20548}
20549
20550inherits(HashBase, Transform)
20551
20552HashBase.prototype._transform = function (chunk, encoding, callback) {
20553 var error = null
20554 try {
20555 this.update(chunk, encoding)
20556 } catch (err) {
20557 error = err
20558 }
20559
20560 callback(error)
20561}
20562
20563HashBase.prototype._flush = function (callback) {
20564 var error = null
20565 try {
20566 this.push(this.digest())
20567 } catch (err) {
20568 error = err
20569 }
20570
20571 callback(error)
20572}
20573
20574HashBase.prototype.update = function (data, encoding) {
20575 throwIfNotStringOrBuffer(data, 'Data')
20576 if (this._finalized) throw new Error('Digest already called')
20577 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
20578
20579 // consume data
20580 var block = this._block
20581 var offset = 0
20582 while (this._blockOffset + data.length - offset >= this._blockSize) {
20583 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
20584 this._update()
20585 this._blockOffset = 0
20586 }
20587 while (offset < data.length) block[this._blockOffset++] = data[offset++]
20588
20589 // update length
20590 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
20591 this._length[j] += carry
20592 carry = (this._length[j] / 0x0100000000) | 0
20593 if (carry > 0) this._length[j] -= 0x0100000000 * carry
20594 }
20595
20596 return this
20597}
20598
20599HashBase.prototype._update = function () {
20600 throw new Error('_update is not implemented')
20601}
20602
20603HashBase.prototype.digest = function (encoding) {
20604 if (this._finalized) throw new Error('Digest already called')
20605 this._finalized = true
20606
20607 var digest = this._digest()
20608 if (encoding !== undefined) digest = digest.toString(encoding)
20609
20610 // reset state
20611 this._block.fill(0)
20612 this._blockOffset = 0
20613 for (var i = 0; i < 4; ++i) this._length[i] = 0
20614
20615 return digest
20616}
20617
20618HashBase.prototype._digest = function () {
20619 throw new Error('_digest is not implemented')
20620}
20621
20622module.exports = HashBase
20623
20624},{"inherits":107,"safe-buffer":156,"stream":172}],119:[function(require,module,exports){
20625var bn = require('bn.js');
20626var brorand = require('brorand');
20627
20628function MillerRabin(rand) {
20629 this.rand = rand || new brorand.Rand();
20630}
20631module.exports = MillerRabin;
20632
20633MillerRabin.create = function create(rand) {
20634 return new MillerRabin(rand);
20635};
20636
20637MillerRabin.prototype._randbelow = function _randbelow(n) {
20638 var len = n.bitLength();
20639 var min_bytes = Math.ceil(len / 8);
20640
20641 // Generage random bytes until a number less than n is found.
20642 // This ensures that 0..n-1 have an equal probability of being selected.
20643 do
20644 var a = new bn(this.rand.generate(min_bytes));
20645 while (a.cmp(n) >= 0);
20646
20647 return a;
20648};
20649
20650MillerRabin.prototype._randrange = function _randrange(start, stop) {
20651 // Generate a random number greater than or equal to start and less than stop.
20652 var size = stop.sub(start);
20653 return start.add(this._randbelow(size));
20654};
20655
20656MillerRabin.prototype.test = function test(n, k, cb) {
20657 var len = n.bitLength();
20658 var red = bn.mont(n);
20659 var rone = new bn(1).toRed(red);
20660
20661 if (!k)
20662 k = Math.max(1, (len / 48) | 0);
20663
20664 // Find d and s, (n - 1) = (2 ^ s) * d;
20665 var n1 = n.subn(1);
20666 for (var s = 0; !n1.testn(s); s++) {}
20667 var d = n.shrn(s);
20668
20669 var rn1 = n1.toRed(red);
20670
20671 var prime = true;
20672 for (; k > 0; k--) {
20673 var a = this._randrange(new bn(2), n1);
20674 if (cb)
20675 cb(a);
20676
20677 var x = a.toRed(red).redPow(d);
20678 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
20679 continue;
20680
20681 for (var i = 1; i < s; i++) {
20682 x = x.redSqr();
20683
20684 if (x.cmp(rone) === 0)
20685 return false;
20686 if (x.cmp(rn1) === 0)
20687 break;
20688 }
20689
20690 if (i === s)
20691 return false;
20692 }
20693
20694 return prime;
20695};
20696
20697MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
20698 var len = n.bitLength();
20699 var red = bn.mont(n);
20700 var rone = new bn(1).toRed(red);
20701
20702 if (!k)
20703 k = Math.max(1, (len / 48) | 0);
20704
20705 // Find d and s, (n - 1) = (2 ^ s) * d;
20706 var n1 = n.subn(1);
20707 for (var s = 0; !n1.testn(s); s++) {}
20708 var d = n.shrn(s);
20709
20710 var rn1 = n1.toRed(red);
20711
20712 for (; k > 0; k--) {
20713 var a = this._randrange(new bn(2), n1);
20714
20715 var g = n.gcd(a);
20716 if (g.cmpn(1) !== 0)
20717 return g;
20718
20719 var x = a.toRed(red).redPow(d);
20720 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
20721 continue;
20722
20723 for (var i = 1; i < s; i++) {
20724 x = x.redSqr();
20725
20726 if (x.cmp(rone) === 0)
20727 return x.fromRed().subn(1).gcd(n);
20728 if (x.cmp(rn1) === 0)
20729 break;
20730 }
20731
20732 if (i === s) {
20733 x = x.redSqr();
20734 return x.fromRed().subn(1).gcd(n);
20735 }
20736 }
20737
20738 return false;
20739};
20740
20741},{"bn.js":21,"brorand":22}],120:[function(require,module,exports){
20742module.exports = assert;
20743
20744function assert(val, msg) {
20745 if (!val)
20746 throw new Error(msg || 'Assertion failed');
20747}
20748
20749assert.equal = function assertEqual(l, r, msg) {
20750 if (l != r)
20751 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
20752};
20753
20754},{}],121:[function(require,module,exports){
20755'use strict';
20756
20757var utils = exports;
20758
20759function toArray(msg, enc) {
20760 if (Array.isArray(msg))
20761 return msg.slice();
20762 if (!msg)
20763 return [];
20764 var res = [];
20765 if (typeof msg !== 'string') {
20766 for (var i = 0; i < msg.length; i++)
20767 res[i] = msg[i] | 0;
20768 return res;
20769 }
20770 if (enc === 'hex') {
20771 msg = msg.replace(/[^a-z0-9]+/ig, '');
20772 if (msg.length % 2 !== 0)
20773 msg = '0' + msg;
20774 for (var i = 0; i < msg.length; i += 2)
20775 res.push(parseInt(msg[i] + msg[i + 1], 16));
20776 } else {
20777 for (var i = 0; i < msg.length; i++) {
20778 var c = msg.charCodeAt(i);
20779 var hi = c >> 8;
20780 var lo = c & 0xff;
20781 if (hi)
20782 res.push(hi, lo);
20783 else
20784 res.push(lo);
20785 }
20786 }
20787 return res;
20788}
20789utils.toArray = toArray;
20790
20791function zero2(word) {
20792 if (word.length === 1)
20793 return '0' + word;
20794 else
20795 return word;
20796}
20797utils.zero2 = zero2;
20798
20799function toHex(msg) {
20800 var res = '';
20801 for (var i = 0; i < msg.length; i++)
20802 res += zero2(msg[i].toString(16));
20803 return res;
20804}
20805utils.toHex = toHex;
20806
20807utils.encode = function encode(arr, enc) {
20808 if (enc === 'hex')
20809 return toHex(arr);
20810 else
20811 return arr;
20812};
20813
20814},{}],122:[function(require,module,exports){
20815module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
20816"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
20817"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
20818"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
20819"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
20820"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
20821"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
20822"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
20823"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
20824"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
20825"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
20826"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
20827}
20828},{}],123:[function(require,module,exports){
20829// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
20830// Fedor, you are amazing.
20831'use strict'
20832
20833var asn1 = require('asn1.js')
20834
20835exports.certificate = require('./certificate')
20836
20837var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
20838 this.seq().obj(
20839 this.key('version').int(),
20840 this.key('modulus').int(),
20841 this.key('publicExponent').int(),
20842 this.key('privateExponent').int(),
20843 this.key('prime1').int(),
20844 this.key('prime2').int(),
20845 this.key('exponent1').int(),
20846 this.key('exponent2').int(),
20847 this.key('coefficient').int()
20848 )
20849})
20850exports.RSAPrivateKey = RSAPrivateKey
20851
20852var RSAPublicKey = asn1.define('RSAPublicKey', function () {
20853 this.seq().obj(
20854 this.key('modulus').int(),
20855 this.key('publicExponent').int()
20856 )
20857})
20858exports.RSAPublicKey = RSAPublicKey
20859
20860var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
20861 this.seq().obj(
20862 this.key('algorithm').use(AlgorithmIdentifier),
20863 this.key('subjectPublicKey').bitstr()
20864 )
20865})
20866exports.PublicKey = PublicKey
20867
20868var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
20869 this.seq().obj(
20870 this.key('algorithm').objid(),
20871 this.key('none').null_().optional(),
20872 this.key('curve').objid().optional(),
20873 this.key('params').seq().obj(
20874 this.key('p').int(),
20875 this.key('q').int(),
20876 this.key('g').int()
20877 ).optional()
20878 )
20879})
20880
20881var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
20882 this.seq().obj(
20883 this.key('version').int(),
20884 this.key('algorithm').use(AlgorithmIdentifier),
20885 this.key('subjectPrivateKey').octstr()
20886 )
20887})
20888exports.PrivateKey = PrivateKeyInfo
20889var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
20890 this.seq().obj(
20891 this.key('algorithm').seq().obj(
20892 this.key('id').objid(),
20893 this.key('decrypt').seq().obj(
20894 this.key('kde').seq().obj(
20895 this.key('id').objid(),
20896 this.key('kdeparams').seq().obj(
20897 this.key('salt').octstr(),
20898 this.key('iters').int()
20899 )
20900 ),
20901 this.key('cipher').seq().obj(
20902 this.key('algo').objid(),
20903 this.key('iv').octstr()
20904 )
20905 )
20906 ),
20907 this.key('subjectPrivateKey').octstr()
20908 )
20909})
20910
20911exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
20912
20913var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
20914 this.seq().obj(
20915 this.key('version').int(),
20916 this.key('p').int(),
20917 this.key('q').int(),
20918 this.key('g').int(),
20919 this.key('pub_key').int(),
20920 this.key('priv_key').int()
20921 )
20922})
20923exports.DSAPrivateKey = DSAPrivateKey
20924
20925exports.DSAparam = asn1.define('DSAparam', function () {
20926 this.int()
20927})
20928
20929var ECPrivateKey = asn1.define('ECPrivateKey', function () {
20930 this.seq().obj(
20931 this.key('version').int(),
20932 this.key('privateKey').octstr(),
20933 this.key('parameters').optional().explicit(0).use(ECParameters),
20934 this.key('publicKey').optional().explicit(1).bitstr()
20935 )
20936})
20937exports.ECPrivateKey = ECPrivateKey
20938
20939var ECParameters = asn1.define('ECParameters', function () {
20940 this.choice({
20941 namedCurve: this.objid()
20942 })
20943})
20944
20945exports.signature = asn1.define('signature', function () {
20946 this.seq().obj(
20947 this.key('r').int(),
20948 this.key('s').int()
20949 )
20950})
20951
20952},{"./certificate":124,"asn1.js":3}],124:[function(require,module,exports){
20953// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
20954// thanks to @Rantanen
20955
20956'use strict'
20957
20958var asn = require('asn1.js')
20959
20960var Time = asn.define('Time', function () {
20961 this.choice({
20962 utcTime: this.utctime(),
20963 generalTime: this.gentime()
20964 })
20965})
20966
20967var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
20968 this.seq().obj(
20969 this.key('type').objid(),
20970 this.key('value').any()
20971 )
20972})
20973
20974var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
20975 this.seq().obj(
20976 this.key('algorithm').objid(),
20977 this.key('parameters').optional()
20978 )
20979})
20980
20981var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
20982 this.seq().obj(
20983 this.key('algorithm').use(AlgorithmIdentifier),
20984 this.key('subjectPublicKey').bitstr()
20985 )
20986})
20987
20988var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
20989 this.setof(AttributeTypeValue)
20990})
20991
20992var RDNSequence = asn.define('RDNSequence', function () {
20993 this.seqof(RelativeDistinguishedName)
20994})
20995
20996var Name = asn.define('Name', function () {
20997 this.choice({
20998 rdnSequence: this.use(RDNSequence)
20999 })
21000})
21001
21002var Validity = asn.define('Validity', function () {
21003 this.seq().obj(
21004 this.key('notBefore').use(Time),
21005 this.key('notAfter').use(Time)
21006 )
21007})
21008
21009var Extension = asn.define('Extension', function () {
21010 this.seq().obj(
21011 this.key('extnID').objid(),
21012 this.key('critical').bool().def(false),
21013 this.key('extnValue').octstr()
21014 )
21015})
21016
21017var TBSCertificate = asn.define('TBSCertificate', function () {
21018 this.seq().obj(
21019 this.key('version').explicit(0).int(),
21020 this.key('serialNumber').int(),
21021 this.key('signature').use(AlgorithmIdentifier),
21022 this.key('issuer').use(Name),
21023 this.key('validity').use(Validity),
21024 this.key('subject').use(Name),
21025 this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
21026 this.key('issuerUniqueID').implicit(1).bitstr().optional(),
21027 this.key('subjectUniqueID').implicit(2).bitstr().optional(),
21028 this.key('extensions').explicit(3).seqof(Extension).optional()
21029 )
21030})
21031
21032var X509Certificate = asn.define('X509Certificate', function () {
21033 this.seq().obj(
21034 this.key('tbsCertificate').use(TBSCertificate),
21035 this.key('signatureAlgorithm').use(AlgorithmIdentifier),
21036 this.key('signatureValue').bitstr()
21037 )
21038})
21039
21040module.exports = X509Certificate
21041
21042},{"asn1.js":3}],125:[function(require,module,exports){
21043(function (Buffer){
21044// adapted from https://github.com/apatil/pemstrip
21045var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m
21046var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m
21047var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m
21048var evp = require('evp_bytestokey')
21049var ciphers = require('browserify-aes')
21050module.exports = function (okey, password) {
21051 var key = okey.toString()
21052 var match = key.match(findProc)
21053 var decrypted
21054 if (!match) {
21055 var match2 = key.match(fullRegex)
21056 decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64')
21057 } else {
21058 var suite = 'aes' + match[1]
21059 var iv = new Buffer(match[2], 'hex')
21060 var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64')
21061 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
21062 var out = []
21063 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
21064 out.push(cipher.update(cipherText))
21065 out.push(cipher.final())
21066 decrypted = Buffer.concat(out)
21067 }
21068 var tag = key.match(startRegex)[1]
21069 return {
21070 tag: tag,
21071 data: decrypted
21072 }
21073}
21074
21075}).call(this,require("buffer").Buffer)
21076},{"browserify-aes":26,"buffer":53,"evp_bytestokey":90}],126:[function(require,module,exports){
21077(function (Buffer){
21078var asn1 = require('./asn1')
21079var aesid = require('./aesid.json')
21080var fixProc = require('./fixProc')
21081var ciphers = require('browserify-aes')
21082var compat = require('pbkdf2')
21083module.exports = parseKeys
21084
21085function parseKeys (buffer) {
21086 var password
21087 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
21088 password = buffer.passphrase
21089 buffer = buffer.key
21090 }
21091 if (typeof buffer === 'string') {
21092 buffer = new Buffer(buffer)
21093 }
21094
21095 var stripped = fixProc(buffer, password)
21096
21097 var type = stripped.tag
21098 var data = stripped.data
21099 var subtype, ndata
21100 switch (type) {
21101 case 'CERTIFICATE':
21102 ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
21103 // falls through
21104 case 'PUBLIC KEY':
21105 if (!ndata) {
21106 ndata = asn1.PublicKey.decode(data, 'der')
21107 }
21108 subtype = ndata.algorithm.algorithm.join('.')
21109 switch (subtype) {
21110 case '1.2.840.113549.1.1.1':
21111 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
21112 case '1.2.840.10045.2.1':
21113 ndata.subjectPrivateKey = ndata.subjectPublicKey
21114 return {
21115 type: 'ec',
21116 data: ndata
21117 }
21118 case '1.2.840.10040.4.1':
21119 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
21120 return {
21121 type: 'dsa',
21122 data: ndata.algorithm.params
21123 }
21124 default: throw new Error('unknown key id ' + subtype)
21125 }
21126 throw new Error('unknown key type ' + type)
21127 case 'ENCRYPTED PRIVATE KEY':
21128 data = asn1.EncryptedPrivateKey.decode(data, 'der')
21129 data = decrypt(data, password)
21130 // falls through
21131 case 'PRIVATE KEY':
21132 ndata = asn1.PrivateKey.decode(data, 'der')
21133 subtype = ndata.algorithm.algorithm.join('.')
21134 switch (subtype) {
21135 case '1.2.840.113549.1.1.1':
21136 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
21137 case '1.2.840.10045.2.1':
21138 return {
21139 curve: ndata.algorithm.curve,
21140 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
21141 }
21142 case '1.2.840.10040.4.1':
21143 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
21144 return {
21145 type: 'dsa',
21146 params: ndata.algorithm.params
21147 }
21148 default: throw new Error('unknown key id ' + subtype)
21149 }
21150 throw new Error('unknown key type ' + type)
21151 case 'RSA PUBLIC KEY':
21152 return asn1.RSAPublicKey.decode(data, 'der')
21153 case 'RSA PRIVATE KEY':
21154 return asn1.RSAPrivateKey.decode(data, 'der')
21155 case 'DSA PRIVATE KEY':
21156 return {
21157 type: 'dsa',
21158 params: asn1.DSAPrivateKey.decode(data, 'der')
21159 }
21160 case 'EC PRIVATE KEY':
21161 data = asn1.ECPrivateKey.decode(data, 'der')
21162 return {
21163 curve: data.parameters.value,
21164 privateKey: data.privateKey
21165 }
21166 default: throw new Error('unknown key type ' + type)
21167 }
21168}
21169parseKeys.signature = asn1.signature
21170function decrypt (data, password) {
21171 var salt = data.algorithm.decrypt.kde.kdeparams.salt
21172 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
21173 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
21174 var iv = data.algorithm.decrypt.cipher.iv
21175 var cipherText = data.subjectPrivateKey
21176 var keylen = parseInt(algo.split('-')[1], 10) / 8
21177 var key = compat.pbkdf2Sync(password, salt, iters, keylen)
21178 var cipher = ciphers.createDecipheriv(algo, key, iv)
21179 var out = []
21180 out.push(cipher.update(cipherText))
21181 out.push(cipher.final())
21182 return Buffer.concat(out)
21183}
21184
21185}).call(this,require("buffer").Buffer)
21186},{"./aesid.json":122,"./asn1":123,"./fixProc":125,"browserify-aes":26,"buffer":53,"pbkdf2":127}],127:[function(require,module,exports){
21187
21188exports.pbkdf2 = require('./lib/async')
21189
21190exports.pbkdf2Sync = require('./lib/sync')
21191
21192},{"./lib/async":128,"./lib/sync":131}],128:[function(require,module,exports){
21193(function (process,global){
21194var checkParameters = require('./precondition')
21195var defaultEncoding = require('./default-encoding')
21196var sync = require('./sync')
21197var Buffer = require('safe-buffer').Buffer
21198
21199var ZERO_BUF
21200var subtle = global.crypto && global.crypto.subtle
21201var toBrowser = {
21202 'sha': 'SHA-1',
21203 'sha-1': 'SHA-1',
21204 'sha1': 'SHA-1',
21205 'sha256': 'SHA-256',
21206 'sha-256': 'SHA-256',
21207 'sha384': 'SHA-384',
21208 'sha-384': 'SHA-384',
21209 'sha-512': 'SHA-512',
21210 'sha512': 'SHA-512'
21211}
21212var checks = []
21213function checkNative (algo) {
21214 if (global.process && !global.process.browser) {
21215 return Promise.resolve(false)
21216 }
21217 if (!subtle || !subtle.importKey || !subtle.deriveBits) {
21218 return Promise.resolve(false)
21219 }
21220 if (checks[algo] !== undefined) {
21221 return checks[algo]
21222 }
21223 ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
21224 var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
21225 .then(function () {
21226 return true
21227 }).catch(function () {
21228 return false
21229 })
21230 checks[algo] = prom
21231 return prom
21232}
21233function browserPbkdf2 (password, salt, iterations, length, algo) {
21234 return subtle.importKey(
21235 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits']
21236 ).then(function (key) {
21237 return subtle.deriveBits({
21238 name: 'PBKDF2',
21239 salt: salt,
21240 iterations: iterations,
21241 hash: {
21242 name: algo
21243 }
21244 }, key, length << 3)
21245 }).then(function (res) {
21246 return Buffer.from(res)
21247 })
21248}
21249function resolvePromise (promise, callback) {
21250 promise.then(function (out) {
21251 process.nextTick(function () {
21252 callback(null, out)
21253 })
21254 }, function (e) {
21255 process.nextTick(function () {
21256 callback(e)
21257 })
21258 })
21259}
21260module.exports = function (password, salt, iterations, keylen, digest, callback) {
21261 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
21262 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
21263
21264 checkParameters(iterations, keylen)
21265 if (typeof digest === 'function') {
21266 callback = digest
21267 digest = undefined
21268 }
21269 if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
21270
21271 digest = digest || 'sha1'
21272 var algo = toBrowser[digest.toLowerCase()]
21273 if (!algo || typeof global.Promise !== 'function') {
21274 return process.nextTick(function () {
21275 var out
21276 try {
21277 out = sync(password, salt, iterations, keylen, digest)
21278 } catch (e) {
21279 return callback(e)
21280 }
21281 callback(null, out)
21282 })
21283 }
21284 resolvePromise(checkNative(algo).then(function (resp) {
21285 if (resp) {
21286 return browserPbkdf2(password, salt, iterations, keylen, algo)
21287 } else {
21288 return sync(password, salt, iterations, keylen, digest)
21289 }
21290 }), callback)
21291}
21292
21293}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
21294},{"./default-encoding":129,"./precondition":130,"./sync":131,"_process":133,"safe-buffer":156}],129:[function(require,module,exports){
21295(function (process){
21296var defaultEncoding
21297/* istanbul ignore next */
21298if (process.browser) {
21299 defaultEncoding = 'utf-8'
21300} else {
21301 var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
21302
21303 defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
21304}
21305module.exports = defaultEncoding
21306
21307}).call(this,require('_process'))
21308},{"_process":133}],130:[function(require,module,exports){
21309var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
21310module.exports = function (iterations, keylen) {
21311 if (typeof iterations !== 'number') {
21312 throw new TypeError('Iterations not a number')
21313 }
21314
21315 if (iterations < 0) {
21316 throw new TypeError('Bad iterations')
21317 }
21318
21319 if (typeof keylen !== 'number') {
21320 throw new TypeError('Key length not a number')
21321 }
21322
21323 if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
21324 throw new TypeError('Bad key length')
21325 }
21326}
21327
21328},{}],131:[function(require,module,exports){
21329var md5 = require('create-hash/md5')
21330var rmd160 = require('ripemd160')
21331var sha = require('sha.js')
21332
21333var checkParameters = require('./precondition')
21334var defaultEncoding = require('./default-encoding')
21335var Buffer = require('safe-buffer').Buffer
21336var ZEROS = Buffer.alloc(128)
21337var sizes = {
21338 md5: 16,
21339 sha1: 20,
21340 sha224: 28,
21341 sha256: 32,
21342 sha384: 48,
21343 sha512: 64,
21344 rmd160: 20,
21345 ripemd160: 20
21346}
21347
21348function Hmac (alg, key, saltLen) {
21349 var hash = getDigest(alg)
21350 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
21351
21352 if (key.length > blocksize) {
21353 key = hash(key)
21354 } else if (key.length < blocksize) {
21355 key = Buffer.concat([key, ZEROS], blocksize)
21356 }
21357
21358 var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
21359 var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
21360 for (var i = 0; i < blocksize; i++) {
21361 ipad[i] = key[i] ^ 0x36
21362 opad[i] = key[i] ^ 0x5C
21363 }
21364
21365 var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
21366 ipad.copy(ipad1, 0, 0, blocksize)
21367 this.ipad1 = ipad1
21368 this.ipad2 = ipad
21369 this.opad = opad
21370 this.alg = alg
21371 this.blocksize = blocksize
21372 this.hash = hash
21373 this.size = sizes[alg]
21374}
21375
21376Hmac.prototype.run = function (data, ipad) {
21377 data.copy(ipad, this.blocksize)
21378 var h = this.hash(ipad)
21379 h.copy(this.opad, this.blocksize)
21380 return this.hash(this.opad)
21381}
21382
21383function getDigest (alg) {
21384 function shaFunc (data) {
21385 return sha(alg).update(data).digest()
21386 }
21387
21388 if (alg === 'rmd160' || alg === 'ripemd160') return rmd160
21389 if (alg === 'md5') return md5
21390 return shaFunc
21391}
21392
21393function pbkdf2 (password, salt, iterations, keylen, digest) {
21394 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
21395 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
21396
21397 checkParameters(iterations, keylen)
21398
21399 digest = digest || 'sha1'
21400
21401 var hmac = new Hmac(digest, password, salt.length)
21402
21403 var DK = Buffer.allocUnsafe(keylen)
21404 var block1 = Buffer.allocUnsafe(salt.length + 4)
21405 salt.copy(block1, 0, 0, salt.length)
21406
21407 var destPos = 0
21408 var hLen = sizes[digest]
21409 var l = Math.ceil(keylen / hLen)
21410
21411 for (var i = 1; i <= l; i++) {
21412 block1.writeUInt32BE(i, salt.length)
21413
21414 var T = hmac.run(block1, hmac.ipad1)
21415 var U = T
21416
21417 for (var j = 1; j < iterations; j++) {
21418 U = hmac.run(U, hmac.ipad2)
21419 for (var k = 0; k < hLen; k++) T[k] ^= U[k]
21420 }
21421
21422 T.copy(DK, destPos)
21423 destPos += hLen
21424 }
21425
21426 return DK
21427}
21428
21429module.exports = pbkdf2
21430
21431},{"./default-encoding":129,"./precondition":130,"create-hash/md5":59,"ripemd160":155,"safe-buffer":156,"sha.js":165}],132:[function(require,module,exports){
21432(function (process){
21433'use strict';
21434
21435if (!process.version ||
21436 process.version.indexOf('v0.') === 0 ||
21437 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
21438 module.exports = nextTick;
21439} else {
21440 module.exports = process.nextTick;
21441}
21442
21443function nextTick(fn, arg1, arg2, arg3) {
21444 if (typeof fn !== 'function') {
21445 throw new TypeError('"callback" argument must be a function');
21446 }
21447 var len = arguments.length;
21448 var args, i;
21449 switch (len) {
21450 case 0:
21451 case 1:
21452 return process.nextTick(fn);
21453 case 2:
21454 return process.nextTick(function afterTickOne() {
21455 fn.call(null, arg1);
21456 });
21457 case 3:
21458 return process.nextTick(function afterTickTwo() {
21459 fn.call(null, arg1, arg2);
21460 });
21461 case 4:
21462 return process.nextTick(function afterTickThree() {
21463 fn.call(null, arg1, arg2, arg3);
21464 });
21465 default:
21466 args = new Array(len - 1);
21467 i = 0;
21468 while (i < args.length) {
21469 args[i++] = arguments[i];
21470 }
21471 return process.nextTick(function afterTick() {
21472 fn.apply(null, args);
21473 });
21474 }
21475}
21476
21477}).call(this,require('_process'))
21478},{"_process":133}],133:[function(require,module,exports){
21479// shim for using process in browser
21480var process = module.exports = {};
21481
21482// cached from whatever global is present so that test runners that stub it
21483// don't break things. But we need to wrap it in a try catch in case it is
21484// wrapped in strict mode code which doesn't define any globals. It's inside a
21485// function because try/catches deoptimize in certain engines.
21486
21487var cachedSetTimeout;
21488var cachedClearTimeout;
21489
21490function defaultSetTimout() {
21491 throw new Error('setTimeout has not been defined');
21492}
21493function defaultClearTimeout () {
21494 throw new Error('clearTimeout has not been defined');
21495}
21496(function () {
21497 try {
21498 if (typeof setTimeout === 'function') {
21499 cachedSetTimeout = setTimeout;
21500 } else {
21501 cachedSetTimeout = defaultSetTimout;
21502 }
21503 } catch (e) {
21504 cachedSetTimeout = defaultSetTimout;
21505 }
21506 try {
21507 if (typeof clearTimeout === 'function') {
21508 cachedClearTimeout = clearTimeout;
21509 } else {
21510 cachedClearTimeout = defaultClearTimeout;
21511 }
21512 } catch (e) {
21513 cachedClearTimeout = defaultClearTimeout;
21514 }
21515} ())
21516function runTimeout(fun) {
21517 if (cachedSetTimeout === setTimeout) {
21518 //normal enviroments in sane situations
21519 return setTimeout(fun, 0);
21520 }
21521 // if setTimeout wasn't available but was latter defined
21522 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
21523 cachedSetTimeout = setTimeout;
21524 return setTimeout(fun, 0);
21525 }
21526 try {
21527 // when when somebody has screwed with setTimeout but no I.E. maddness
21528 return cachedSetTimeout(fun, 0);
21529 } catch(e){
21530 try {
21531 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
21532 return cachedSetTimeout.call(null, fun, 0);
21533 } catch(e){
21534 // 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
21535 return cachedSetTimeout.call(this, fun, 0);
21536 }
21537 }
21538
21539
21540}
21541function runClearTimeout(marker) {
21542 if (cachedClearTimeout === clearTimeout) {
21543 //normal enviroments in sane situations
21544 return clearTimeout(marker);
21545 }
21546 // if clearTimeout wasn't available but was latter defined
21547 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
21548 cachedClearTimeout = clearTimeout;
21549 return clearTimeout(marker);
21550 }
21551 try {
21552 // when when somebody has screwed with setTimeout but no I.E. maddness
21553 return cachedClearTimeout(marker);
21554 } catch (e){
21555 try {
21556 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
21557 return cachedClearTimeout.call(null, marker);
21558 } catch (e){
21559 // 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.
21560 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
21561 return cachedClearTimeout.call(this, marker);
21562 }
21563 }
21564
21565
21566
21567}
21568var queue = [];
21569var draining = false;
21570var currentQueue;
21571var queueIndex = -1;
21572
21573function cleanUpNextTick() {
21574 if (!draining || !currentQueue) {
21575 return;
21576 }
21577 draining = false;
21578 if (currentQueue.length) {
21579 queue = currentQueue.concat(queue);
21580 } else {
21581 queueIndex = -1;
21582 }
21583 if (queue.length) {
21584 drainQueue();
21585 }
21586}
21587
21588function drainQueue() {
21589 if (draining) {
21590 return;
21591 }
21592 var timeout = runTimeout(cleanUpNextTick);
21593 draining = true;
21594
21595 var len = queue.length;
21596 while(len) {
21597 currentQueue = queue;
21598 queue = [];
21599 while (++queueIndex < len) {
21600 if (currentQueue) {
21601 currentQueue[queueIndex].run();
21602 }
21603 }
21604 queueIndex = -1;
21605 len = queue.length;
21606 }
21607 currentQueue = null;
21608 draining = false;
21609 runClearTimeout(timeout);
21610}
21611
21612process.nextTick = function (fun) {
21613 var args = new Array(arguments.length - 1);
21614 if (arguments.length > 1) {
21615 for (var i = 1; i < arguments.length; i++) {
21616 args[i - 1] = arguments[i];
21617 }
21618 }
21619 queue.push(new Item(fun, args));
21620 if (queue.length === 1 && !draining) {
21621 runTimeout(drainQueue);
21622 }
21623};
21624
21625// v8 likes predictible objects
21626function Item(fun, array) {
21627 this.fun = fun;
21628 this.array = array;
21629}
21630Item.prototype.run = function () {
21631 this.fun.apply(null, this.array);
21632};
21633process.title = 'browser';
21634process.browser = true;
21635process.env = {};
21636process.argv = [];
21637process.version = ''; // empty string to avoid regexp issues
21638process.versions = {};
21639
21640function noop() {}
21641
21642process.on = noop;
21643process.addListener = noop;
21644process.once = noop;
21645process.off = noop;
21646process.removeListener = noop;
21647process.removeAllListeners = noop;
21648process.emit = noop;
21649process.prependListener = noop;
21650process.prependOnceListener = noop;
21651
21652process.listeners = function (name) { return [] }
21653
21654process.binding = function (name) {
21655 throw new Error('process.binding is not supported');
21656};
21657
21658process.cwd = function () { return '/' };
21659process.chdir = function (dir) {
21660 throw new Error('process.chdir is not supported');
21661};
21662process.umask = function() { return 0; };
21663
21664},{}],134:[function(require,module,exports){
21665exports.publicEncrypt = require('./publicEncrypt');
21666exports.privateDecrypt = require('./privateDecrypt');
21667
21668exports.privateEncrypt = function privateEncrypt(key, buf) {
21669 return exports.publicEncrypt(key, buf, true);
21670};
21671
21672exports.publicDecrypt = function publicDecrypt(key, buf) {
21673 return exports.privateDecrypt(key, buf, true);
21674};
21675},{"./privateDecrypt":136,"./publicEncrypt":137}],135:[function(require,module,exports){
21676(function (Buffer){
21677var createHash = require('create-hash');
21678module.exports = function (seed, len) {
21679 var t = new Buffer('');
21680 var i = 0, c;
21681 while (t.length < len) {
21682 c = i2ops(i++);
21683 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]);
21684 }
21685 return t.slice(0, len);
21686};
21687
21688function i2ops(c) {
21689 var out = new Buffer(4);
21690 out.writeUInt32BE(c,0);
21691 return out;
21692}
21693}).call(this,require("buffer").Buffer)
21694},{"buffer":53,"create-hash":57}],136:[function(require,module,exports){
21695(function (Buffer){
21696var parseKeys = require('parse-asn1');
21697var mgf = require('./mgf');
21698var xor = require('./xor');
21699var bn = require('bn.js');
21700var crt = require('browserify-rsa');
21701var createHash = require('create-hash');
21702var withPublic = require('./withPublic');
21703module.exports = function privateDecrypt(private_key, enc, reverse) {
21704 var padding;
21705 if (private_key.padding) {
21706 padding = private_key.padding;
21707 } else if (reverse) {
21708 padding = 1;
21709 } else {
21710 padding = 4;
21711 }
21712
21713 var key = parseKeys(private_key);
21714 var k = key.modulus.byteLength();
21715 if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) {
21716 throw new Error('decryption error');
21717 }
21718 var msg;
21719 if (reverse) {
21720 msg = withPublic(new bn(enc), key);
21721 } else {
21722 msg = crt(enc, key);
21723 }
21724 var zBuffer = new Buffer(k - msg.length);
21725 zBuffer.fill(0);
21726 msg = Buffer.concat([zBuffer, msg], k);
21727 if (padding === 4) {
21728 return oaep(key, msg);
21729 } else if (padding === 1) {
21730 return pkcs1(key, msg, reverse);
21731 } else if (padding === 3) {
21732 return msg;
21733 } else {
21734 throw new Error('unknown padding');
21735 }
21736};
21737
21738function oaep(key, msg){
21739 var n = key.modulus;
21740 var k = key.modulus.byteLength();
21741 var mLen = msg.length;
21742 var iHash = createHash('sha1').update(new Buffer('')).digest();
21743 var hLen = iHash.length;
21744 var hLen2 = 2 * hLen;
21745 if (msg[0] !== 0) {
21746 throw new Error('decryption error');
21747 }
21748 var maskedSeed = msg.slice(1, hLen + 1);
21749 var maskedDb = msg.slice(hLen + 1);
21750 var seed = xor(maskedSeed, mgf(maskedDb, hLen));
21751 var db = xor(maskedDb, mgf(seed, k - hLen - 1));
21752 if (compare(iHash, db.slice(0, hLen))) {
21753 throw new Error('decryption error');
21754 }
21755 var i = hLen;
21756 while (db[i] === 0) {
21757 i++;
21758 }
21759 if (db[i++] !== 1) {
21760 throw new Error('decryption error');
21761 }
21762 return db.slice(i);
21763}
21764
21765function pkcs1(key, msg, reverse){
21766 var p1 = msg.slice(0, 2);
21767 var i = 2;
21768 var status = 0;
21769 while (msg[i++] !== 0) {
21770 if (i >= msg.length) {
21771 status++;
21772 break;
21773 }
21774 }
21775 var ps = msg.slice(2, i - 1);
21776 var p2 = msg.slice(i - 1, i);
21777
21778 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){
21779 status++;
21780 }
21781 if (ps.length < 8) {
21782 status++;
21783 }
21784 if (status) {
21785 throw new Error('decryption error');
21786 }
21787 return msg.slice(i);
21788}
21789function compare(a, b){
21790 a = new Buffer(a);
21791 b = new Buffer(b);
21792 var dif = 0;
21793 var len = a.length;
21794 if (a.length !== b.length) {
21795 dif++;
21796 len = Math.min(a.length, b.length);
21797 }
21798 var i = -1;
21799 while (++i < len) {
21800 dif += (a[i] ^ b[i]);
21801 }
21802 return dif;
21803}
21804}).call(this,require("buffer").Buffer)
21805},{"./mgf":135,"./withPublic":138,"./xor":139,"bn.js":21,"browserify-rsa":44,"buffer":53,"create-hash":57,"parse-asn1":126}],137:[function(require,module,exports){
21806(function (Buffer){
21807var parseKeys = require('parse-asn1');
21808var randomBytes = require('randombytes');
21809var createHash = require('create-hash');
21810var mgf = require('./mgf');
21811var xor = require('./xor');
21812var bn = require('bn.js');
21813var withPublic = require('./withPublic');
21814var crt = require('browserify-rsa');
21815
21816var constants = {
21817 RSA_PKCS1_OAEP_PADDING: 4,
21818 RSA_PKCS1_PADDIN: 1,
21819 RSA_NO_PADDING: 3
21820};
21821
21822module.exports = function publicEncrypt(public_key, msg, reverse) {
21823 var padding;
21824 if (public_key.padding) {
21825 padding = public_key.padding;
21826 } else if (reverse) {
21827 padding = 1;
21828 } else {
21829 padding = 4;
21830 }
21831 var key = parseKeys(public_key);
21832 var paddedMsg;
21833 if (padding === 4) {
21834 paddedMsg = oaep(key, msg);
21835 } else if (padding === 1) {
21836 paddedMsg = pkcs1(key, msg, reverse);
21837 } else if (padding === 3) {
21838 paddedMsg = new bn(msg);
21839 if (paddedMsg.cmp(key.modulus) >= 0) {
21840 throw new Error('data too long for modulus');
21841 }
21842 } else {
21843 throw new Error('unknown padding');
21844 }
21845 if (reverse) {
21846 return crt(paddedMsg, key);
21847 } else {
21848 return withPublic(paddedMsg, key);
21849 }
21850};
21851
21852function oaep(key, msg){
21853 var k = key.modulus.byteLength();
21854 var mLen = msg.length;
21855 var iHash = createHash('sha1').update(new Buffer('')).digest();
21856 var hLen = iHash.length;
21857 var hLen2 = 2 * hLen;
21858 if (mLen > k - hLen2 - 2) {
21859 throw new Error('message too long');
21860 }
21861 var ps = new Buffer(k - mLen - hLen2 - 2);
21862 ps.fill(0);
21863 var dblen = k - hLen - 1;
21864 var seed = randomBytes(hLen);
21865 var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen));
21866 var maskedSeed = xor(seed, mgf(maskedDb, hLen));
21867 return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k));
21868}
21869function pkcs1(key, msg, reverse){
21870 var mLen = msg.length;
21871 var k = key.modulus.byteLength();
21872 if (mLen > k - 11) {
21873 throw new Error('message too long');
21874 }
21875 var ps;
21876 if (reverse) {
21877 ps = new Buffer(k - mLen - 3);
21878 ps.fill(0xff);
21879 } else {
21880 ps = nonZero(k - mLen - 3);
21881 }
21882 return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k));
21883}
21884function nonZero(len, crypto) {
21885 var out = new Buffer(len);
21886 var i = 0;
21887 var cache = randomBytes(len*2);
21888 var cur = 0;
21889 var num;
21890 while (i < len) {
21891 if (cur === cache.length) {
21892 cache = randomBytes(len*2);
21893 cur = 0;
21894 }
21895 num = cache[cur++];
21896 if (num) {
21897 out[i++] = num;
21898 }
21899 }
21900 return out;
21901}
21902}).call(this,require("buffer").Buffer)
21903},{"./mgf":135,"./withPublic":138,"./xor":139,"bn.js":21,"browserify-rsa":44,"buffer":53,"create-hash":57,"parse-asn1":126,"randombytes":140}],138:[function(require,module,exports){
21904(function (Buffer){
21905var bn = require('bn.js');
21906function withPublic(paddedMsg, key) {
21907 return new Buffer(paddedMsg
21908 .toRed(bn.mont(key.modulus))
21909 .redPow(new bn(key.publicExponent))
21910 .fromRed()
21911 .toArray());
21912}
21913
21914module.exports = withPublic;
21915}).call(this,require("buffer").Buffer)
21916},{"bn.js":21,"buffer":53}],139:[function(require,module,exports){
21917module.exports = function xor(a, b) {
21918 var len = a.length;
21919 var i = -1;
21920 while (++i < len) {
21921 a[i] ^= b[i];
21922 }
21923 return a
21924};
21925},{}],140:[function(require,module,exports){
21926(function (process,global){
21927'use strict'
21928
21929function oldBrowser () {
21930 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
21931}
21932
21933var Buffer = require('safe-buffer').Buffer
21934var crypto = global.crypto || global.msCrypto
21935
21936if (crypto && crypto.getRandomValues) {
21937 module.exports = randomBytes
21938} else {
21939 module.exports = oldBrowser
21940}
21941
21942function randomBytes (size, cb) {
21943 // phantomjs needs to throw
21944 if (size > 65536) throw new Error('requested too many random bytes')
21945 // in case browserify isn't using the Uint8Array version
21946 var rawBytes = new global.Uint8Array(size)
21947
21948 // This will not work in older browsers.
21949 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
21950 if (size > 0) { // getRandomValues fails on IE if size == 0
21951 crypto.getRandomValues(rawBytes)
21952 }
21953
21954 // XXX: phantomjs doesn't like a buffer being passed here
21955 var bytes = Buffer.from(rawBytes.buffer)
21956
21957 if (typeof cb === 'function') {
21958 return process.nextTick(function () {
21959 cb(null, bytes)
21960 })
21961 }
21962
21963 return bytes
21964}
21965
21966}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
21967},{"_process":133,"safe-buffer":156}],141:[function(require,module,exports){
21968(function (process,global){
21969'use strict'
21970
21971function oldBrowser () {
21972 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
21973}
21974var safeBuffer = require('safe-buffer')
21975var randombytes = require('randombytes')
21976var Buffer = safeBuffer.Buffer
21977var kBufferMaxLength = safeBuffer.kMaxLength
21978var crypto = global.crypto || global.msCrypto
21979var kMaxUint32 = Math.pow(2, 32) - 1
21980function assertOffset (offset, length) {
21981 if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
21982 throw new TypeError('offset must be a number')
21983 }
21984
21985 if (offset > kMaxUint32 || offset < 0) {
21986 throw new TypeError('offset must be a uint32')
21987 }
21988
21989 if (offset > kBufferMaxLength || offset > length) {
21990 throw new RangeError('offset out of range')
21991 }
21992}
21993
21994function assertSize (size, offset, length) {
21995 if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
21996 throw new TypeError('size must be a number')
21997 }
21998
21999 if (size > kMaxUint32 || size < 0) {
22000 throw new TypeError('size must be a uint32')
22001 }
22002
22003 if (size + offset > length || size > kBufferMaxLength) {
22004 throw new RangeError('buffer too small')
22005 }
22006}
22007if ((crypto && crypto.getRandomValues) || !process.browser) {
22008 exports.randomFill = randomFill
22009 exports.randomFillSync = randomFillSync
22010} else {
22011 exports.randomFill = oldBrowser
22012 exports.randomFillSync = oldBrowser
22013}
22014function randomFill (buf, offset, size, cb) {
22015 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
22016 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
22017 }
22018
22019 if (typeof offset === 'function') {
22020 cb = offset
22021 offset = 0
22022 size = buf.length
22023 } else if (typeof size === 'function') {
22024 cb = size
22025 size = buf.length - offset
22026 } else if (typeof cb !== 'function') {
22027 throw new TypeError('"cb" argument must be a function')
22028 }
22029 assertOffset(offset, buf.length)
22030 assertSize(size, offset, buf.length)
22031 return actualFill(buf, offset, size, cb)
22032}
22033
22034function actualFill (buf, offset, size, cb) {
22035 if (process.browser) {
22036 var ourBuf = buf.buffer
22037 var uint = new Uint8Array(ourBuf, offset, size)
22038 crypto.getRandomValues(uint)
22039 if (cb) {
22040 process.nextTick(function () {
22041 cb(null, buf)
22042 })
22043 return
22044 }
22045 return buf
22046 }
22047 if (cb) {
22048 randombytes(size, function (err, bytes) {
22049 if (err) {
22050 return cb(err)
22051 }
22052 bytes.copy(buf, offset)
22053 cb(null, buf)
22054 })
22055 return
22056 }
22057 var bytes = randombytes(size)
22058 bytes.copy(buf, offset)
22059 return buf
22060}
22061function randomFillSync (buf, offset, size) {
22062 if (typeof offset === 'undefined') {
22063 offset = 0
22064 }
22065 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
22066 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
22067 }
22068
22069 assertOffset(offset, buf.length)
22070
22071 if (size === undefined) size = buf.length - offset
22072
22073 assertSize(size, offset, buf.length)
22074
22075 return actualFill(buf, offset, size)
22076}
22077
22078}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
22079},{"_process":133,"randombytes":140,"safe-buffer":156}],142:[function(require,module,exports){
22080module.exports = require('./lib/_stream_duplex.js');
22081
22082},{"./lib/_stream_duplex.js":143}],143:[function(require,module,exports){
22083// Copyright Joyent, Inc. and other Node contributors.
22084//
22085// Permission is hereby granted, free of charge, to any person obtaining a
22086// copy of this software and associated documentation files (the
22087// "Software"), to deal in the Software without restriction, including
22088// without limitation the rights to use, copy, modify, merge, publish,
22089// distribute, sublicense, and/or sell copies of the Software, and to permit
22090// persons to whom the Software is furnished to do so, subject to the
22091// following conditions:
22092//
22093// The above copyright notice and this permission notice shall be included
22094// in all copies or substantial portions of the Software.
22095//
22096// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22097// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22098// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22099// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
22100// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22101// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22102// USE OR OTHER DEALINGS IN THE SOFTWARE.
22103
22104// a duplex stream is just a stream that is both readable and writable.
22105// Since JS doesn't have multiple prototypal inheritance, this class
22106// prototypally inherits from Readable, and then parasitically from
22107// Writable.
22108
22109'use strict';
22110
22111/*<replacement>*/
22112
22113var processNextTick = require('process-nextick-args');
22114/*</replacement>*/
22115
22116/*<replacement>*/
22117var objectKeys = Object.keys || function (obj) {
22118 var keys = [];
22119 for (var key in obj) {
22120 keys.push(key);
22121 }return keys;
22122};
22123/*</replacement>*/
22124
22125module.exports = Duplex;
22126
22127/*<replacement>*/
22128var util = require('core-util-is');
22129util.inherits = require('inherits');
22130/*</replacement>*/
22131
22132var Readable = require('./_stream_readable');
22133var Writable = require('./_stream_writable');
22134
22135util.inherits(Duplex, Readable);
22136
22137var keys = objectKeys(Writable.prototype);
22138for (var v = 0; v < keys.length; v++) {
22139 var method = keys[v];
22140 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
22141}
22142
22143function Duplex(options) {
22144 if (!(this instanceof Duplex)) return new Duplex(options);
22145
22146 Readable.call(this, options);
22147 Writable.call(this, options);
22148
22149 if (options && options.readable === false) this.readable = false;
22150
22151 if (options && options.writable === false) this.writable = false;
22152
22153 this.allowHalfOpen = true;
22154 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
22155
22156 this.once('end', onend);
22157}
22158
22159// the no-half-open enforcer
22160function onend() {
22161 // if we allow half-open state, or if the writable side ended,
22162 // then we're ok.
22163 if (this.allowHalfOpen || this._writableState.ended) return;
22164
22165 // no more data can be written.
22166 // But allow more writes to happen in this tick.
22167 processNextTick(onEndNT, this);
22168}
22169
22170function onEndNT(self) {
22171 self.end();
22172}
22173
22174Object.defineProperty(Duplex.prototype, 'destroyed', {
22175 get: function () {
22176 if (this._readableState === undefined || this._writableState === undefined) {
22177 return false;
22178 }
22179 return this._readableState.destroyed && this._writableState.destroyed;
22180 },
22181 set: function (value) {
22182 // we ignore the value if the stream
22183 // has not been initialized yet
22184 if (this._readableState === undefined || this._writableState === undefined) {
22185 return;
22186 }
22187
22188 // backward compatibility, the user is explicitly
22189 // managing destroyed
22190 this._readableState.destroyed = value;
22191 this._writableState.destroyed = value;
22192 }
22193});
22194
22195Duplex.prototype._destroy = function (err, cb) {
22196 this.push(null);
22197 this.end();
22198
22199 processNextTick(cb, err);
22200};
22201
22202function forEach(xs, f) {
22203 for (var i = 0, l = xs.length; i < l; i++) {
22204 f(xs[i], i);
22205 }
22206}
22207},{"./_stream_readable":145,"./_stream_writable":147,"core-util-is":55,"inherits":107,"process-nextick-args":132}],144:[function(require,module,exports){
22208// Copyright Joyent, Inc. and other Node contributors.
22209//
22210// Permission is hereby granted, free of charge, to any person obtaining a
22211// copy of this software and associated documentation files (the
22212// "Software"), to deal in the Software without restriction, including
22213// without limitation the rights to use, copy, modify, merge, publish,
22214// distribute, sublicense, and/or sell copies of the Software, and to permit
22215// persons to whom the Software is furnished to do so, subject to the
22216// following conditions:
22217//
22218// The above copyright notice and this permission notice shall be included
22219// in all copies or substantial portions of the Software.
22220//
22221// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22222// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22223// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22224// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
22225// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22226// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22227// USE OR OTHER DEALINGS IN THE SOFTWARE.
22228
22229// a passthrough stream.
22230// basically just the most minimal sort of Transform stream.
22231// Every written chunk gets output as-is.
22232
22233'use strict';
22234
22235module.exports = PassThrough;
22236
22237var Transform = require('./_stream_transform');
22238
22239/*<replacement>*/
22240var util = require('core-util-is');
22241util.inherits = require('inherits');
22242/*</replacement>*/
22243
22244util.inherits(PassThrough, Transform);
22245
22246function PassThrough(options) {
22247 if (!(this instanceof PassThrough)) return new PassThrough(options);
22248
22249 Transform.call(this, options);
22250}
22251
22252PassThrough.prototype._transform = function (chunk, encoding, cb) {
22253 cb(null, chunk);
22254};
22255},{"./_stream_transform":146,"core-util-is":55,"inherits":107}],145:[function(require,module,exports){
22256(function (process,global){
22257// Copyright Joyent, Inc. and other Node contributors.
22258//
22259// Permission is hereby granted, free of charge, to any person obtaining a
22260// copy of this software and associated documentation files (the
22261// "Software"), to deal in the Software without restriction, including
22262// without limitation the rights to use, copy, modify, merge, publish,
22263// distribute, sublicense, and/or sell copies of the Software, and to permit
22264// persons to whom the Software is furnished to do so, subject to the
22265// following conditions:
22266//
22267// The above copyright notice and this permission notice shall be included
22268// in all copies or substantial portions of the Software.
22269//
22270// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22271// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22272// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22273// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
22274// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22275// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22276// USE OR OTHER DEALINGS IN THE SOFTWARE.
22277
22278'use strict';
22279
22280/*<replacement>*/
22281
22282var processNextTick = require('process-nextick-args');
22283/*</replacement>*/
22284
22285module.exports = Readable;
22286
22287/*<replacement>*/
22288var isArray = require('isarray');
22289/*</replacement>*/
22290
22291/*<replacement>*/
22292var Duplex;
22293/*</replacement>*/
22294
22295Readable.ReadableState = ReadableState;
22296
22297/*<replacement>*/
22298var EE = require('events').EventEmitter;
22299
22300var EElistenerCount = function (emitter, type) {
22301 return emitter.listeners(type).length;
22302};
22303/*</replacement>*/
22304
22305/*<replacement>*/
22306var Stream = require('./internal/streams/stream');
22307/*</replacement>*/
22308
22309// TODO(bmeurer): Change this back to const once hole checks are
22310// properly optimized away early in Ignition+TurboFan.
22311/*<replacement>*/
22312var Buffer = require('safe-buffer').Buffer;
22313var OurUint8Array = global.Uint8Array || function () {};
22314function _uint8ArrayToBuffer(chunk) {
22315 return Buffer.from(chunk);
22316}
22317function _isUint8Array(obj) {
22318 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
22319}
22320/*</replacement>*/
22321
22322/*<replacement>*/
22323var util = require('core-util-is');
22324util.inherits = require('inherits');
22325/*</replacement>*/
22326
22327/*<replacement>*/
22328var debugUtil = require('util');
22329var debug = void 0;
22330if (debugUtil && debugUtil.debuglog) {
22331 debug = debugUtil.debuglog('stream');
22332} else {
22333 debug = function () {};
22334}
22335/*</replacement>*/
22336
22337var BufferList = require('./internal/streams/BufferList');
22338var destroyImpl = require('./internal/streams/destroy');
22339var StringDecoder;
22340
22341util.inherits(Readable, Stream);
22342
22343var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
22344
22345function prependListener(emitter, event, fn) {
22346 // Sadly this is not cacheable as some libraries bundle their own
22347 // event emitter implementation with them.
22348 if (typeof emitter.prependListener === 'function') {
22349 return emitter.prependListener(event, fn);
22350 } else {
22351 // This is a hack to make sure that our error handler is attached before any
22352 // userland ones. NEVER DO THIS. This is here only because this code needs
22353 // to continue to work with older versions of Node.js that do not include
22354 // the prependListener() method. The goal is to eventually remove this hack.
22355 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]];
22356 }
22357}
22358
22359function ReadableState(options, stream) {
22360 Duplex = Duplex || require('./_stream_duplex');
22361
22362 options = options || {};
22363
22364 // object stream flag. Used to make read(n) ignore n and to
22365 // make all the buffer merging and length checks go away
22366 this.objectMode = !!options.objectMode;
22367
22368 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
22369
22370 // the point at which it stops calling _read() to fill the buffer
22371 // Note: 0 is a valid value, means "don't call _read preemptively ever"
22372 var hwm = options.highWaterMark;
22373 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
22374 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
22375
22376 // cast to ints.
22377 this.highWaterMark = Math.floor(this.highWaterMark);
22378
22379 // A linked list is used to store data chunks instead of an array because the
22380 // linked list can remove elements from the beginning faster than
22381 // array.shift()
22382 this.buffer = new BufferList();
22383 this.length = 0;
22384 this.pipes = null;
22385 this.pipesCount = 0;
22386 this.flowing = null;
22387 this.ended = false;
22388 this.endEmitted = false;
22389 this.reading = false;
22390
22391 // a flag to be able to tell if the event 'readable'/'data' is emitted
22392 // immediately, or on a later tick. We set this to true at first, because
22393 // any actions that shouldn't happen until "later" should generally also
22394 // not happen before the first read call.
22395 this.sync = true;
22396
22397 // whenever we return null, then we set a flag to say
22398 // that we're awaiting a 'readable' event emission.
22399 this.needReadable = false;
22400 this.emittedReadable = false;
22401 this.readableListening = false;
22402 this.resumeScheduled = false;
22403
22404 // has it been destroyed
22405 this.destroyed = false;
22406
22407 // Crypto is kind of old and crusty. Historically, its default string
22408 // encoding is 'binary' so we have to make this configurable.
22409 // Everything else in the universe uses 'utf8', though.
22410 this.defaultEncoding = options.defaultEncoding || 'utf8';
22411
22412 // the number of writers that are awaiting a drain event in .pipe()s
22413 this.awaitDrain = 0;
22414
22415 // if true, a maybeReadMore has been scheduled
22416 this.readingMore = false;
22417
22418 this.decoder = null;
22419 this.encoding = null;
22420 if (options.encoding) {
22421 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
22422 this.decoder = new StringDecoder(options.encoding);
22423 this.encoding = options.encoding;
22424 }
22425}
22426
22427function Readable(options) {
22428 Duplex = Duplex || require('./_stream_duplex');
22429
22430 if (!(this instanceof Readable)) return new Readable(options);
22431
22432 this._readableState = new ReadableState(options, this);
22433
22434 // legacy
22435 this.readable = true;
22436
22437 if (options) {
22438 if (typeof options.read === 'function') this._read = options.read;
22439
22440 if (typeof options.destroy === 'function') this._destroy = options.destroy;
22441 }
22442
22443 Stream.call(this);
22444}
22445
22446Object.defineProperty(Readable.prototype, 'destroyed', {
22447 get: function () {
22448 if (this._readableState === undefined) {
22449 return false;
22450 }
22451 return this._readableState.destroyed;
22452 },
22453 set: function (value) {
22454 // we ignore the value if the stream
22455 // has not been initialized yet
22456 if (!this._readableState) {
22457 return;
22458 }
22459
22460 // backward compatibility, the user is explicitly
22461 // managing destroyed
22462 this._readableState.destroyed = value;
22463 }
22464});
22465
22466Readable.prototype.destroy = destroyImpl.destroy;
22467Readable.prototype._undestroy = destroyImpl.undestroy;
22468Readable.prototype._destroy = function (err, cb) {
22469 this.push(null);
22470 cb(err);
22471};
22472
22473// Manually shove something into the read() buffer.
22474// This returns true if the highWaterMark has not been hit yet,
22475// similar to how Writable.write() returns true if you should
22476// write() some more.
22477Readable.prototype.push = function (chunk, encoding) {
22478 var state = this._readableState;
22479 var skipChunkCheck;
22480
22481 if (!state.objectMode) {
22482 if (typeof chunk === 'string') {
22483 encoding = encoding || state.defaultEncoding;
22484 if (encoding !== state.encoding) {
22485 chunk = Buffer.from(chunk, encoding);
22486 encoding = '';
22487 }
22488 skipChunkCheck = true;
22489 }
22490 } else {
22491 skipChunkCheck = true;
22492 }
22493
22494 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
22495};
22496
22497// Unshift should *always* be something directly out of read()
22498Readable.prototype.unshift = function (chunk) {
22499 return readableAddChunk(this, chunk, null, true, false);
22500};
22501
22502function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
22503 var state = stream._readableState;
22504 if (chunk === null) {
22505 state.reading = false;
22506 onEofChunk(stream, state);
22507 } else {
22508 var er;
22509 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
22510 if (er) {
22511 stream.emit('error', er);
22512 } else if (state.objectMode || chunk && chunk.length > 0) {
22513 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
22514 chunk = _uint8ArrayToBuffer(chunk);
22515 }
22516
22517 if (addToFront) {
22518 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
22519 } else if (state.ended) {
22520 stream.emit('error', new Error('stream.push() after EOF'));
22521 } else {
22522 state.reading = false;
22523 if (state.decoder && !encoding) {
22524 chunk = state.decoder.write(chunk);
22525 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
22526 } else {
22527 addChunk(stream, state, chunk, false);
22528 }
22529 }
22530 } else if (!addToFront) {
22531 state.reading = false;
22532 }
22533 }
22534
22535 return needMoreData(state);
22536}
22537
22538function addChunk(stream, state, chunk, addToFront) {
22539 if (state.flowing && state.length === 0 && !state.sync) {
22540 stream.emit('data', chunk);
22541 stream.read(0);
22542 } else {
22543 // update the buffer info.
22544 state.length += state.objectMode ? 1 : chunk.length;
22545 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
22546
22547 if (state.needReadable) emitReadable(stream);
22548 }
22549 maybeReadMore(stream, state);
22550}
22551
22552function chunkInvalid(state, chunk) {
22553 var er;
22554 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
22555 er = new TypeError('Invalid non-string/buffer chunk');
22556 }
22557 return er;
22558}
22559
22560// if it's past the high water mark, we can push in some more.
22561// Also, if we have no data yet, we can stand some
22562// more bytes. This is to work around cases where hwm=0,
22563// such as the repl. Also, if the push() triggered a
22564// readable event, and the user called read(largeNumber) such that
22565// needReadable was set, then we ought to push more, so that another
22566// 'readable' event will be triggered.
22567function needMoreData(state) {
22568 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
22569}
22570
22571Readable.prototype.isPaused = function () {
22572 return this._readableState.flowing === false;
22573};
22574
22575// backwards compatibility.
22576Readable.prototype.setEncoding = function (enc) {
22577 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
22578 this._readableState.decoder = new StringDecoder(enc);
22579 this._readableState.encoding = enc;
22580 return this;
22581};
22582
22583// Don't raise the hwm > 8MB
22584var MAX_HWM = 0x800000;
22585function computeNewHighWaterMark(n) {
22586 if (n >= MAX_HWM) {
22587 n = MAX_HWM;
22588 } else {
22589 // Get the next highest power of 2 to prevent increasing hwm excessively in
22590 // tiny amounts
22591 n--;
22592 n |= n >>> 1;
22593 n |= n >>> 2;
22594 n |= n >>> 4;
22595 n |= n >>> 8;
22596 n |= n >>> 16;
22597 n++;
22598 }
22599 return n;
22600}
22601
22602// This function is designed to be inlinable, so please take care when making
22603// changes to the function body.
22604function howMuchToRead(n, state) {
22605 if (n <= 0 || state.length === 0 && state.ended) return 0;
22606 if (state.objectMode) return 1;
22607 if (n !== n) {
22608 // Only flow one buffer at a time
22609 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
22610 }
22611 // If we're asking for more than the current hwm, then raise the hwm.
22612 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
22613 if (n <= state.length) return n;
22614 // Don't have enough
22615 if (!state.ended) {
22616 state.needReadable = true;
22617 return 0;
22618 }
22619 return state.length;
22620}
22621
22622// you can override either this method, or the async _read(n) below.
22623Readable.prototype.read = function (n) {
22624 debug('read', n);
22625 n = parseInt(n, 10);
22626 var state = this._readableState;
22627 var nOrig = n;
22628
22629 if (n !== 0) state.emittedReadable = false;
22630
22631 // if we're doing read(0) to trigger a readable event, but we
22632 // already have a bunch of data in the buffer, then just trigger
22633 // the 'readable' event and move on.
22634 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
22635 debug('read: emitReadable', state.length, state.ended);
22636 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
22637 return null;
22638 }
22639
22640 n = howMuchToRead(n, state);
22641
22642 // if we've ended, and we're now clear, then finish it up.
22643 if (n === 0 && state.ended) {
22644 if (state.length === 0) endReadable(this);
22645 return null;
22646 }
22647
22648 // All the actual chunk generation logic needs to be
22649 // *below* the call to _read. The reason is that in certain
22650 // synthetic stream cases, such as passthrough streams, _read
22651 // may be a completely synchronous operation which may change
22652 // the state of the read buffer, providing enough data when
22653 // before there was *not* enough.
22654 //
22655 // So, the steps are:
22656 // 1. Figure out what the state of things will be after we do
22657 // a read from the buffer.
22658 //
22659 // 2. If that resulting state will trigger a _read, then call _read.
22660 // Note that this may be asynchronous, or synchronous. Yes, it is
22661 // deeply ugly to write APIs this way, but that still doesn't mean
22662 // that the Readable class should behave improperly, as streams are
22663 // designed to be sync/async agnostic.
22664 // Take note if the _read call is sync or async (ie, if the read call
22665 // has returned yet), so that we know whether or not it's safe to emit
22666 // 'readable' etc.
22667 //
22668 // 3. Actually pull the requested chunks out of the buffer and return.
22669
22670 // if we need a readable event, then we need to do some reading.
22671 var doRead = state.needReadable;
22672 debug('need readable', doRead);
22673
22674 // if we currently have less than the highWaterMark, then also read some
22675 if (state.length === 0 || state.length - n < state.highWaterMark) {
22676 doRead = true;
22677 debug('length less than watermark', doRead);
22678 }
22679
22680 // however, if we've ended, then there's no point, and if we're already
22681 // reading, then it's unnecessary.
22682 if (state.ended || state.reading) {
22683 doRead = false;
22684 debug('reading or ended', doRead);
22685 } else if (doRead) {
22686 debug('do read');
22687 state.reading = true;
22688 state.sync = true;
22689 // if the length is currently zero, then we *need* a readable event.
22690 if (state.length === 0) state.needReadable = true;
22691 // call internal read method
22692 this._read(state.highWaterMark);
22693 state.sync = false;
22694 // If _read pushed data synchronously, then `reading` will be false,
22695 // and we need to re-evaluate how much data we can return to the user.
22696 if (!state.reading) n = howMuchToRead(nOrig, state);
22697 }
22698
22699 var ret;
22700 if (n > 0) ret = fromList(n, state);else ret = null;
22701
22702 if (ret === null) {
22703 state.needReadable = true;
22704 n = 0;
22705 } else {
22706 state.length -= n;
22707 }
22708
22709 if (state.length === 0) {
22710 // If we have nothing in the buffer, then we want to know
22711 // as soon as we *do* get something into the buffer.
22712 if (!state.ended) state.needReadable = true;
22713
22714 // If we tried to read() past the EOF, then emit end on the next tick.
22715 if (nOrig !== n && state.ended) endReadable(this);
22716 }
22717
22718 if (ret !== null) this.emit('data', ret);
22719
22720 return ret;
22721};
22722
22723function onEofChunk(stream, state) {
22724 if (state.ended) return;
22725 if (state.decoder) {
22726 var chunk = state.decoder.end();
22727 if (chunk && chunk.length) {
22728 state.buffer.push(chunk);
22729 state.length += state.objectMode ? 1 : chunk.length;
22730 }
22731 }
22732 state.ended = true;
22733
22734 // emit 'readable' now to make sure it gets picked up.
22735 emitReadable(stream);
22736}
22737
22738// Don't emit readable right away in sync mode, because this can trigger
22739// another read() call => stack overflow. This way, it might trigger
22740// a nextTick recursion warning, but that's not so bad.
22741function emitReadable(stream) {
22742 var state = stream._readableState;
22743 state.needReadable = false;
22744 if (!state.emittedReadable) {
22745 debug('emitReadable', state.flowing);
22746 state.emittedReadable = true;
22747 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
22748 }
22749}
22750
22751function emitReadable_(stream) {
22752 debug('emit readable');
22753 stream.emit('readable');
22754 flow(stream);
22755}
22756
22757// at this point, the user has presumably seen the 'readable' event,
22758// and called read() to consume some data. that may have triggered
22759// in turn another _read(n) call, in which case reading = true if
22760// it's in progress.
22761// However, if we're not ended, or reading, and the length < hwm,
22762// then go ahead and try to read some more preemptively.
22763function maybeReadMore(stream, state) {
22764 if (!state.readingMore) {
22765 state.readingMore = true;
22766 processNextTick(maybeReadMore_, stream, state);
22767 }
22768}
22769
22770function maybeReadMore_(stream, state) {
22771 var len = state.length;
22772 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
22773 debug('maybeReadMore read 0');
22774 stream.read(0);
22775 if (len === state.length)
22776 // didn't get any data, stop spinning.
22777 break;else len = state.length;
22778 }
22779 state.readingMore = false;
22780}
22781
22782// abstract method. to be overridden in specific implementation classes.
22783// call cb(er, data) where data is <= n in length.
22784// for virtual (non-string, non-buffer) streams, "length" is somewhat
22785// arbitrary, and perhaps not very meaningful.
22786Readable.prototype._read = function (n) {
22787 this.emit('error', new Error('_read() is not implemented'));
22788};
22789
22790Readable.prototype.pipe = function (dest, pipeOpts) {
22791 var src = this;
22792 var state = this._readableState;
22793
22794 switch (state.pipesCount) {
22795 case 0:
22796 state.pipes = dest;
22797 break;
22798 case 1:
22799 state.pipes = [state.pipes, dest];
22800 break;
22801 default:
22802 state.pipes.push(dest);
22803 break;
22804 }
22805 state.pipesCount += 1;
22806 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
22807
22808 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
22809
22810 var endFn = doEnd ? onend : unpipe;
22811 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
22812
22813 dest.on('unpipe', onunpipe);
22814 function onunpipe(readable, unpipeInfo) {
22815 debug('onunpipe');
22816 if (readable === src) {
22817 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
22818 unpipeInfo.hasUnpiped = true;
22819 cleanup();
22820 }
22821 }
22822 }
22823
22824 function onend() {
22825 debug('onend');
22826 dest.end();
22827 }
22828
22829 // when the dest drains, it reduces the awaitDrain counter
22830 // on the source. This would be more elegant with a .once()
22831 // handler in flow(), but adding and removing repeatedly is
22832 // too slow.
22833 var ondrain = pipeOnDrain(src);
22834 dest.on('drain', ondrain);
22835
22836 var cleanedUp = false;
22837 function cleanup() {
22838 debug('cleanup');
22839 // cleanup event handlers once the pipe is broken
22840 dest.removeListener('close', onclose);
22841 dest.removeListener('finish', onfinish);
22842 dest.removeListener('drain', ondrain);
22843 dest.removeListener('error', onerror);
22844 dest.removeListener('unpipe', onunpipe);
22845 src.removeListener('end', onend);
22846 src.removeListener('end', unpipe);
22847 src.removeListener('data', ondata);
22848
22849 cleanedUp = true;
22850
22851 // if the reader is waiting for a drain event from this
22852 // specific writer, then it would cause it to never start
22853 // flowing again.
22854 // So, if this is awaiting a drain, then we just call it now.
22855 // If we don't know, then assume that we are waiting for one.
22856 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
22857 }
22858
22859 // If the user pushes more data while we're writing to dest then we'll end up
22860 // in ondata again. However, we only want to increase awaitDrain once because
22861 // dest will only emit one 'drain' event for the multiple writes.
22862 // => Introduce a guard on increasing awaitDrain.
22863 var increasedAwaitDrain = false;
22864 src.on('data', ondata);
22865 function ondata(chunk) {
22866 debug('ondata');
22867 increasedAwaitDrain = false;
22868 var ret = dest.write(chunk);
22869 if (false === ret && !increasedAwaitDrain) {
22870 // If the user unpiped during `dest.write()`, it is possible
22871 // to get stuck in a permanently paused state if that write
22872 // also returned false.
22873 // => Check whether `dest` is still a piping destination.
22874 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
22875 debug('false write response, pause', src._readableState.awaitDrain);
22876 src._readableState.awaitDrain++;
22877 increasedAwaitDrain = true;
22878 }
22879 src.pause();
22880 }
22881 }
22882
22883 // if the dest has an error, then stop piping into it.
22884 // however, don't suppress the throwing behavior for this.
22885 function onerror(er) {
22886 debug('onerror', er);
22887 unpipe();
22888 dest.removeListener('error', onerror);
22889 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
22890 }
22891
22892 // Make sure our error handler is attached before userland ones.
22893 prependListener(dest, 'error', onerror);
22894
22895 // Both close and finish should trigger unpipe, but only once.
22896 function onclose() {
22897 dest.removeListener('finish', onfinish);
22898 unpipe();
22899 }
22900 dest.once('close', onclose);
22901 function onfinish() {
22902 debug('onfinish');
22903 dest.removeListener('close', onclose);
22904 unpipe();
22905 }
22906 dest.once('finish', onfinish);
22907
22908 function unpipe() {
22909 debug('unpipe');
22910 src.unpipe(dest);
22911 }
22912
22913 // tell the dest that it's being piped to
22914 dest.emit('pipe', src);
22915
22916 // start the flow if it hasn't been started already.
22917 if (!state.flowing) {
22918 debug('pipe resume');
22919 src.resume();
22920 }
22921
22922 return dest;
22923};
22924
22925function pipeOnDrain(src) {
22926 return function () {
22927 var state = src._readableState;
22928 debug('pipeOnDrain', state.awaitDrain);
22929 if (state.awaitDrain) state.awaitDrain--;
22930 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
22931 state.flowing = true;
22932 flow(src);
22933 }
22934 };
22935}
22936
22937Readable.prototype.unpipe = function (dest) {
22938 var state = this._readableState;
22939 var unpipeInfo = { hasUnpiped: false };
22940
22941 // if we're not piping anywhere, then do nothing.
22942 if (state.pipesCount === 0) return this;
22943
22944 // just one destination. most common case.
22945 if (state.pipesCount === 1) {
22946 // passed in one, but it's not the right one.
22947 if (dest && dest !== state.pipes) return this;
22948
22949 if (!dest) dest = state.pipes;
22950
22951 // got a match.
22952 state.pipes = null;
22953 state.pipesCount = 0;
22954 state.flowing = false;
22955 if (dest) dest.emit('unpipe', this, unpipeInfo);
22956 return this;
22957 }
22958
22959 // slow case. multiple pipe destinations.
22960
22961 if (!dest) {
22962 // remove all.
22963 var dests = state.pipes;
22964 var len = state.pipesCount;
22965 state.pipes = null;
22966 state.pipesCount = 0;
22967 state.flowing = false;
22968
22969 for (var i = 0; i < len; i++) {
22970 dests[i].emit('unpipe', this, unpipeInfo);
22971 }return this;
22972 }
22973
22974 // try to find the right one.
22975 var index = indexOf(state.pipes, dest);
22976 if (index === -1) return this;
22977
22978 state.pipes.splice(index, 1);
22979 state.pipesCount -= 1;
22980 if (state.pipesCount === 1) state.pipes = state.pipes[0];
22981
22982 dest.emit('unpipe', this, unpipeInfo);
22983
22984 return this;
22985};
22986
22987// set up data events if they are asked for
22988// Ensure readable listeners eventually get something
22989Readable.prototype.on = function (ev, fn) {
22990 var res = Stream.prototype.on.call(this, ev, fn);
22991
22992 if (ev === 'data') {
22993 // Start flowing on next tick if stream isn't explicitly paused
22994 if (this._readableState.flowing !== false) this.resume();
22995 } else if (ev === 'readable') {
22996 var state = this._readableState;
22997 if (!state.endEmitted && !state.readableListening) {
22998 state.readableListening = state.needReadable = true;
22999 state.emittedReadable = false;
23000 if (!state.reading) {
23001 processNextTick(nReadingNextTick, this);
23002 } else if (state.length) {
23003 emitReadable(this);
23004 }
23005 }
23006 }
23007
23008 return res;
23009};
23010Readable.prototype.addListener = Readable.prototype.on;
23011
23012function nReadingNextTick(self) {
23013 debug('readable nexttick read 0');
23014 self.read(0);
23015}
23016
23017// pause() and resume() are remnants of the legacy readable stream API
23018// If the user uses them, then switch into old mode.
23019Readable.prototype.resume = function () {
23020 var state = this._readableState;
23021 if (!state.flowing) {
23022 debug('resume');
23023 state.flowing = true;
23024 resume(this, state);
23025 }
23026 return this;
23027};
23028
23029function resume(stream, state) {
23030 if (!state.resumeScheduled) {
23031 state.resumeScheduled = true;
23032 processNextTick(resume_, stream, state);
23033 }
23034}
23035
23036function resume_(stream, state) {
23037 if (!state.reading) {
23038 debug('resume read 0');
23039 stream.read(0);
23040 }
23041
23042 state.resumeScheduled = false;
23043 state.awaitDrain = 0;
23044 stream.emit('resume');
23045 flow(stream);
23046 if (state.flowing && !state.reading) stream.read(0);
23047}
23048
23049Readable.prototype.pause = function () {
23050 debug('call pause flowing=%j', this._readableState.flowing);
23051 if (false !== this._readableState.flowing) {
23052 debug('pause');
23053 this._readableState.flowing = false;
23054 this.emit('pause');
23055 }
23056 return this;
23057};
23058
23059function flow(stream) {
23060 var state = stream._readableState;
23061 debug('flow', state.flowing);
23062 while (state.flowing && stream.read() !== null) {}
23063}
23064
23065// wrap an old-style stream as the async data source.
23066// This is *not* part of the readable stream interface.
23067// It is an ugly unfortunate mess of history.
23068Readable.prototype.wrap = function (stream) {
23069 var state = this._readableState;
23070 var paused = false;
23071
23072 var self = this;
23073 stream.on('end', function () {
23074 debug('wrapped end');
23075 if (state.decoder && !state.ended) {
23076 var chunk = state.decoder.end();
23077 if (chunk && chunk.length) self.push(chunk);
23078 }
23079
23080 self.push(null);
23081 });
23082
23083 stream.on('data', function (chunk) {
23084 debug('wrapped data');
23085 if (state.decoder) chunk = state.decoder.write(chunk);
23086
23087 // don't skip over falsy values in objectMode
23088 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
23089
23090 var ret = self.push(chunk);
23091 if (!ret) {
23092 paused = true;
23093 stream.pause();
23094 }
23095 });
23096
23097 // proxy all the other methods.
23098 // important when wrapping filters and duplexes.
23099 for (var i in stream) {
23100 if (this[i] === undefined && typeof stream[i] === 'function') {
23101 this[i] = function (method) {
23102 return function () {
23103 return stream[method].apply(stream, arguments);
23104 };
23105 }(i);
23106 }
23107 }
23108
23109 // proxy certain important events.
23110 for (var n = 0; n < kProxyEvents.length; n++) {
23111 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
23112 }
23113
23114 // when we try to consume some more bytes, simply unpause the
23115 // underlying stream.
23116 self._read = function (n) {
23117 debug('wrapped _read', n);
23118 if (paused) {
23119 paused = false;
23120 stream.resume();
23121 }
23122 };
23123
23124 return self;
23125};
23126
23127// exposed for testing purposes only.
23128Readable._fromList = fromList;
23129
23130// Pluck off n bytes from an array of buffers.
23131// Length is the combined lengths of all the buffers in the list.
23132// This function is designed to be inlinable, so please take care when making
23133// changes to the function body.
23134function fromList(n, state) {
23135 // nothing buffered
23136 if (state.length === 0) return null;
23137
23138 var ret;
23139 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
23140 // read it all, truncate the list
23141 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);
23142 state.buffer.clear();
23143 } else {
23144 // read part of list
23145 ret = fromListPartial(n, state.buffer, state.decoder);
23146 }
23147
23148 return ret;
23149}
23150
23151// Extracts only enough buffered data to satisfy the amount requested.
23152// This function is designed to be inlinable, so please take care when making
23153// changes to the function body.
23154function fromListPartial(n, list, hasStrings) {
23155 var ret;
23156 if (n < list.head.data.length) {
23157 // slice is the same for buffers and strings
23158 ret = list.head.data.slice(0, n);
23159 list.head.data = list.head.data.slice(n);
23160 } else if (n === list.head.data.length) {
23161 // first chunk is a perfect match
23162 ret = list.shift();
23163 } else {
23164 // result spans more than one buffer
23165 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
23166 }
23167 return ret;
23168}
23169
23170// Copies a specified amount of characters from the list of buffered data
23171// chunks.
23172// This function is designed to be inlinable, so please take care when making
23173// changes to the function body.
23174function copyFromBufferString(n, list) {
23175 var p = list.head;
23176 var c = 1;
23177 var ret = p.data;
23178 n -= ret.length;
23179 while (p = p.next) {
23180 var str = p.data;
23181 var nb = n > str.length ? str.length : n;
23182 if (nb === str.length) ret += str;else ret += str.slice(0, n);
23183 n -= nb;
23184 if (n === 0) {
23185 if (nb === str.length) {
23186 ++c;
23187 if (p.next) list.head = p.next;else list.head = list.tail = null;
23188 } else {
23189 list.head = p;
23190 p.data = str.slice(nb);
23191 }
23192 break;
23193 }
23194 ++c;
23195 }
23196 list.length -= c;
23197 return ret;
23198}
23199
23200// Copies a specified amount of bytes from the list of buffered data chunks.
23201// This function is designed to be inlinable, so please take care when making
23202// changes to the function body.
23203function copyFromBuffer(n, list) {
23204 var ret = Buffer.allocUnsafe(n);
23205 var p = list.head;
23206 var c = 1;
23207 p.data.copy(ret);
23208 n -= p.data.length;
23209 while (p = p.next) {
23210 var buf = p.data;
23211 var nb = n > buf.length ? buf.length : n;
23212 buf.copy(ret, ret.length - n, 0, nb);
23213 n -= nb;
23214 if (n === 0) {
23215 if (nb === buf.length) {
23216 ++c;
23217 if (p.next) list.head = p.next;else list.head = list.tail = null;
23218 } else {
23219 list.head = p;
23220 p.data = buf.slice(nb);
23221 }
23222 break;
23223 }
23224 ++c;
23225 }
23226 list.length -= c;
23227 return ret;
23228}
23229
23230function endReadable(stream) {
23231 var state = stream._readableState;
23232
23233 // If we get here before consuming all the bytes, then that is a
23234 // bug in node. Should never happen.
23235 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
23236
23237 if (!state.endEmitted) {
23238 state.ended = true;
23239 processNextTick(endReadableNT, state, stream);
23240 }
23241}
23242
23243function endReadableNT(state, stream) {
23244 // Check that we didn't get one last unshift.
23245 if (!state.endEmitted && state.length === 0) {
23246 state.endEmitted = true;
23247 stream.readable = false;
23248 stream.emit('end');
23249 }
23250}
23251
23252function forEach(xs, f) {
23253 for (var i = 0, l = xs.length; i < l; i++) {
23254 f(xs[i], i);
23255 }
23256}
23257
23258function indexOf(xs, x) {
23259 for (var i = 0, l = xs.length; i < l; i++) {
23260 if (xs[i] === x) return i;
23261 }
23262 return -1;
23263}
23264}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23265},{"./_stream_duplex":143,"./internal/streams/BufferList":148,"./internal/streams/destroy":149,"./internal/streams/stream":150,"_process":133,"core-util-is":55,"events":89,"inherits":107,"isarray":109,"process-nextick-args":132,"safe-buffer":156,"string_decoder/":173,"util":23}],146:[function(require,module,exports){
23266// Copyright Joyent, Inc. and other Node contributors.
23267//
23268// Permission is hereby granted, free of charge, to any person obtaining a
23269// copy of this software and associated documentation files (the
23270// "Software"), to deal in the Software without restriction, including
23271// without limitation the rights to use, copy, modify, merge, publish,
23272// distribute, sublicense, and/or sell copies of the Software, and to permit
23273// persons to whom the Software is furnished to do so, subject to the
23274// following conditions:
23275//
23276// The above copyright notice and this permission notice shall be included
23277// in all copies or substantial portions of the Software.
23278//
23279// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23280// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23281// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
23282// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
23283// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23284// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23285// USE OR OTHER DEALINGS IN THE SOFTWARE.
23286
23287// a transform stream is a readable/writable stream where you do
23288// something with the data. Sometimes it's called a "filter",
23289// but that's not a great name for it, since that implies a thing where
23290// some bits pass through, and others are simply ignored. (That would
23291// be a valid example of a transform, of course.)
23292//
23293// While the output is causally related to the input, it's not a
23294// necessarily symmetric or synchronous transformation. For example,
23295// a zlib stream might take multiple plain-text writes(), and then
23296// emit a single compressed chunk some time in the future.
23297//
23298// Here's how this works:
23299//
23300// The Transform stream has all the aspects of the readable and writable
23301// stream classes. When you write(chunk), that calls _write(chunk,cb)
23302// internally, and returns false if there's a lot of pending writes
23303// buffered up. When you call read(), that calls _read(n) until
23304// there's enough pending readable data buffered up.
23305//
23306// In a transform stream, the written data is placed in a buffer. When
23307// _read(n) is called, it transforms the queued up data, calling the
23308// buffered _write cb's as it consumes chunks. If consuming a single
23309// written chunk would result in multiple output chunks, then the first
23310// outputted bit calls the readcb, and subsequent chunks just go into
23311// the read buffer, and will cause it to emit 'readable' if necessary.
23312//
23313// This way, back-pressure is actually determined by the reading side,
23314// since _read has to be called to start processing a new chunk. However,
23315// a pathological inflate type of transform can cause excessive buffering
23316// here. For example, imagine a stream where every byte of input is
23317// interpreted as an integer from 0-255, and then results in that many
23318// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
23319// 1kb of data being output. In this case, you could write a very small
23320// amount of input, and end up with a very large amount of output. In
23321// such a pathological inflating mechanism, there'd be no way to tell
23322// the system to stop doing the transform. A single 4MB write could
23323// cause the system to run out of memory.
23324//
23325// However, even in such a pathological case, only a single written chunk
23326// would be consumed, and then the rest would wait (un-transformed) until
23327// the results of the previous transformed chunk were consumed.
23328
23329'use strict';
23330
23331module.exports = Transform;
23332
23333var Duplex = require('./_stream_duplex');
23334
23335/*<replacement>*/
23336var util = require('core-util-is');
23337util.inherits = require('inherits');
23338/*</replacement>*/
23339
23340util.inherits(Transform, Duplex);
23341
23342function TransformState(stream) {
23343 this.afterTransform = function (er, data) {
23344 return afterTransform(stream, er, data);
23345 };
23346
23347 this.needTransform = false;
23348 this.transforming = false;
23349 this.writecb = null;
23350 this.writechunk = null;
23351 this.writeencoding = null;
23352}
23353
23354function afterTransform(stream, er, data) {
23355 var ts = stream._transformState;
23356 ts.transforming = false;
23357
23358 var cb = ts.writecb;
23359
23360 if (!cb) {
23361 return stream.emit('error', new Error('write callback called multiple times'));
23362 }
23363
23364 ts.writechunk = null;
23365 ts.writecb = null;
23366
23367 if (data !== null && data !== undefined) stream.push(data);
23368
23369 cb(er);
23370
23371 var rs = stream._readableState;
23372 rs.reading = false;
23373 if (rs.needReadable || rs.length < rs.highWaterMark) {
23374 stream._read(rs.highWaterMark);
23375 }
23376}
23377
23378function Transform(options) {
23379 if (!(this instanceof Transform)) return new Transform(options);
23380
23381 Duplex.call(this, options);
23382
23383 this._transformState = new TransformState(this);
23384
23385 var stream = this;
23386
23387 // start out asking for a readable event once data is transformed.
23388 this._readableState.needReadable = true;
23389
23390 // we have implemented the _read method, and done the other things
23391 // that Readable wants before the first _read call, so unset the
23392 // sync guard flag.
23393 this._readableState.sync = false;
23394
23395 if (options) {
23396 if (typeof options.transform === 'function') this._transform = options.transform;
23397
23398 if (typeof options.flush === 'function') this._flush = options.flush;
23399 }
23400
23401 // When the writable side finishes, then flush out anything remaining.
23402 this.once('prefinish', function () {
23403 if (typeof this._flush === 'function') this._flush(function (er, data) {
23404 done(stream, er, data);
23405 });else done(stream);
23406 });
23407}
23408
23409Transform.prototype.push = function (chunk, encoding) {
23410 this._transformState.needTransform = false;
23411 return Duplex.prototype.push.call(this, chunk, encoding);
23412};
23413
23414// This is the part where you do stuff!
23415// override this function in implementation classes.
23416// 'chunk' is an input chunk.
23417//
23418// Call `push(newChunk)` to pass along transformed output
23419// to the readable side. You may call 'push' zero or more times.
23420//
23421// Call `cb(err)` when you are done with this chunk. If you pass
23422// an error, then that'll put the hurt on the whole operation. If you
23423// never call cb(), then you'll never get another chunk.
23424Transform.prototype._transform = function (chunk, encoding, cb) {
23425 throw new Error('_transform() is not implemented');
23426};
23427
23428Transform.prototype._write = function (chunk, encoding, cb) {
23429 var ts = this._transformState;
23430 ts.writecb = cb;
23431 ts.writechunk = chunk;
23432 ts.writeencoding = encoding;
23433 if (!ts.transforming) {
23434 var rs = this._readableState;
23435 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
23436 }
23437};
23438
23439// Doesn't matter what the args are here.
23440// _transform does all the work.
23441// That we got here means that the readable side wants more data.
23442Transform.prototype._read = function (n) {
23443 var ts = this._transformState;
23444
23445 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
23446 ts.transforming = true;
23447 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
23448 } else {
23449 // mark that we need a transform, so that any data that comes in
23450 // will get processed, now that we've asked for it.
23451 ts.needTransform = true;
23452 }
23453};
23454
23455Transform.prototype._destroy = function (err, cb) {
23456 var _this = this;
23457
23458 Duplex.prototype._destroy.call(this, err, function (err2) {
23459 cb(err2);
23460 _this.emit('close');
23461 });
23462};
23463
23464function done(stream, er, data) {
23465 if (er) return stream.emit('error', er);
23466
23467 if (data !== null && data !== undefined) stream.push(data);
23468
23469 // if there's nothing in the write buffer, then that means
23470 // that nothing more will ever be provided
23471 var ws = stream._writableState;
23472 var ts = stream._transformState;
23473
23474 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
23475
23476 if (ts.transforming) throw new Error('Calling transform done when still transforming');
23477
23478 return stream.push(null);
23479}
23480},{"./_stream_duplex":143,"core-util-is":55,"inherits":107}],147:[function(require,module,exports){
23481(function (process,global){
23482// Copyright Joyent, Inc. and other Node contributors.
23483//
23484// Permission is hereby granted, free of charge, to any person obtaining a
23485// copy of this software and associated documentation files (the
23486// "Software"), to deal in the Software without restriction, including
23487// without limitation the rights to use, copy, modify, merge, publish,
23488// distribute, sublicense, and/or sell copies of the Software, and to permit
23489// persons to whom the Software is furnished to do so, subject to the
23490// following conditions:
23491//
23492// The above copyright notice and this permission notice shall be included
23493// in all copies or substantial portions of the Software.
23494//
23495// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23496// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23497// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
23498// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
23499// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23500// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23501// USE OR OTHER DEALINGS IN THE SOFTWARE.
23502
23503// A bit simpler than readable streams.
23504// Implement an async ._write(chunk, encoding, cb), and it'll handle all
23505// the drain event emission and buffering.
23506
23507'use strict';
23508
23509/*<replacement>*/
23510
23511var processNextTick = require('process-nextick-args');
23512/*</replacement>*/
23513
23514module.exports = Writable;
23515
23516/* <replacement> */
23517function WriteReq(chunk, encoding, cb) {
23518 this.chunk = chunk;
23519 this.encoding = encoding;
23520 this.callback = cb;
23521 this.next = null;
23522}
23523
23524// It seems a linked list but it is not
23525// there will be only 2 of these for each stream
23526function CorkedRequest(state) {
23527 var _this = this;
23528
23529 this.next = null;
23530 this.entry = null;
23531 this.finish = function () {
23532 onCorkedFinish(_this, state);
23533 };
23534}
23535/* </replacement> */
23536
23537/*<replacement>*/
23538var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
23539/*</replacement>*/
23540
23541/*<replacement>*/
23542var Duplex;
23543/*</replacement>*/
23544
23545Writable.WritableState = WritableState;
23546
23547/*<replacement>*/
23548var util = require('core-util-is');
23549util.inherits = require('inherits');
23550/*</replacement>*/
23551
23552/*<replacement>*/
23553var internalUtil = {
23554 deprecate: require('util-deprecate')
23555};
23556/*</replacement>*/
23557
23558/*<replacement>*/
23559var Stream = require('./internal/streams/stream');
23560/*</replacement>*/
23561
23562/*<replacement>*/
23563var Buffer = require('safe-buffer').Buffer;
23564var OurUint8Array = global.Uint8Array || function () {};
23565function _uint8ArrayToBuffer(chunk) {
23566 return Buffer.from(chunk);
23567}
23568function _isUint8Array(obj) {
23569 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
23570}
23571/*</replacement>*/
23572
23573var destroyImpl = require('./internal/streams/destroy');
23574
23575util.inherits(Writable, Stream);
23576
23577function nop() {}
23578
23579function WritableState(options, stream) {
23580 Duplex = Duplex || require('./_stream_duplex');
23581
23582 options = options || {};
23583
23584 // object stream flag to indicate whether or not this stream
23585 // contains buffers or objects.
23586 this.objectMode = !!options.objectMode;
23587
23588 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
23589
23590 // the point at which write() starts returning false
23591 // Note: 0 is a valid value, means that we always return false if
23592 // the entire buffer is not flushed immediately on write()
23593 var hwm = options.highWaterMark;
23594 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
23595 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
23596
23597 // cast to ints.
23598 this.highWaterMark = Math.floor(this.highWaterMark);
23599
23600 // if _final has been called
23601 this.finalCalled = false;
23602
23603 // drain event flag.
23604 this.needDrain = false;
23605 // at the start of calling end()
23606 this.ending = false;
23607 // when end() has been called, and returned
23608 this.ended = false;
23609 // when 'finish' is emitted
23610 this.finished = false;
23611
23612 // has it been destroyed
23613 this.destroyed = false;
23614
23615 // should we decode strings into buffers before passing to _write?
23616 // this is here so that some node-core streams can optimize string
23617 // handling at a lower level.
23618 var noDecode = options.decodeStrings === false;
23619 this.decodeStrings = !noDecode;
23620
23621 // Crypto is kind of old and crusty. Historically, its default string
23622 // encoding is 'binary' so we have to make this configurable.
23623 // Everything else in the universe uses 'utf8', though.
23624 this.defaultEncoding = options.defaultEncoding || 'utf8';
23625
23626 // not an actual buffer we keep track of, but a measurement
23627 // of how much we're waiting to get pushed to some underlying
23628 // socket or file.
23629 this.length = 0;
23630
23631 // a flag to see when we're in the middle of a write.
23632 this.writing = false;
23633
23634 // when true all writes will be buffered until .uncork() call
23635 this.corked = 0;
23636
23637 // a flag to be able to tell if the onwrite cb is called immediately,
23638 // or on a later tick. We set this to true at first, because any
23639 // actions that shouldn't happen until "later" should generally also
23640 // not happen before the first write call.
23641 this.sync = true;
23642
23643 // a flag to know if we're processing previously buffered items, which
23644 // may call the _write() callback in the same tick, so that we don't
23645 // end up in an overlapped onwrite situation.
23646 this.bufferProcessing = false;
23647
23648 // the callback that's passed to _write(chunk,cb)
23649 this.onwrite = function (er) {
23650 onwrite(stream, er);
23651 };
23652
23653 // the callback that the user supplies to write(chunk,encoding,cb)
23654 this.writecb = null;
23655
23656 // the amount that is being written when _write is called.
23657 this.writelen = 0;
23658
23659 this.bufferedRequest = null;
23660 this.lastBufferedRequest = null;
23661
23662 // number of pending user-supplied write callbacks
23663 // this must be 0 before 'finish' can be emitted
23664 this.pendingcb = 0;
23665
23666 // emit prefinish if the only thing we're waiting for is _write cbs
23667 // This is relevant for synchronous Transform streams
23668 this.prefinished = false;
23669
23670 // True if the error was already emitted and should not be thrown again
23671 this.errorEmitted = false;
23672
23673 // count buffered requests
23674 this.bufferedRequestCount = 0;
23675
23676 // allocate the first CorkedRequest, there is always
23677 // one allocated and free to use, and we maintain at most two
23678 this.corkedRequestsFree = new CorkedRequest(this);
23679}
23680
23681WritableState.prototype.getBuffer = function getBuffer() {
23682 var current = this.bufferedRequest;
23683 var out = [];
23684 while (current) {
23685 out.push(current);
23686 current = current.next;
23687 }
23688 return out;
23689};
23690
23691(function () {
23692 try {
23693 Object.defineProperty(WritableState.prototype, 'buffer', {
23694 get: internalUtil.deprecate(function () {
23695 return this.getBuffer();
23696 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
23697 });
23698 } catch (_) {}
23699})();
23700
23701// Test _writableState for inheritance to account for Duplex streams,
23702// whose prototype chain only points to Readable.
23703var realHasInstance;
23704if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
23705 realHasInstance = Function.prototype[Symbol.hasInstance];
23706 Object.defineProperty(Writable, Symbol.hasInstance, {
23707 value: function (object) {
23708 if (realHasInstance.call(this, object)) return true;
23709
23710 return object && object._writableState instanceof WritableState;
23711 }
23712 });
23713} else {
23714 realHasInstance = function (object) {
23715 return object instanceof this;
23716 };
23717}
23718
23719function Writable(options) {
23720 Duplex = Duplex || require('./_stream_duplex');
23721
23722 // Writable ctor is applied to Duplexes, too.
23723 // `realHasInstance` is necessary because using plain `instanceof`
23724 // would return false, as no `_writableState` property is attached.
23725
23726 // Trying to use the custom `instanceof` for Writable here will also break the
23727 // Node.js LazyTransform implementation, which has a non-trivial getter for
23728 // `_writableState` that would lead to infinite recursion.
23729 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
23730 return new Writable(options);
23731 }
23732
23733 this._writableState = new WritableState(options, this);
23734
23735 // legacy.
23736 this.writable = true;
23737
23738 if (options) {
23739 if (typeof options.write === 'function') this._write = options.write;
23740
23741 if (typeof options.writev === 'function') this._writev = options.writev;
23742
23743 if (typeof options.destroy === 'function') this._destroy = options.destroy;
23744
23745 if (typeof options.final === 'function') this._final = options.final;
23746 }
23747
23748 Stream.call(this);
23749}
23750
23751// Otherwise people can pipe Writable streams, which is just wrong.
23752Writable.prototype.pipe = function () {
23753 this.emit('error', new Error('Cannot pipe, not readable'));
23754};
23755
23756function writeAfterEnd(stream, cb) {
23757 var er = new Error('write after end');
23758 // TODO: defer error events consistently everywhere, not just the cb
23759 stream.emit('error', er);
23760 processNextTick(cb, er);
23761}
23762
23763// Checks that a user-supplied chunk is valid, especially for the particular
23764// mode the stream is in. Currently this means that `null` is never accepted
23765// and undefined/non-string values are only allowed in object mode.
23766function validChunk(stream, state, chunk, cb) {
23767 var valid = true;
23768 var er = false;
23769
23770 if (chunk === null) {
23771 er = new TypeError('May not write null values to stream');
23772 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
23773 er = new TypeError('Invalid non-string/buffer chunk');
23774 }
23775 if (er) {
23776 stream.emit('error', er);
23777 processNextTick(cb, er);
23778 valid = false;
23779 }
23780 return valid;
23781}
23782
23783Writable.prototype.write = function (chunk, encoding, cb) {
23784 var state = this._writableState;
23785 var ret = false;
23786 var isBuf = _isUint8Array(chunk) && !state.objectMode;
23787
23788 if (isBuf && !Buffer.isBuffer(chunk)) {
23789 chunk = _uint8ArrayToBuffer(chunk);
23790 }
23791
23792 if (typeof encoding === 'function') {
23793 cb = encoding;
23794 encoding = null;
23795 }
23796
23797 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
23798
23799 if (typeof cb !== 'function') cb = nop;
23800
23801 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
23802 state.pendingcb++;
23803 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
23804 }
23805
23806 return ret;
23807};
23808
23809Writable.prototype.cork = function () {
23810 var state = this._writableState;
23811
23812 state.corked++;
23813};
23814
23815Writable.prototype.uncork = function () {
23816 var state = this._writableState;
23817
23818 if (state.corked) {
23819 state.corked--;
23820
23821 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
23822 }
23823};
23824
23825Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
23826 // node::ParseEncoding() requires lower case.
23827 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
23828 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);
23829 this._writableState.defaultEncoding = encoding;
23830 return this;
23831};
23832
23833function decodeChunk(state, chunk, encoding) {
23834 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
23835 chunk = Buffer.from(chunk, encoding);
23836 }
23837 return chunk;
23838}
23839
23840// if we're already writing something, then just put this
23841// in the queue, and wait our turn. Otherwise, call _write
23842// If we return false, then we need a drain event, so set that flag.
23843function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
23844 if (!isBuf) {
23845 var newChunk = decodeChunk(state, chunk, encoding);
23846 if (chunk !== newChunk) {
23847 isBuf = true;
23848 encoding = 'buffer';
23849 chunk = newChunk;
23850 }
23851 }
23852 var len = state.objectMode ? 1 : chunk.length;
23853
23854 state.length += len;
23855
23856 var ret = state.length < state.highWaterMark;
23857 // we must ensure that previous needDrain will not be reset to false.
23858 if (!ret) state.needDrain = true;
23859
23860 if (state.writing || state.corked) {
23861 var last = state.lastBufferedRequest;
23862 state.lastBufferedRequest = {
23863 chunk: chunk,
23864 encoding: encoding,
23865 isBuf: isBuf,
23866 callback: cb,
23867 next: null
23868 };
23869 if (last) {
23870 last.next = state.lastBufferedRequest;
23871 } else {
23872 state.bufferedRequest = state.lastBufferedRequest;
23873 }
23874 state.bufferedRequestCount += 1;
23875 } else {
23876 doWrite(stream, state, false, len, chunk, encoding, cb);
23877 }
23878
23879 return ret;
23880}
23881
23882function doWrite(stream, state, writev, len, chunk, encoding, cb) {
23883 state.writelen = len;
23884 state.writecb = cb;
23885 state.writing = true;
23886 state.sync = true;
23887 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
23888 state.sync = false;
23889}
23890
23891function onwriteError(stream, state, sync, er, cb) {
23892 --state.pendingcb;
23893
23894 if (sync) {
23895 // defer the callback if we are being called synchronously
23896 // to avoid piling up things on the stack
23897 processNextTick(cb, er);
23898 // this can emit finish, and it will always happen
23899 // after error
23900 processNextTick(finishMaybe, stream, state);
23901 stream._writableState.errorEmitted = true;
23902 stream.emit('error', er);
23903 } else {
23904 // the caller expect this to happen before if
23905 // it is async
23906 cb(er);
23907 stream._writableState.errorEmitted = true;
23908 stream.emit('error', er);
23909 // this can emit finish, but finish must
23910 // always follow error
23911 finishMaybe(stream, state);
23912 }
23913}
23914
23915function onwriteStateUpdate(state) {
23916 state.writing = false;
23917 state.writecb = null;
23918 state.length -= state.writelen;
23919 state.writelen = 0;
23920}
23921
23922function onwrite(stream, er) {
23923 var state = stream._writableState;
23924 var sync = state.sync;
23925 var cb = state.writecb;
23926
23927 onwriteStateUpdate(state);
23928
23929 if (er) onwriteError(stream, state, sync, er, cb);else {
23930 // Check if we're actually ready to finish, but don't emit yet
23931 var finished = needFinish(state);
23932
23933 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
23934 clearBuffer(stream, state);
23935 }
23936
23937 if (sync) {
23938 /*<replacement>*/
23939 asyncWrite(afterWrite, stream, state, finished, cb);
23940 /*</replacement>*/
23941 } else {
23942 afterWrite(stream, state, finished, cb);
23943 }
23944 }
23945}
23946
23947function afterWrite(stream, state, finished, cb) {
23948 if (!finished) onwriteDrain(stream, state);
23949 state.pendingcb--;
23950 cb();
23951 finishMaybe(stream, state);
23952}
23953
23954// Must force callback to be called on nextTick, so that we don't
23955// emit 'drain' before the write() consumer gets the 'false' return
23956// value, and has a chance to attach a 'drain' listener.
23957function onwriteDrain(stream, state) {
23958 if (state.length === 0 && state.needDrain) {
23959 state.needDrain = false;
23960 stream.emit('drain');
23961 }
23962}
23963
23964// if there's something in the buffer waiting, then process it
23965function clearBuffer(stream, state) {
23966 state.bufferProcessing = true;
23967 var entry = state.bufferedRequest;
23968
23969 if (stream._writev && entry && entry.next) {
23970 // Fast case, write everything using _writev()
23971 var l = state.bufferedRequestCount;
23972 var buffer = new Array(l);
23973 var holder = state.corkedRequestsFree;
23974 holder.entry = entry;
23975
23976 var count = 0;
23977 var allBuffers = true;
23978 while (entry) {
23979 buffer[count] = entry;
23980 if (!entry.isBuf) allBuffers = false;
23981 entry = entry.next;
23982 count += 1;
23983 }
23984 buffer.allBuffers = allBuffers;
23985
23986 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
23987
23988 // doWrite is almost always async, defer these to save a bit of time
23989 // as the hot path ends with doWrite
23990 state.pendingcb++;
23991 state.lastBufferedRequest = null;
23992 if (holder.next) {
23993 state.corkedRequestsFree = holder.next;
23994 holder.next = null;
23995 } else {
23996 state.corkedRequestsFree = new CorkedRequest(state);
23997 }
23998 } else {
23999 // Slow case, write chunks one-by-one
24000 while (entry) {
24001 var chunk = entry.chunk;
24002 var encoding = entry.encoding;
24003 var cb = entry.callback;
24004 var len = state.objectMode ? 1 : chunk.length;
24005
24006 doWrite(stream, state, false, len, chunk, encoding, cb);
24007 entry = entry.next;
24008 // if we didn't call the onwrite immediately, then
24009 // it means that we need to wait until it does.
24010 // also, that means that the chunk and cb are currently
24011 // being processed, so move the buffer counter past them.
24012 if (state.writing) {
24013 break;
24014 }
24015 }
24016
24017 if (entry === null) state.lastBufferedRequest = null;
24018 }
24019
24020 state.bufferedRequestCount = 0;
24021 state.bufferedRequest = entry;
24022 state.bufferProcessing = false;
24023}
24024
24025Writable.prototype._write = function (chunk, encoding, cb) {
24026 cb(new Error('_write() is not implemented'));
24027};
24028
24029Writable.prototype._writev = null;
24030
24031Writable.prototype.end = function (chunk, encoding, cb) {
24032 var state = this._writableState;
24033
24034 if (typeof chunk === 'function') {
24035 cb = chunk;
24036 chunk = null;
24037 encoding = null;
24038 } else if (typeof encoding === 'function') {
24039 cb = encoding;
24040 encoding = null;
24041 }
24042
24043 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
24044
24045 // .end() fully uncorks
24046 if (state.corked) {
24047 state.corked = 1;
24048 this.uncork();
24049 }
24050
24051 // ignore unnecessary end() calls.
24052 if (!state.ending && !state.finished) endWritable(this, state, cb);
24053};
24054
24055function needFinish(state) {
24056 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
24057}
24058function callFinal(stream, state) {
24059 stream._final(function (err) {
24060 state.pendingcb--;
24061 if (err) {
24062 stream.emit('error', err);
24063 }
24064 state.prefinished = true;
24065 stream.emit('prefinish');
24066 finishMaybe(stream, state);
24067 });
24068}
24069function prefinish(stream, state) {
24070 if (!state.prefinished && !state.finalCalled) {
24071 if (typeof stream._final === 'function') {
24072 state.pendingcb++;
24073 state.finalCalled = true;
24074 processNextTick(callFinal, stream, state);
24075 } else {
24076 state.prefinished = true;
24077 stream.emit('prefinish');
24078 }
24079 }
24080}
24081
24082function finishMaybe(stream, state) {
24083 var need = needFinish(state);
24084 if (need) {
24085 prefinish(stream, state);
24086 if (state.pendingcb === 0) {
24087 state.finished = true;
24088 stream.emit('finish');
24089 }
24090 }
24091 return need;
24092}
24093
24094function endWritable(stream, state, cb) {
24095 state.ending = true;
24096 finishMaybe(stream, state);
24097 if (cb) {
24098 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
24099 }
24100 state.ended = true;
24101 stream.writable = false;
24102}
24103
24104function onCorkedFinish(corkReq, state, err) {
24105 var entry = corkReq.entry;
24106 corkReq.entry = null;
24107 while (entry) {
24108 var cb = entry.callback;
24109 state.pendingcb--;
24110 cb(err);
24111 entry = entry.next;
24112 }
24113 if (state.corkedRequestsFree) {
24114 state.corkedRequestsFree.next = corkReq;
24115 } else {
24116 state.corkedRequestsFree = corkReq;
24117 }
24118}
24119
24120Object.defineProperty(Writable.prototype, 'destroyed', {
24121 get: function () {
24122 if (this._writableState === undefined) {
24123 return false;
24124 }
24125 return this._writableState.destroyed;
24126 },
24127 set: function (value) {
24128 // we ignore the value if the stream
24129 // has not been initialized yet
24130 if (!this._writableState) {
24131 return;
24132 }
24133
24134 // backward compatibility, the user is explicitly
24135 // managing destroyed
24136 this._writableState.destroyed = value;
24137 }
24138});
24139
24140Writable.prototype.destroy = destroyImpl.destroy;
24141Writable.prototype._undestroy = destroyImpl.undestroy;
24142Writable.prototype._destroy = function (err, cb) {
24143 this.end();
24144 cb(err);
24145};
24146}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
24147},{"./_stream_duplex":143,"./internal/streams/destroy":149,"./internal/streams/stream":150,"_process":133,"core-util-is":55,"inherits":107,"process-nextick-args":132,"safe-buffer":156,"util-deprecate":174}],148:[function(require,module,exports){
24148'use strict';
24149
24150/*<replacement>*/
24151
24152function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
24153
24154var Buffer = require('safe-buffer').Buffer;
24155/*</replacement>*/
24156
24157function copyBuffer(src, target, offset) {
24158 src.copy(target, offset);
24159}
24160
24161module.exports = function () {
24162 function BufferList() {
24163 _classCallCheck(this, BufferList);
24164
24165 this.head = null;
24166 this.tail = null;
24167 this.length = 0;
24168 }
24169
24170 BufferList.prototype.push = function push(v) {
24171 var entry = { data: v, next: null };
24172 if (this.length > 0) this.tail.next = entry;else this.head = entry;
24173 this.tail = entry;
24174 ++this.length;
24175 };
24176
24177 BufferList.prototype.unshift = function unshift(v) {
24178 var entry = { data: v, next: this.head };
24179 if (this.length === 0) this.tail = entry;
24180 this.head = entry;
24181 ++this.length;
24182 };
24183
24184 BufferList.prototype.shift = function shift() {
24185 if (this.length === 0) return;
24186 var ret = this.head.data;
24187 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
24188 --this.length;
24189 return ret;
24190 };
24191
24192 BufferList.prototype.clear = function clear() {
24193 this.head = this.tail = null;
24194 this.length = 0;
24195 };
24196
24197 BufferList.prototype.join = function join(s) {
24198 if (this.length === 0) return '';
24199 var p = this.head;
24200 var ret = '' + p.data;
24201 while (p = p.next) {
24202 ret += s + p.data;
24203 }return ret;
24204 };
24205
24206 BufferList.prototype.concat = function concat(n) {
24207 if (this.length === 0) return Buffer.alloc(0);
24208 if (this.length === 1) return this.head.data;
24209 var ret = Buffer.allocUnsafe(n >>> 0);
24210 var p = this.head;
24211 var i = 0;
24212 while (p) {
24213 copyBuffer(p.data, ret, i);
24214 i += p.data.length;
24215 p = p.next;
24216 }
24217 return ret;
24218 };
24219
24220 return BufferList;
24221}();
24222},{"safe-buffer":156}],149:[function(require,module,exports){
24223'use strict';
24224
24225/*<replacement>*/
24226
24227var processNextTick = require('process-nextick-args');
24228/*</replacement>*/
24229
24230// undocumented cb() API, needed for core, not for public API
24231function destroy(err, cb) {
24232 var _this = this;
24233
24234 var readableDestroyed = this._readableState && this._readableState.destroyed;
24235 var writableDestroyed = this._writableState && this._writableState.destroyed;
24236
24237 if (readableDestroyed || writableDestroyed) {
24238 if (cb) {
24239 cb(err);
24240 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
24241 processNextTick(emitErrorNT, this, err);
24242 }
24243 return;
24244 }
24245
24246 // we set destroyed to true before firing error callbacks in order
24247 // to make it re-entrance safe in case destroy() is called within callbacks
24248
24249 if (this._readableState) {
24250 this._readableState.destroyed = true;
24251 }
24252
24253 // if this is a duplex stream mark the writable part as destroyed as well
24254 if (this._writableState) {
24255 this._writableState.destroyed = true;
24256 }
24257
24258 this._destroy(err || null, function (err) {
24259 if (!cb && err) {
24260 processNextTick(emitErrorNT, _this, err);
24261 if (_this._writableState) {
24262 _this._writableState.errorEmitted = true;
24263 }
24264 } else if (cb) {
24265 cb(err);
24266 }
24267 });
24268}
24269
24270function undestroy() {
24271 if (this._readableState) {
24272 this._readableState.destroyed = false;
24273 this._readableState.reading = false;
24274 this._readableState.ended = false;
24275 this._readableState.endEmitted = false;
24276 }
24277
24278 if (this._writableState) {
24279 this._writableState.destroyed = false;
24280 this._writableState.ended = false;
24281 this._writableState.ending = false;
24282 this._writableState.finished = false;
24283 this._writableState.errorEmitted = false;
24284 }
24285}
24286
24287function emitErrorNT(self, err) {
24288 self.emit('error', err);
24289}
24290
24291module.exports = {
24292 destroy: destroy,
24293 undestroy: undestroy
24294};
24295},{"process-nextick-args":132}],150:[function(require,module,exports){
24296module.exports = require('events').EventEmitter;
24297
24298},{"events":89}],151:[function(require,module,exports){
24299module.exports = require('./readable').PassThrough
24300
24301},{"./readable":152}],152:[function(require,module,exports){
24302exports = module.exports = require('./lib/_stream_readable.js');
24303exports.Stream = exports;
24304exports.Readable = exports;
24305exports.Writable = require('./lib/_stream_writable.js');
24306exports.Duplex = require('./lib/_stream_duplex.js');
24307exports.Transform = require('./lib/_stream_transform.js');
24308exports.PassThrough = require('./lib/_stream_passthrough.js');
24309
24310},{"./lib/_stream_duplex.js":143,"./lib/_stream_passthrough.js":144,"./lib/_stream_readable.js":145,"./lib/_stream_transform.js":146,"./lib/_stream_writable.js":147}],153:[function(require,module,exports){
24311module.exports = require('./readable').Transform
24312
24313},{"./readable":152}],154:[function(require,module,exports){
24314module.exports = require('./lib/_stream_writable.js');
24315
24316},{"./lib/_stream_writable.js":147}],155:[function(require,module,exports){
24317(function (Buffer){
24318'use strict'
24319var inherits = require('inherits')
24320var HashBase = require('hash-base')
24321
24322function RIPEMD160 () {
24323 HashBase.call(this, 64)
24324
24325 // state
24326 this._a = 0x67452301
24327 this._b = 0xefcdab89
24328 this._c = 0x98badcfe
24329 this._d = 0x10325476
24330 this._e = 0xc3d2e1f0
24331}
24332
24333inherits(RIPEMD160, HashBase)
24334
24335RIPEMD160.prototype._update = function () {
24336 var m = new Array(16)
24337 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
24338
24339 var al = this._a
24340 var bl = this._b
24341 var cl = this._c
24342 var dl = this._d
24343 var el = this._e
24344
24345 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
24346 // K = 0x00000000
24347 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
24348 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
24349 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
24350 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
24351 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
24352 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
24353 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
24354 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
24355 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
24356 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
24357 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
24358 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
24359 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
24360 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
24361 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
24362 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
24363 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
24364
24365 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
24366 // K = 0x5a827999
24367 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
24368 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
24369 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
24370 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
24371 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
24372 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
24373 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
24374 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
24375 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
24376 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
24377 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
24378 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
24379 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
24380 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
24381 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
24382 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
24383 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
24384
24385 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
24386 // K = 0x6ed9eba1
24387 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
24388 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
24389 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
24390 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
24391 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
24392 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
24393 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
24394 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
24395 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
24396 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
24397 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
24398 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
24399 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
24400 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
24401 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
24402 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
24403 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
24404
24405 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
24406 // K = 0x8f1bbcdc
24407 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
24408 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
24409 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
24410 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
24411 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
24412 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
24413 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
24414 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
24415 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
24416 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
24417 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
24418 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
24419 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
24420 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
24421 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
24422 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
24423 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
24424
24425 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
24426 // K = 0xa953fd4e
24427 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
24428 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
24429 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
24430 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
24431 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
24432 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
24433 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
24434 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
24435 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
24436 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
24437 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
24438 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
24439 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
24440 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
24441 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
24442 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
24443 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
24444
24445 var ar = this._a
24446 var br = this._b
24447 var cr = this._c
24448 var dr = this._d
24449 var er = this._e
24450
24451 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
24452 // K' = 0x50a28be6
24453 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
24454 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
24455 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
24456 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
24457 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
24458 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
24459 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
24460 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
24461 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
24462 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
24463 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
24464 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
24465 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
24466 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
24467 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
24468 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
24469 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
24470
24471 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
24472 // K' = 0x5c4dd124
24473 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
24474 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
24475 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
24476 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
24477 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
24478 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
24479 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
24480 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
24481 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
24482 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
24483 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
24484 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
24485 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
24486 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
24487 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
24488 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
24489 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
24490
24491 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
24492 // K' = 0x6d703ef3
24493 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
24494 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
24495 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
24496 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
24497 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
24498 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
24499 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
24500 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
24501 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
24502 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
24503 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
24504 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
24505 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
24506 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
24507 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
24508 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
24509 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
24510
24511 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
24512 // K' = 0x7a6d76e9
24513 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
24514 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
24515 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
24516 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
24517 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
24518 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
24519 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
24520 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
24521 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
24522 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
24523 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
24524 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
24525 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
24526 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
24527 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
24528 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
24529 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
24530
24531 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
24532 // K' = 0x00000000
24533 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
24534 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
24535 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
24536 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
24537 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
24538 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
24539 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
24540 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
24541 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
24542 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
24543 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
24544 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
24545 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
24546 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
24547 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
24548 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
24549 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
24550
24551 // change state
24552 var t = (this._b + cl + dr) | 0
24553 this._b = (this._c + dl + er) | 0
24554 this._c = (this._d + el + ar) | 0
24555 this._d = (this._e + al + br) | 0
24556 this._e = (this._a + bl + cr) | 0
24557 this._a = t
24558}
24559
24560RIPEMD160.prototype._digest = function () {
24561 // create padding and handle blocks
24562 this._block[this._blockOffset++] = 0x80
24563 if (this._blockOffset > 56) {
24564 this._block.fill(0, this._blockOffset, 64)
24565 this._update()
24566 this._blockOffset = 0
24567 }
24568
24569 this._block.fill(0, this._blockOffset, 56)
24570 this._block.writeUInt32LE(this._length[0], 56)
24571 this._block.writeUInt32LE(this._length[1], 60)
24572 this._update()
24573
24574 // produce result
24575 var buffer = new Buffer(20)
24576 buffer.writeInt32LE(this._a, 0)
24577 buffer.writeInt32LE(this._b, 4)
24578 buffer.writeInt32LE(this._c, 8)
24579 buffer.writeInt32LE(this._d, 12)
24580 buffer.writeInt32LE(this._e, 16)
24581 return buffer
24582}
24583
24584function rotl (x, n) {
24585 return (x << n) | (x >>> (32 - n))
24586}
24587
24588function fn1 (a, b, c, d, e, m, k, s) {
24589 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
24590}
24591
24592function fn2 (a, b, c, d, e, m, k, s) {
24593 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
24594}
24595
24596function fn3 (a, b, c, d, e, m, k, s) {
24597 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
24598}
24599
24600function fn4 (a, b, c, d, e, m, k, s) {
24601 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
24602}
24603
24604function fn5 (a, b, c, d, e, m, k, s) {
24605 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
24606}
24607
24608module.exports = RIPEMD160
24609
24610}).call(this,require("buffer").Buffer)
24611},{"buffer":53,"hash-base":91,"inherits":107}],156:[function(require,module,exports){
24612/* eslint-disable node/no-deprecated-api */
24613var buffer = require('buffer')
24614var Buffer = buffer.Buffer
24615
24616// alternative to using Object.keys for old browsers
24617function copyProps (src, dst) {
24618 for (var key in src) {
24619 dst[key] = src[key]
24620 }
24621}
24622if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
24623 module.exports = buffer
24624} else {
24625 // Copy properties from require('buffer')
24626 copyProps(buffer, exports)
24627 exports.Buffer = SafeBuffer
24628}
24629
24630function SafeBuffer (arg, encodingOrOffset, length) {
24631 return Buffer(arg, encodingOrOffset, length)
24632}
24633
24634// Copy static methods from Buffer
24635copyProps(Buffer, SafeBuffer)
24636
24637SafeBuffer.from = function (arg, encodingOrOffset, length) {
24638 if (typeof arg === 'number') {
24639 throw new TypeError('Argument must not be a number')
24640 }
24641 return Buffer(arg, encodingOrOffset, length)
24642}
24643
24644SafeBuffer.alloc = function (size, fill, encoding) {
24645 if (typeof size !== 'number') {
24646 throw new TypeError('Argument must be a number')
24647 }
24648 var buf = Buffer(size)
24649 if (fill !== undefined) {
24650 if (typeof encoding === 'string') {
24651 buf.fill(fill, encoding)
24652 } else {
24653 buf.fill(fill)
24654 }
24655 } else {
24656 buf.fill(0)
24657 }
24658 return buf
24659}
24660
24661SafeBuffer.allocUnsafe = function (size) {
24662 if (typeof size !== 'number') {
24663 throw new TypeError('Argument must be a number')
24664 }
24665 return Buffer(size)
24666}
24667
24668SafeBuffer.allocUnsafeSlow = function (size) {
24669 if (typeof size !== 'number') {
24670 throw new TypeError('Argument must be a number')
24671 }
24672 return buffer.SlowBuffer(size)
24673}
24674
24675},{"buffer":53}],157:[function(require,module,exports){
24676(function (Buffer){
24677var crypto = require('crypto')
24678/* eslint-disable camelcase */
24679
24680var MAX_VALUE = 0x7fffffff
24681
24682// N = Cpu cost, r = Memory cost, p = parallelization cost
24683function scrypt (key, salt, N, r, p, dkLen, progressCallback) {
24684 if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')
24685
24686 if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')
24687 if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')
24688
24689 var XY = new Buffer(256 * r)
24690 var V = new Buffer(128 * r * N)
24691
24692 // pseudo global
24693 var B32 = new Int32Array(16) // salsa20_8
24694 var x = new Int32Array(16) // salsa20_8
24695 var _X = new Buffer(64) // blockmix_salsa8
24696
24697 // pseudo global
24698 var B = crypto.pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')
24699
24700 var tickCallback
24701 if (progressCallback) {
24702 var totalOps = p * N * 2
24703 var currentOp = 0
24704
24705 tickCallback = function () {
24706 ++currentOp
24707
24708 // send progress notifications once every 1,000 ops
24709 if (currentOp % 1000 === 0) {
24710 progressCallback({
24711 current: currentOp,
24712 total: totalOps,
24713 percent: (currentOp / totalOps) * 100.0
24714 })
24715 }
24716 }
24717 }
24718
24719 for (var i = 0; i < p; i++) {
24720 smix(B, i * 128 * r, r, N, V, XY)
24721 }
24722
24723 return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256')
24724
24725 // all of these functions are actually moved to the top
24726 // due to function hoisting
24727
24728 function smix (B, Bi, r, N, V, XY) {
24729 var Xi = 0
24730 var Yi = 128 * r
24731 var i
24732
24733 B.copy(XY, Xi, Bi, Bi + Yi)
24734
24735 for (i = 0; i < N; i++) {
24736 XY.copy(V, i * Yi, Xi, Xi + Yi)
24737 blockmix_salsa8(XY, Xi, Yi, r)
24738
24739 if (tickCallback) tickCallback()
24740 }
24741
24742 for (i = 0; i < N; i++) {
24743 var offset = Xi + (2 * r - 1) * 64
24744 var j = XY.readUInt32LE(offset) & (N - 1)
24745 blockxor(V, j * Yi, XY, Xi, Yi)
24746 blockmix_salsa8(XY, Xi, Yi, r)
24747
24748 if (tickCallback) tickCallback()
24749 }
24750
24751 XY.copy(B, Bi, Xi, Xi + Yi)
24752 }
24753
24754 function blockmix_salsa8 (BY, Bi, Yi, r) {
24755 var i
24756
24757 arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)
24758
24759 for (i = 0; i < 2 * r; i++) {
24760 blockxor(BY, i * 64, _X, 0, 64)
24761 salsa20_8(_X)
24762 arraycopy(_X, 0, BY, Yi + (i * 64), 64)
24763 }
24764
24765 for (i = 0; i < r; i++) {
24766 arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)
24767 }
24768
24769 for (i = 0; i < r; i++) {
24770 arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)
24771 }
24772 }
24773
24774 function R (a, b) {
24775 return (a << b) | (a >>> (32 - b))
24776 }
24777
24778 function salsa20_8 (B) {
24779 var i
24780
24781 for (i = 0; i < 16; i++) {
24782 B32[i] = (B[i * 4 + 0] & 0xff) << 0
24783 B32[i] |= (B[i * 4 + 1] & 0xff) << 8
24784 B32[i] |= (B[i * 4 + 2] & 0xff) << 16
24785 B32[i] |= (B[i * 4 + 3] & 0xff) << 24
24786 // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js
24787 }
24788
24789 arraycopy(B32, 0, x, 0, 16)
24790
24791 for (i = 8; i > 0; i -= 2) {
24792 x[4] ^= R(x[0] + x[12], 7)
24793 x[8] ^= R(x[4] + x[0], 9)
24794 x[12] ^= R(x[8] + x[4], 13)
24795 x[0] ^= R(x[12] + x[8], 18)
24796 x[9] ^= R(x[5] + x[1], 7)
24797 x[13] ^= R(x[9] + x[5], 9)
24798 x[1] ^= R(x[13] + x[9], 13)
24799 x[5] ^= R(x[1] + x[13], 18)
24800 x[14] ^= R(x[10] + x[6], 7)
24801 x[2] ^= R(x[14] + x[10], 9)
24802 x[6] ^= R(x[2] + x[14], 13)
24803 x[10] ^= R(x[6] + x[2], 18)
24804 x[3] ^= R(x[15] + x[11], 7)
24805 x[7] ^= R(x[3] + x[15], 9)
24806 x[11] ^= R(x[7] + x[3], 13)
24807 x[15] ^= R(x[11] + x[7], 18)
24808 x[1] ^= R(x[0] + x[3], 7)
24809 x[2] ^= R(x[1] + x[0], 9)
24810 x[3] ^= R(x[2] + x[1], 13)
24811 x[0] ^= R(x[3] + x[2], 18)
24812 x[6] ^= R(x[5] + x[4], 7)
24813 x[7] ^= R(x[6] + x[5], 9)
24814 x[4] ^= R(x[7] + x[6], 13)
24815 x[5] ^= R(x[4] + x[7], 18)
24816 x[11] ^= R(x[10] + x[9], 7)
24817 x[8] ^= R(x[11] + x[10], 9)
24818 x[9] ^= R(x[8] + x[11], 13)
24819 x[10] ^= R(x[9] + x[8], 18)
24820 x[12] ^= R(x[15] + x[14], 7)
24821 x[13] ^= R(x[12] + x[15], 9)
24822 x[14] ^= R(x[13] + x[12], 13)
24823 x[15] ^= R(x[14] + x[13], 18)
24824 }
24825
24826 for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]
24827
24828 for (i = 0; i < 16; i++) {
24829 var bi = i * 4
24830 B[bi + 0] = (B32[i] >> 0 & 0xff)
24831 B[bi + 1] = (B32[i] >> 8 & 0xff)
24832 B[bi + 2] = (B32[i] >> 16 & 0xff)
24833 B[bi + 3] = (B32[i] >> 24 & 0xff)
24834 // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js
24835 }
24836 }
24837
24838 // naive approach... going back to loop unrolling may yield additional performance
24839 function blockxor (S, Si, D, Di, len) {
24840 for (var i = 0; i < len; i++) {
24841 D[Di + i] ^= S[Si + i]
24842 }
24843 }
24844}
24845
24846function arraycopy (src, srcPos, dest, destPos, length) {
24847 if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) {
24848 src.copy(dest, destPos, srcPos, srcPos + length)
24849 } else {
24850 while (length--) {
24851 dest[destPos++] = src[srcPos++]
24852 }
24853 }
24854}
24855
24856module.exports = scrypt
24857
24858}).call(this,require("buffer").Buffer)
24859},{"buffer":53,"crypto":62}],158:[function(require,module,exports){
24860'use strict'
24861module.exports = require('./lib')(require('./lib/elliptic'))
24862
24863},{"./lib":162,"./lib/elliptic":161}],159:[function(require,module,exports){
24864(function (Buffer){
24865'use strict'
24866var toString = Object.prototype.toString
24867
24868// TypeError
24869exports.isArray = function (value, message) {
24870 if (!Array.isArray(value)) throw TypeError(message)
24871}
24872
24873exports.isBoolean = function (value, message) {
24874 if (toString.call(value) !== '[object Boolean]') throw TypeError(message)
24875}
24876
24877exports.isBuffer = function (value, message) {
24878 if (!Buffer.isBuffer(value)) throw TypeError(message)
24879}
24880
24881exports.isFunction = function (value, message) {
24882 if (toString.call(value) !== '[object Function]') throw TypeError(message)
24883}
24884
24885exports.isNumber = function (value, message) {
24886 if (toString.call(value) !== '[object Number]') throw TypeError(message)
24887}
24888
24889exports.isObject = function (value, message) {
24890 if (toString.call(value) !== '[object Object]') throw TypeError(message)
24891}
24892
24893// RangeError
24894exports.isBufferLength = function (buffer, length, message) {
24895 if (buffer.length !== length) throw RangeError(message)
24896}
24897
24898exports.isBufferLength2 = function (buffer, length1, length2, message) {
24899 if (buffer.length !== length1 && buffer.length !== length2) throw RangeError(message)
24900}
24901
24902exports.isLengthGTZero = function (value, message) {
24903 if (value.length === 0) throw RangeError(message)
24904}
24905
24906exports.isNumberInInterval = function (number, x, y, message) {
24907 if (number <= x || number >= y) throw RangeError(message)
24908}
24909
24910}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
24911},{"../../is-buffer/index.js":108}],160:[function(require,module,exports){
24912'use strict'
24913var Buffer = require('safe-buffer').Buffer
24914var bip66 = require('bip66')
24915
24916var EC_PRIVKEY_EXPORT_DER_COMPRESSED = Buffer.from([
24917 // begin
24918 0x30, 0x81, 0xd3, 0x02, 0x01, 0x01, 0x04, 0x20,
24919 // private key
24920 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24921 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24922 // middle
24923 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48,
24924 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
24925 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
24926 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04,
24927 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87,
24928 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8,
24929 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
24930 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E,
24931 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00,
24932 // public key
24933 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24934 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24935 0x00
24936])
24937
24938var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([
24939 // begin
24940 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20,
24941 // private key
24942 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24943 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24944 // middle
24945 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48,
24946 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
24947 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
24948 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04,
24949 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87,
24950 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8,
24951 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11,
24952 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10,
24953 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
24954 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E,
24955 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00,
24956 // public key
24957 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24958 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24959 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24960 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
24961 0x00
24962])
24963
24964exports.privateKeyExport = function (privateKey, publicKey, compressed) {
24965 var result = Buffer.from(compressed ? EC_PRIVKEY_EXPORT_DER_COMPRESSED : EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED)
24966 privateKey.copy(result, compressed ? 8 : 9)
24967 publicKey.copy(result, compressed ? 181 : 214)
24968 return result
24969}
24970
24971exports.privateKeyImport = function (privateKey) {
24972 var length = privateKey.length
24973
24974 // sequence header
24975 var index = 0
24976 if (length < index + 1 || privateKey[index] !== 0x30) return
24977 index += 1
24978
24979 // sequence length constructor
24980 if (length < index + 1 || !(privateKey[index] & 0x80)) return
24981
24982 var lenb = privateKey[index] & 0x7f
24983 index += 1
24984 if (lenb < 1 || lenb > 2) return
24985 if (length < index + lenb) return
24986
24987 // sequence length
24988 var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0)
24989 index += lenb
24990 if (length < index + len) return
24991
24992 // sequence element 0: version number (=1)
24993 if (length < index + 3 ||
24994 privateKey[index] !== 0x02 ||
24995 privateKey[index + 1] !== 0x01 ||
24996 privateKey[index + 2] !== 0x01) {
24997 return
24998 }
24999 index += 3
25000
25001 // sequence element 1: octet string, up to 32 bytes
25002 if (length < index + 2 ||
25003 privateKey[index] !== 0x04 ||
25004 privateKey[index + 1] > 0x20 ||
25005 length < index + 2 + privateKey[index + 1]) {
25006 return
25007 }
25008
25009 return privateKey.slice(index + 2, index + 2 + privateKey[index + 1])
25010}
25011
25012exports.signatureExport = function (sigObj) {
25013 var r = Buffer.concat([Buffer.from([0]), sigObj.r])
25014 for (var lenR = 33, posR = 0; lenR > 1 && r[posR] === 0x00 && !(r[posR + 1] & 0x80); --lenR, ++posR);
25015
25016 var s = Buffer.concat([Buffer.from([0]), sigObj.s])
25017 for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS);
25018
25019 return bip66.encode(r.slice(posR), s.slice(posS))
25020}
25021
25022exports.signatureImport = function (sig) {
25023 var r = Buffer.alloc(32, 0)
25024 var s = Buffer.alloc(32, 0)
25025
25026 try {
25027 var sigObj = bip66.decode(sig)
25028 if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1)
25029 if (sigObj.r.length > 32) throw new Error('R length is too long')
25030 if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1)
25031 if (sigObj.s.length > 32) throw new Error('S length is too long')
25032 } catch (err) {
25033 return
25034 }
25035
25036 sigObj.r.copy(r, 32 - sigObj.r.length)
25037 sigObj.s.copy(s, 32 - sigObj.s.length)
25038
25039 return { r: r, s: s }
25040}
25041
25042exports.signatureImportLax = function (sig) {
25043 var r = Buffer.alloc(32, 0)
25044 var s = Buffer.alloc(32, 0)
25045
25046 var length = sig.length
25047 var index = 0
25048
25049 // sequence tag byte
25050 if (sig[index++] !== 0x30) return
25051
25052 // sequence length byte
25053 var lenbyte = sig[index++]
25054 if (lenbyte & 0x80) {
25055 index += lenbyte - 0x80
25056 if (index > length) return
25057 }
25058
25059 // sequence tag byte for r
25060 if (sig[index++] !== 0x02) return
25061
25062 // length for r
25063 var rlen = sig[index++]
25064 if (rlen & 0x80) {
25065 lenbyte = rlen - 0x80
25066 if (index + lenbyte > length) return
25067 for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1);
25068 for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index]
25069 }
25070 if (rlen > length - index) return
25071 var rindex = index
25072 index += rlen
25073
25074 // sequence tag byte for s
25075 if (sig[index++] !== 0x02) return
25076
25077 // length for s
25078 var slen = sig[index++]
25079 if (slen & 0x80) {
25080 lenbyte = slen - 0x80
25081 if (index + lenbyte > length) return
25082 for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1);
25083 for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index]
25084 }
25085 if (slen > length - index) return
25086 var sindex = index
25087 index += slen
25088
25089 // ignore leading zeros in r
25090 for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1);
25091 // copy r value
25092 if (rlen > 32) return
25093 var rvalue = sig.slice(rindex, rindex + rlen)
25094 rvalue.copy(r, 32 - rvalue.length)
25095
25096 // ignore leading zeros in s
25097 for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1);
25098 // copy s value
25099 if (slen > 32) return
25100 var svalue = sig.slice(sindex, sindex + slen)
25101 svalue.copy(s, 32 - svalue.length)
25102
25103 return { r: r, s: s }
25104}
25105
25106},{"bip66":20,"safe-buffer":156}],161:[function(require,module,exports){
25107'use strict'
25108var Buffer = require('safe-buffer').Buffer
25109var createHash = require('create-hash')
25110var BN = require('bn.js')
25111var EC = require('elliptic').ec
25112
25113var messages = require('../messages.json')
25114
25115var ec = new EC('secp256k1')
25116var ecparams = ec.curve
25117
25118function loadCompressedPublicKey (first, xBuffer) {
25119 var x = new BN(xBuffer)
25120
25121 // overflow
25122 if (x.cmp(ecparams.p) >= 0) return null
25123 x = x.toRed(ecparams.red)
25124
25125 // compute corresponding Y
25126 var y = x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt()
25127 if ((first === 0x03) !== y.isOdd()) y = y.redNeg()
25128
25129 return ec.keyPair({ pub: { x: x, y: y } })
25130}
25131
25132function loadUncompressedPublicKey (first, xBuffer, yBuffer) {
25133 var x = new BN(xBuffer)
25134 var y = new BN(yBuffer)
25135
25136 // overflow
25137 if (x.cmp(ecparams.p) >= 0 || y.cmp(ecparams.p) >= 0) return null
25138
25139 x = x.toRed(ecparams.red)
25140 y = y.toRed(ecparams.red)
25141
25142 // is odd flag
25143 if ((first === 0x06 || first === 0x07) && y.isOdd() !== (first === 0x07)) return null
25144
25145 // x*x*x + b = y*y
25146 var x3 = x.redSqr().redIMul(x)
25147 if (!y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero()) return null
25148
25149 return ec.keyPair({ pub: { x: x, y: y } })
25150}
25151
25152function loadPublicKey (publicKey) {
25153 var first = publicKey[0]
25154 switch (first) {
25155 case 0x02:
25156 case 0x03:
25157 if (publicKey.length !== 33) return null
25158 return loadCompressedPublicKey(first, publicKey.slice(1, 33))
25159 case 0x04:
25160 case 0x06:
25161 case 0x07:
25162 if (publicKey.length !== 65) return null
25163 return loadUncompressedPublicKey(first, publicKey.slice(1, 33), publicKey.slice(33, 65))
25164 default:
25165 return null
25166 }
25167}
25168
25169exports.privateKeyVerify = function (privateKey) {
25170 var bn = new BN(privateKey)
25171 return bn.cmp(ecparams.n) < 0 && !bn.isZero()
25172}
25173
25174exports.privateKeyExport = function (privateKey, compressed) {
25175 var d = new BN(privateKey)
25176 if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL)
25177
25178 return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true))
25179}
25180
25181exports.privateKeyNegate = function (privateKey) {
25182 var bn = new BN(privateKey)
25183 return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32)
25184}
25185
25186exports.privateKeyModInverse = function (privateKey) {
25187 var bn = new BN(privateKey)
25188 if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID)
25189
25190 return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32)
25191}
25192
25193exports.privateKeyTweakAdd = function (privateKey, tweak) {
25194 var bn = new BN(tweak)
25195 if (bn.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL)
25196
25197 bn.iadd(new BN(privateKey))
25198 if (bn.cmp(ecparams.n) >= 0) bn.isub(ecparams.n)
25199 if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL)
25200
25201 return bn.toArrayLike(Buffer, 'be', 32)
25202}
25203
25204exports.privateKeyTweakMul = function (privateKey, tweak) {
25205 var bn = new BN(tweak)
25206 if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL)
25207
25208 bn.imul(new BN(privateKey))
25209 if (bn.cmp(ecparams.n)) bn = bn.umod(ecparams.n)
25210
25211 return bn.toArrayLike(Buffer, 'be', 32)
25212}
25213
25214exports.publicKeyCreate = function (privateKey, compressed) {
25215 var d = new BN(privateKey)
25216 if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL)
25217
25218 return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true))
25219}
25220
25221exports.publicKeyConvert = function (publicKey, compressed) {
25222 var pair = loadPublicKey(publicKey)
25223 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
25224
25225 return Buffer.from(pair.getPublic(compressed, true))
25226}
25227
25228exports.publicKeyVerify = function (publicKey) {
25229 return loadPublicKey(publicKey) !== null
25230}
25231
25232exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) {
25233 var pair = loadPublicKey(publicKey)
25234 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
25235
25236 tweak = new BN(tweak)
25237 if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL)
25238
25239 return Buffer.from(ecparams.g.mul(tweak).add(pair.pub).encode(true, compressed))
25240}
25241
25242exports.publicKeyTweakMul = function (publicKey, tweak, compressed) {
25243 var pair = loadPublicKey(publicKey)
25244 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
25245
25246 tweak = new BN(tweak)
25247 if (tweak.cmp(ecparams.n) >= 0 || tweak.isZero()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_MUL_FAIL)
25248
25249 return Buffer.from(pair.pub.mul(tweak).encode(true, compressed))
25250}
25251
25252exports.publicKeyCombine = function (publicKeys, compressed) {
25253 var pairs = new Array(publicKeys.length)
25254 for (var i = 0; i < publicKeys.length; ++i) {
25255 pairs[i] = loadPublicKey(publicKeys[i])
25256 if (pairs[i] === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
25257 }
25258
25259 var point = pairs[0].pub
25260 for (var j = 1; j < pairs.length; ++j) point = point.add(pairs[j].pub)
25261 if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_COMBINE_FAIL)
25262
25263 return Buffer.from(point.encode(true, compressed))
25264}
25265
25266exports.signatureNormalize = function (signature) {
25267 var r = new BN(signature.slice(0, 32))
25268 var s = new BN(signature.slice(32, 64))
25269 if (r.cmp(ecparams.n) >= 0 || s.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
25270
25271 var result = Buffer.from(signature)
25272 if (s.cmp(ec.nh) === 1) ecparams.n.sub(s).toArrayLike(Buffer, 'be', 32).copy(result, 32)
25273
25274 return result
25275}
25276
25277exports.signatureExport = function (signature) {
25278 var r = signature.slice(0, 32)
25279 var s = signature.slice(32, 64)
25280 if (new BN(r).cmp(ecparams.n) >= 0 || new BN(s).cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
25281
25282 return { r: r, s: s }
25283}
25284
25285exports.signatureImport = function (sigObj) {
25286 var r = new BN(sigObj.r)
25287 if (r.cmp(ecparams.n) >= 0) r = new BN(0)
25288
25289 var s = new BN(sigObj.s)
25290 if (s.cmp(ecparams.n) >= 0) s = new BN(0)
25291
25292 return Buffer.concat([
25293 r.toArrayLike(Buffer, 'be', 32),
25294 s.toArrayLike(Buffer, 'be', 32)
25295 ])
25296}
25297
25298exports.sign = function (message, privateKey, noncefn, data) {
25299 if (typeof noncefn === 'function') {
25300 var getNonce = noncefn
25301 noncefn = function (counter) {
25302 var nonce = getNonce(message, privateKey, null, data, counter)
25303 if (!Buffer.isBuffer(nonce) || nonce.length !== 32) throw new Error(messages.ECDSA_SIGN_FAIL)
25304
25305 return new BN(nonce)
25306 }
25307 }
25308
25309 var d = new BN(privateKey)
25310 if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.ECDSA_SIGN_FAIL)
25311
25312 var result = ec.sign(message, privateKey, { canonical: true, k: noncefn, pers: data })
25313 return {
25314 signature: Buffer.concat([
25315 result.r.toArrayLike(Buffer, 'be', 32),
25316 result.s.toArrayLike(Buffer, 'be', 32)
25317 ]),
25318 recovery: result.recoveryParam
25319 }
25320}
25321
25322exports.verify = function (message, signature, publicKey) {
25323 var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)}
25324
25325 var sigr = new BN(sigObj.r)
25326 var sigs = new BN(sigObj.s)
25327 if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
25328 if (sigs.cmp(ec.nh) === 1 || sigr.isZero() || sigs.isZero()) return false
25329
25330 var pair = loadPublicKey(publicKey)
25331 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
25332
25333 return ec.verify(message, sigObj, {x: pair.pub.x, y: pair.pub.y})
25334}
25335
25336exports.recover = function (message, signature, recovery, compressed) {
25337 var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)}
25338
25339 var sigr = new BN(sigObj.r)
25340 var sigs = new BN(sigObj.s)
25341 if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
25342
25343 try {
25344 if (sigr.isZero() || sigs.isZero()) throw new Error()
25345
25346 var point = ec.recoverPubKey(message, sigObj, recovery)
25347 return Buffer.from(point.encode(true, compressed))
25348 } catch (err) {
25349 throw new Error(messages.ECDSA_RECOVER_FAIL)
25350 }
25351}
25352
25353exports.ecdh = function (publicKey, privateKey) {
25354 var shared = exports.ecdhUnsafe(publicKey, privateKey, true)
25355 return createHash('sha256').update(shared).digest()
25356}
25357
25358exports.ecdhUnsafe = function (publicKey, privateKey, compressed) {
25359 var pair = loadPublicKey(publicKey)
25360 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
25361
25362 var scalar = new BN(privateKey)
25363 if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) throw new Error(messages.ECDH_FAIL)
25364
25365 return Buffer.from(pair.pub.mul(scalar).encode(true, compressed))
25366}
25367
25368},{"../messages.json":163,"bn.js":21,"create-hash":57,"elliptic":73,"safe-buffer":156}],162:[function(require,module,exports){
25369'use strict'
25370var assert = require('./assert')
25371var der = require('./der')
25372var messages = require('./messages.json')
25373
25374function initCompressedValue (value, defaultValue) {
25375 if (value === undefined) return defaultValue
25376
25377 assert.isBoolean(value, messages.COMPRESSED_TYPE_INVALID)
25378 return value
25379}
25380
25381module.exports = function (secp256k1) {
25382 return {
25383 privateKeyVerify: function (privateKey) {
25384 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25385 return privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)
25386 },
25387
25388 privateKeyExport: function (privateKey, compressed) {
25389 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25390 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25391
25392 compressed = initCompressedValue(compressed, true)
25393 var publicKey = secp256k1.privateKeyExport(privateKey, compressed)
25394
25395 return der.privateKeyExport(privateKey, publicKey, compressed)
25396 },
25397
25398 privateKeyImport: function (privateKey) {
25399 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25400
25401 privateKey = der.privateKeyImport(privateKey)
25402 if (privateKey && privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)) return privateKey
25403
25404 throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL)
25405 },
25406
25407 privateKeyNegate: function (privateKey) {
25408 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25409 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25410
25411 return secp256k1.privateKeyNegate(privateKey)
25412 },
25413
25414 privateKeyModInverse: function (privateKey) {
25415 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25416 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25417
25418 return secp256k1.privateKeyModInverse(privateKey)
25419 },
25420
25421 privateKeyTweakAdd: function (privateKey, tweak) {
25422 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25423 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25424
25425 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
25426 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
25427
25428 return secp256k1.privateKeyTweakAdd(privateKey, tweak)
25429 },
25430
25431 privateKeyTweakMul: function (privateKey, tweak) {
25432 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25433 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25434
25435 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
25436 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
25437
25438 return secp256k1.privateKeyTweakMul(privateKey, tweak)
25439 },
25440
25441 publicKeyCreate: function (privateKey, compressed) {
25442 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25443 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25444
25445 compressed = initCompressedValue(compressed, true)
25446
25447 return secp256k1.publicKeyCreate(privateKey, compressed)
25448 },
25449
25450 publicKeyConvert: function (publicKey, compressed) {
25451 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
25452 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
25453
25454 compressed = initCompressedValue(compressed, true)
25455
25456 return secp256k1.publicKeyConvert(publicKey, compressed)
25457 },
25458
25459 publicKeyVerify: function (publicKey) {
25460 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
25461 return secp256k1.publicKeyVerify(publicKey)
25462 },
25463
25464 publicKeyTweakAdd: function (publicKey, tweak, compressed) {
25465 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
25466 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
25467
25468 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
25469 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
25470
25471 compressed = initCompressedValue(compressed, true)
25472
25473 return secp256k1.publicKeyTweakAdd(publicKey, tweak, compressed)
25474 },
25475
25476 publicKeyTweakMul: function (publicKey, tweak, compressed) {
25477 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
25478 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
25479
25480 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
25481 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
25482
25483 compressed = initCompressedValue(compressed, true)
25484
25485 return secp256k1.publicKeyTweakMul(publicKey, tweak, compressed)
25486 },
25487
25488 publicKeyCombine: function (publicKeys, compressed) {
25489 assert.isArray(publicKeys, messages.EC_PUBLIC_KEYS_TYPE_INVALID)
25490 assert.isLengthGTZero(publicKeys, messages.EC_PUBLIC_KEYS_LENGTH_INVALID)
25491 for (var i = 0; i < publicKeys.length; ++i) {
25492 assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID)
25493 assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
25494 }
25495
25496 compressed = initCompressedValue(compressed, true)
25497
25498 return secp256k1.publicKeyCombine(publicKeys, compressed)
25499 },
25500
25501 signatureNormalize: function (signature) {
25502 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
25503 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
25504
25505 return secp256k1.signatureNormalize(signature)
25506 },
25507
25508 signatureExport: function (signature) {
25509 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
25510 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
25511
25512 var sigObj = secp256k1.signatureExport(signature)
25513 return der.signatureExport(sigObj)
25514 },
25515
25516 signatureImport: function (sig) {
25517 assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID)
25518 assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
25519
25520 var sigObj = der.signatureImport(sig)
25521 if (sigObj) return secp256k1.signatureImport(sigObj)
25522
25523 throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL)
25524 },
25525
25526 signatureImportLax: function (sig) {
25527 assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID)
25528 assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
25529
25530 var sigObj = der.signatureImportLax(sig)
25531 if (sigObj) return secp256k1.signatureImport(sigObj)
25532
25533 throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL)
25534 },
25535
25536 sign: function (message, privateKey, options) {
25537 assert.isBuffer(message, messages.MSG32_TYPE_INVALID)
25538 assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID)
25539
25540 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25541 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25542
25543 var data = null
25544 var noncefn = null
25545 if (options !== undefined) {
25546 assert.isObject(options, messages.OPTIONS_TYPE_INVALID)
25547
25548 if (options.data !== undefined) {
25549 assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID)
25550 assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID)
25551 data = options.data
25552 }
25553
25554 if (options.noncefn !== undefined) {
25555 assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID)
25556 noncefn = options.noncefn
25557 }
25558 }
25559
25560 return secp256k1.sign(message, privateKey, noncefn, data)
25561 },
25562
25563 verify: function (message, signature, publicKey) {
25564 assert.isBuffer(message, messages.MSG32_TYPE_INVALID)
25565 assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID)
25566
25567 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
25568 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
25569
25570 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
25571 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
25572
25573 return secp256k1.verify(message, signature, publicKey)
25574 },
25575
25576 recover: function (message, signature, recovery, compressed) {
25577 assert.isBuffer(message, messages.MSG32_TYPE_INVALID)
25578 assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID)
25579
25580 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
25581 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
25582
25583 assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID)
25584 assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID)
25585
25586 compressed = initCompressedValue(compressed, true)
25587
25588 return secp256k1.recover(message, signature, recovery, compressed)
25589 },
25590
25591 ecdh: function (publicKey, privateKey) {
25592 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
25593 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
25594
25595 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25596 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25597
25598 return secp256k1.ecdh(publicKey, privateKey)
25599 },
25600
25601 ecdhUnsafe: function (publicKey, privateKey, compressed) {
25602 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
25603 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
25604
25605 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
25606 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
25607
25608 compressed = initCompressedValue(compressed, true)
25609
25610 return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed)
25611 }
25612 }
25613}
25614
25615},{"./assert":159,"./der":160,"./messages.json":163}],163:[function(require,module,exports){
25616module.exports={
25617 "COMPRESSED_TYPE_INVALID": "compressed should be a boolean",
25618 "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer",
25619 "EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid",
25620 "EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid",
25621 "EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid",
25622 "EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range",
25623 "EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format",
25624 "EC_PRIVATE_KEY_IMPORT_DER_FAIL": "couldn't import from DER format",
25625 "EC_PUBLIC_KEYS_TYPE_INVALID": "public keys should be an Array",
25626 "EC_PUBLIC_KEYS_LENGTH_INVALID": "public keys Array should have at least 1 element",
25627 "EC_PUBLIC_KEY_TYPE_INVALID": "public key should be a Buffer",
25628 "EC_PUBLIC_KEY_LENGTH_INVALID": "public key length is invalid",
25629 "EC_PUBLIC_KEY_PARSE_FAIL": "the public key could not be parsed or is invalid",
25630 "EC_PUBLIC_KEY_CREATE_FAIL": "private was invalid, try again",
25631 "EC_PUBLIC_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting public key is invalid",
25632 "EC_PUBLIC_KEY_TWEAK_MUL_FAIL": "tweak out of range",
25633 "EC_PUBLIC_KEY_COMBINE_FAIL": "the sum of the public keys is not valid",
25634 "ECDH_FAIL": "scalar was invalid (zero or overflow)",
25635 "ECDSA_SIGNATURE_TYPE_INVALID": "signature should be a Buffer",
25636 "ECDSA_SIGNATURE_LENGTH_INVALID": "signature length is invalid",
25637 "ECDSA_SIGNATURE_PARSE_FAIL": "couldn't parse signature",
25638 "ECDSA_SIGNATURE_PARSE_DER_FAIL": "couldn't parse DER signature",
25639 "ECDSA_SIGNATURE_SERIALIZE_DER_FAIL": "couldn't serialize signature to DER format",
25640 "ECDSA_SIGN_FAIL": "nonce generation function failed or private key is invalid",
25641 "ECDSA_RECOVER_FAIL": "couldn't recover public key from signature",
25642 "MSG32_TYPE_INVALID": "message should be a Buffer",
25643 "MSG32_LENGTH_INVALID": "message length is invalid",
25644 "OPTIONS_TYPE_INVALID": "options should be an Object",
25645 "OPTIONS_DATA_TYPE_INVALID": "options.data should be a Buffer",
25646 "OPTIONS_DATA_LENGTH_INVALID": "options.data length is invalid",
25647 "OPTIONS_NONCEFN_TYPE_INVALID": "options.noncefn should be a Function",
25648 "RECOVERY_ID_TYPE_INVALID": "recovery should be a Number",
25649 "RECOVERY_ID_VALUE_INVALID": "recovery should have value between -1 and 4",
25650 "TWEAK_TYPE_INVALID": "tweak should be a Buffer",
25651 "TWEAK_LENGTH_INVALID": "tweak length is invalid"
25652}
25653
25654},{}],164:[function(require,module,exports){
25655var Buffer = require('safe-buffer').Buffer
25656
25657// prototype class for hash functions
25658function Hash (blockSize, finalSize) {
25659 this._block = Buffer.alloc(blockSize)
25660 this._finalSize = finalSize
25661 this._blockSize = blockSize
25662 this._len = 0
25663}
25664
25665Hash.prototype.update = function (data, enc) {
25666 if (typeof data === 'string') {
25667 enc = enc || 'utf8'
25668 data = Buffer.from(data, enc)
25669 }
25670
25671 var block = this._block
25672 var blockSize = this._blockSize
25673 var length = data.length
25674 var accum = this._len
25675
25676 for (var offset = 0; offset < length;) {
25677 var assigned = accum % blockSize
25678 var remainder = Math.min(length - offset, blockSize - assigned)
25679
25680 for (var i = 0; i < remainder; i++) {
25681 block[assigned + i] = data[offset + i]
25682 }
25683
25684 accum += remainder
25685 offset += remainder
25686
25687 if ((accum % blockSize) === 0) {
25688 this._update(block)
25689 }
25690 }
25691
25692 this._len += length
25693 return this
25694}
25695
25696Hash.prototype.digest = function (enc) {
25697 var rem = this._len % this._blockSize
25698
25699 this._block[rem] = 0x80
25700
25701 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
25702 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
25703 this._block.fill(0, rem + 1)
25704
25705 if (rem >= this._finalSize) {
25706 this._update(this._block)
25707 this._block.fill(0)
25708 }
25709
25710 var bits = this._len * 8
25711
25712 // uint32
25713 if (bits <= 0xffffffff) {
25714 this._block.writeUInt32BE(bits, this._blockSize - 4)
25715
25716 // uint64
25717 } else {
25718 var lowBits = bits & 0xffffffff
25719 var highBits = (bits - lowBits) / 0x100000000
25720
25721 this._block.writeUInt32BE(highBits, this._blockSize - 8)
25722 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
25723 }
25724
25725 this._update(this._block)
25726 var hash = this._hash()
25727
25728 return enc ? hash.toString(enc) : hash
25729}
25730
25731Hash.prototype._update = function () {
25732 throw new Error('_update must be implemented by subclass')
25733}
25734
25735module.exports = Hash
25736
25737},{"safe-buffer":156}],165:[function(require,module,exports){
25738var exports = module.exports = function SHA (algorithm) {
25739 algorithm = algorithm.toLowerCase()
25740
25741 var Algorithm = exports[algorithm]
25742 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
25743
25744 return new Algorithm()
25745}
25746
25747exports.sha = require('./sha')
25748exports.sha1 = require('./sha1')
25749exports.sha224 = require('./sha224')
25750exports.sha256 = require('./sha256')
25751exports.sha384 = require('./sha384')
25752exports.sha512 = require('./sha512')
25753
25754},{"./sha":166,"./sha1":167,"./sha224":168,"./sha256":169,"./sha384":170,"./sha512":171}],166:[function(require,module,exports){
25755/*
25756 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
25757 * in FIPS PUB 180-1
25758 * This source code is derived from sha1.js of the same repository.
25759 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
25760 * operation was added.
25761 */
25762
25763var inherits = require('inherits')
25764var Hash = require('./hash')
25765var Buffer = require('safe-buffer').Buffer
25766
25767var K = [
25768 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
25769]
25770
25771var W = new Array(80)
25772
25773function Sha () {
25774 this.init()
25775 this._w = W
25776
25777 Hash.call(this, 64, 56)
25778}
25779
25780inherits(Sha, Hash)
25781
25782Sha.prototype.init = function () {
25783 this._a = 0x67452301
25784 this._b = 0xefcdab89
25785 this._c = 0x98badcfe
25786 this._d = 0x10325476
25787 this._e = 0xc3d2e1f0
25788
25789 return this
25790}
25791
25792function rotl5 (num) {
25793 return (num << 5) | (num >>> 27)
25794}
25795
25796function rotl30 (num) {
25797 return (num << 30) | (num >>> 2)
25798}
25799
25800function ft (s, b, c, d) {
25801 if (s === 0) return (b & c) | ((~b) & d)
25802 if (s === 2) return (b & c) | (b & d) | (c & d)
25803 return b ^ c ^ d
25804}
25805
25806Sha.prototype._update = function (M) {
25807 var W = this._w
25808
25809 var a = this._a | 0
25810 var b = this._b | 0
25811 var c = this._c | 0
25812 var d = this._d | 0
25813 var e = this._e | 0
25814
25815 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
25816 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
25817
25818 for (var j = 0; j < 80; ++j) {
25819 var s = ~~(j / 20)
25820 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
25821
25822 e = d
25823 d = c
25824 c = rotl30(b)
25825 b = a
25826 a = t
25827 }
25828
25829 this._a = (a + this._a) | 0
25830 this._b = (b + this._b) | 0
25831 this._c = (c + this._c) | 0
25832 this._d = (d + this._d) | 0
25833 this._e = (e + this._e) | 0
25834}
25835
25836Sha.prototype._hash = function () {
25837 var H = Buffer.allocUnsafe(20)
25838
25839 H.writeInt32BE(this._a | 0, 0)
25840 H.writeInt32BE(this._b | 0, 4)
25841 H.writeInt32BE(this._c | 0, 8)
25842 H.writeInt32BE(this._d | 0, 12)
25843 H.writeInt32BE(this._e | 0, 16)
25844
25845 return H
25846}
25847
25848module.exports = Sha
25849
25850},{"./hash":164,"inherits":107,"safe-buffer":156}],167:[function(require,module,exports){
25851/*
25852 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
25853 * in FIPS PUB 180-1
25854 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
25855 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
25856 * Distributed under the BSD License
25857 * See http://pajhome.org.uk/crypt/md5 for details.
25858 */
25859
25860var inherits = require('inherits')
25861var Hash = require('./hash')
25862var Buffer = require('safe-buffer').Buffer
25863
25864var K = [
25865 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
25866]
25867
25868var W = new Array(80)
25869
25870function Sha1 () {
25871 this.init()
25872 this._w = W
25873
25874 Hash.call(this, 64, 56)
25875}
25876
25877inherits(Sha1, Hash)
25878
25879Sha1.prototype.init = function () {
25880 this._a = 0x67452301
25881 this._b = 0xefcdab89
25882 this._c = 0x98badcfe
25883 this._d = 0x10325476
25884 this._e = 0xc3d2e1f0
25885
25886 return this
25887}
25888
25889function rotl1 (num) {
25890 return (num << 1) | (num >>> 31)
25891}
25892
25893function rotl5 (num) {
25894 return (num << 5) | (num >>> 27)
25895}
25896
25897function rotl30 (num) {
25898 return (num << 30) | (num >>> 2)
25899}
25900
25901function ft (s, b, c, d) {
25902 if (s === 0) return (b & c) | ((~b) & d)
25903 if (s === 2) return (b & c) | (b & d) | (c & d)
25904 return b ^ c ^ d
25905}
25906
25907Sha1.prototype._update = function (M) {
25908 var W = this._w
25909
25910 var a = this._a | 0
25911 var b = this._b | 0
25912 var c = this._c | 0
25913 var d = this._d | 0
25914 var e = this._e | 0
25915
25916 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
25917 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
25918
25919 for (var j = 0; j < 80; ++j) {
25920 var s = ~~(j / 20)
25921 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
25922
25923 e = d
25924 d = c
25925 c = rotl30(b)
25926 b = a
25927 a = t
25928 }
25929
25930 this._a = (a + this._a) | 0
25931 this._b = (b + this._b) | 0
25932 this._c = (c + this._c) | 0
25933 this._d = (d + this._d) | 0
25934 this._e = (e + this._e) | 0
25935}
25936
25937Sha1.prototype._hash = function () {
25938 var H = Buffer.allocUnsafe(20)
25939
25940 H.writeInt32BE(this._a | 0, 0)
25941 H.writeInt32BE(this._b | 0, 4)
25942 H.writeInt32BE(this._c | 0, 8)
25943 H.writeInt32BE(this._d | 0, 12)
25944 H.writeInt32BE(this._e | 0, 16)
25945
25946 return H
25947}
25948
25949module.exports = Sha1
25950
25951},{"./hash":164,"inherits":107,"safe-buffer":156}],168:[function(require,module,exports){
25952/**
25953 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
25954 * in FIPS 180-2
25955 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
25956 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
25957 *
25958 */
25959
25960var inherits = require('inherits')
25961var Sha256 = require('./sha256')
25962var Hash = require('./hash')
25963var Buffer = require('safe-buffer').Buffer
25964
25965var W = new Array(64)
25966
25967function Sha224 () {
25968 this.init()
25969
25970 this._w = W // new Array(64)
25971
25972 Hash.call(this, 64, 56)
25973}
25974
25975inherits(Sha224, Sha256)
25976
25977Sha224.prototype.init = function () {
25978 this._a = 0xc1059ed8
25979 this._b = 0x367cd507
25980 this._c = 0x3070dd17
25981 this._d = 0xf70e5939
25982 this._e = 0xffc00b31
25983 this._f = 0x68581511
25984 this._g = 0x64f98fa7
25985 this._h = 0xbefa4fa4
25986
25987 return this
25988}
25989
25990Sha224.prototype._hash = function () {
25991 var H = Buffer.allocUnsafe(28)
25992
25993 H.writeInt32BE(this._a, 0)
25994 H.writeInt32BE(this._b, 4)
25995 H.writeInt32BE(this._c, 8)
25996 H.writeInt32BE(this._d, 12)
25997 H.writeInt32BE(this._e, 16)
25998 H.writeInt32BE(this._f, 20)
25999 H.writeInt32BE(this._g, 24)
26000
26001 return H
26002}
26003
26004module.exports = Sha224
26005
26006},{"./hash":164,"./sha256":169,"inherits":107,"safe-buffer":156}],169:[function(require,module,exports){
26007/**
26008 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
26009 * in FIPS 180-2
26010 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
26011 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
26012 *
26013 */
26014
26015var inherits = require('inherits')
26016var Hash = require('./hash')
26017var Buffer = require('safe-buffer').Buffer
26018
26019var K = [
26020 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
26021 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
26022 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
26023 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
26024 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
26025 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
26026 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
26027 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
26028 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
26029 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
26030 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
26031 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
26032 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
26033 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
26034 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
26035 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
26036]
26037
26038var W = new Array(64)
26039
26040function Sha256 () {
26041 this.init()
26042
26043 this._w = W // new Array(64)
26044
26045 Hash.call(this, 64, 56)
26046}
26047
26048inherits(Sha256, Hash)
26049
26050Sha256.prototype.init = function () {
26051 this._a = 0x6a09e667
26052 this._b = 0xbb67ae85
26053 this._c = 0x3c6ef372
26054 this._d = 0xa54ff53a
26055 this._e = 0x510e527f
26056 this._f = 0x9b05688c
26057 this._g = 0x1f83d9ab
26058 this._h = 0x5be0cd19
26059
26060 return this
26061}
26062
26063function ch (x, y, z) {
26064 return z ^ (x & (y ^ z))
26065}
26066
26067function maj (x, y, z) {
26068 return (x & y) | (z & (x | y))
26069}
26070
26071function sigma0 (x) {
26072 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
26073}
26074
26075function sigma1 (x) {
26076 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
26077}
26078
26079function gamma0 (x) {
26080 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
26081}
26082
26083function gamma1 (x) {
26084 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
26085}
26086
26087Sha256.prototype._update = function (M) {
26088 var W = this._w
26089
26090 var a = this._a | 0
26091 var b = this._b | 0
26092 var c = this._c | 0
26093 var d = this._d | 0
26094 var e = this._e | 0
26095 var f = this._f | 0
26096 var g = this._g | 0
26097 var h = this._h | 0
26098
26099 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
26100 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
26101
26102 for (var j = 0; j < 64; ++j) {
26103 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
26104 var T2 = (sigma0(a) + maj(a, b, c)) | 0
26105
26106 h = g
26107 g = f
26108 f = e
26109 e = (d + T1) | 0
26110 d = c
26111 c = b
26112 b = a
26113 a = (T1 + T2) | 0
26114 }
26115
26116 this._a = (a + this._a) | 0
26117 this._b = (b + this._b) | 0
26118 this._c = (c + this._c) | 0
26119 this._d = (d + this._d) | 0
26120 this._e = (e + this._e) | 0
26121 this._f = (f + this._f) | 0
26122 this._g = (g + this._g) | 0
26123 this._h = (h + this._h) | 0
26124}
26125
26126Sha256.prototype._hash = function () {
26127 var H = Buffer.allocUnsafe(32)
26128
26129 H.writeInt32BE(this._a, 0)
26130 H.writeInt32BE(this._b, 4)
26131 H.writeInt32BE(this._c, 8)
26132 H.writeInt32BE(this._d, 12)
26133 H.writeInt32BE(this._e, 16)
26134 H.writeInt32BE(this._f, 20)
26135 H.writeInt32BE(this._g, 24)
26136 H.writeInt32BE(this._h, 28)
26137
26138 return H
26139}
26140
26141module.exports = Sha256
26142
26143},{"./hash":164,"inherits":107,"safe-buffer":156}],170:[function(require,module,exports){
26144var inherits = require('inherits')
26145var SHA512 = require('./sha512')
26146var Hash = require('./hash')
26147var Buffer = require('safe-buffer').Buffer
26148
26149var W = new Array(160)
26150
26151function Sha384 () {
26152 this.init()
26153 this._w = W
26154
26155 Hash.call(this, 128, 112)
26156}
26157
26158inherits(Sha384, SHA512)
26159
26160Sha384.prototype.init = function () {
26161 this._ah = 0xcbbb9d5d
26162 this._bh = 0x629a292a
26163 this._ch = 0x9159015a
26164 this._dh = 0x152fecd8
26165 this._eh = 0x67332667
26166 this._fh = 0x8eb44a87
26167 this._gh = 0xdb0c2e0d
26168 this._hh = 0x47b5481d
26169
26170 this._al = 0xc1059ed8
26171 this._bl = 0x367cd507
26172 this._cl = 0x3070dd17
26173 this._dl = 0xf70e5939
26174 this._el = 0xffc00b31
26175 this._fl = 0x68581511
26176 this._gl = 0x64f98fa7
26177 this._hl = 0xbefa4fa4
26178
26179 return this
26180}
26181
26182Sha384.prototype._hash = function () {
26183 var H = Buffer.allocUnsafe(48)
26184
26185 function writeInt64BE (h, l, offset) {
26186 H.writeInt32BE(h, offset)
26187 H.writeInt32BE(l, offset + 4)
26188 }
26189
26190 writeInt64BE(this._ah, this._al, 0)
26191 writeInt64BE(this._bh, this._bl, 8)
26192 writeInt64BE(this._ch, this._cl, 16)
26193 writeInt64BE(this._dh, this._dl, 24)
26194 writeInt64BE(this._eh, this._el, 32)
26195 writeInt64BE(this._fh, this._fl, 40)
26196
26197 return H
26198}
26199
26200module.exports = Sha384
26201
26202},{"./hash":164,"./sha512":171,"inherits":107,"safe-buffer":156}],171:[function(require,module,exports){
26203var inherits = require('inherits')
26204var Hash = require('./hash')
26205var Buffer = require('safe-buffer').Buffer
26206
26207var K = [
26208 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
26209 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
26210 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
26211 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
26212 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
26213 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
26214 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
26215 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
26216 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
26217 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
26218 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
26219 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
26220 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
26221 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
26222 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
26223 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
26224 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
26225 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
26226 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
26227 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
26228 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
26229 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
26230 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
26231 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
26232 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
26233 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
26234 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
26235 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
26236 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
26237 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
26238 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
26239 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
26240 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
26241 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
26242 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
26243 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
26244 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
26245 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
26246 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
26247 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
26248]
26249
26250var W = new Array(160)
26251
26252function Sha512 () {
26253 this.init()
26254 this._w = W
26255
26256 Hash.call(this, 128, 112)
26257}
26258
26259inherits(Sha512, Hash)
26260
26261Sha512.prototype.init = function () {
26262 this._ah = 0x6a09e667
26263 this._bh = 0xbb67ae85
26264 this._ch = 0x3c6ef372
26265 this._dh = 0xa54ff53a
26266 this._eh = 0x510e527f
26267 this._fh = 0x9b05688c
26268 this._gh = 0x1f83d9ab
26269 this._hh = 0x5be0cd19
26270
26271 this._al = 0xf3bcc908
26272 this._bl = 0x84caa73b
26273 this._cl = 0xfe94f82b
26274 this._dl = 0x5f1d36f1
26275 this._el = 0xade682d1
26276 this._fl = 0x2b3e6c1f
26277 this._gl = 0xfb41bd6b
26278 this._hl = 0x137e2179
26279
26280 return this
26281}
26282
26283function Ch (x, y, z) {
26284 return z ^ (x & (y ^ z))
26285}
26286
26287function maj (x, y, z) {
26288 return (x & y) | (z & (x | y))
26289}
26290
26291function sigma0 (x, xl) {
26292 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
26293}
26294
26295function sigma1 (x, xl) {
26296 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
26297}
26298
26299function Gamma0 (x, xl) {
26300 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
26301}
26302
26303function Gamma0l (x, xl) {
26304 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
26305}
26306
26307function Gamma1 (x, xl) {
26308 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
26309}
26310
26311function Gamma1l (x, xl) {
26312 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
26313}
26314
26315function getCarry (a, b) {
26316 return (a >>> 0) < (b >>> 0) ? 1 : 0
26317}
26318
26319Sha512.prototype._update = function (M) {
26320 var W = this._w
26321
26322 var ah = this._ah | 0
26323 var bh = this._bh | 0
26324 var ch = this._ch | 0
26325 var dh = this._dh | 0
26326 var eh = this._eh | 0
26327 var fh = this._fh | 0
26328 var gh = this._gh | 0
26329 var hh = this._hh | 0
26330
26331 var al = this._al | 0
26332 var bl = this._bl | 0
26333 var cl = this._cl | 0
26334 var dl = this._dl | 0
26335 var el = this._el | 0
26336 var fl = this._fl | 0
26337 var gl = this._gl | 0
26338 var hl = this._hl | 0
26339
26340 for (var i = 0; i < 32; i += 2) {
26341 W[i] = M.readInt32BE(i * 4)
26342 W[i + 1] = M.readInt32BE(i * 4 + 4)
26343 }
26344 for (; i < 160; i += 2) {
26345 var xh = W[i - 15 * 2]
26346 var xl = W[i - 15 * 2 + 1]
26347 var gamma0 = Gamma0(xh, xl)
26348 var gamma0l = Gamma0l(xl, xh)
26349
26350 xh = W[i - 2 * 2]
26351 xl = W[i - 2 * 2 + 1]
26352 var gamma1 = Gamma1(xh, xl)
26353 var gamma1l = Gamma1l(xl, xh)
26354
26355 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
26356 var Wi7h = W[i - 7 * 2]
26357 var Wi7l = W[i - 7 * 2 + 1]
26358
26359 var Wi16h = W[i - 16 * 2]
26360 var Wi16l = W[i - 16 * 2 + 1]
26361
26362 var Wil = (gamma0l + Wi7l) | 0
26363 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
26364 Wil = (Wil + gamma1l) | 0
26365 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
26366 Wil = (Wil + Wi16l) | 0
26367 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
26368
26369 W[i] = Wih
26370 W[i + 1] = Wil
26371 }
26372
26373 for (var j = 0; j < 160; j += 2) {
26374 Wih = W[j]
26375 Wil = W[j + 1]
26376
26377 var majh = maj(ah, bh, ch)
26378 var majl = maj(al, bl, cl)
26379
26380 var sigma0h = sigma0(ah, al)
26381 var sigma0l = sigma0(al, ah)
26382 var sigma1h = sigma1(eh, el)
26383 var sigma1l = sigma1(el, eh)
26384
26385 // t1 = h + sigma1 + ch + K[j] + W[j]
26386 var Kih = K[j]
26387 var Kil = K[j + 1]
26388
26389 var chh = Ch(eh, fh, gh)
26390 var chl = Ch(el, fl, gl)
26391
26392 var t1l = (hl + sigma1l) | 0
26393 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
26394 t1l = (t1l + chl) | 0
26395 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
26396 t1l = (t1l + Kil) | 0
26397 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
26398 t1l = (t1l + Wil) | 0
26399 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
26400
26401 // t2 = sigma0 + maj
26402 var t2l = (sigma0l + majl) | 0
26403 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
26404
26405 hh = gh
26406 hl = gl
26407 gh = fh
26408 gl = fl
26409 fh = eh
26410 fl = el
26411 el = (dl + t1l) | 0
26412 eh = (dh + t1h + getCarry(el, dl)) | 0
26413 dh = ch
26414 dl = cl
26415 ch = bh
26416 cl = bl
26417 bh = ah
26418 bl = al
26419 al = (t1l + t2l) | 0
26420 ah = (t1h + t2h + getCarry(al, t1l)) | 0
26421 }
26422
26423 this._al = (this._al + al) | 0
26424 this._bl = (this._bl + bl) | 0
26425 this._cl = (this._cl + cl) | 0
26426 this._dl = (this._dl + dl) | 0
26427 this._el = (this._el + el) | 0
26428 this._fl = (this._fl + fl) | 0
26429 this._gl = (this._gl + gl) | 0
26430 this._hl = (this._hl + hl) | 0
26431
26432 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
26433 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
26434 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
26435 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
26436 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
26437 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
26438 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
26439 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
26440}
26441
26442Sha512.prototype._hash = function () {
26443 var H = Buffer.allocUnsafe(64)
26444
26445 function writeInt64BE (h, l, offset) {
26446 H.writeInt32BE(h, offset)
26447 H.writeInt32BE(l, offset + 4)
26448 }
26449
26450 writeInt64BE(this._ah, this._al, 0)
26451 writeInt64BE(this._bh, this._bl, 8)
26452 writeInt64BE(this._ch, this._cl, 16)
26453 writeInt64BE(this._dh, this._dl, 24)
26454 writeInt64BE(this._eh, this._el, 32)
26455 writeInt64BE(this._fh, this._fl, 40)
26456 writeInt64BE(this._gh, this._gl, 48)
26457 writeInt64BE(this._hh, this._hl, 56)
26458
26459 return H
26460}
26461
26462module.exports = Sha512
26463
26464},{"./hash":164,"inherits":107,"safe-buffer":156}],172:[function(require,module,exports){
26465// Copyright Joyent, Inc. and other Node contributors.
26466//
26467// Permission is hereby granted, free of charge, to any person obtaining a
26468// copy of this software and associated documentation files (the
26469// "Software"), to deal in the Software without restriction, including
26470// without limitation the rights to use, copy, modify, merge, publish,
26471// distribute, sublicense, and/or sell copies of the Software, and to permit
26472// persons to whom the Software is furnished to do so, subject to the
26473// following conditions:
26474//
26475// The above copyright notice and this permission notice shall be included
26476// in all copies or substantial portions of the Software.
26477//
26478// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26479// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26480// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26481// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26482// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26483// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26484// USE OR OTHER DEALINGS IN THE SOFTWARE.
26485
26486module.exports = Stream;
26487
26488var EE = require('events').EventEmitter;
26489var inherits = require('inherits');
26490
26491inherits(Stream, EE);
26492Stream.Readable = require('readable-stream/readable.js');
26493Stream.Writable = require('readable-stream/writable.js');
26494Stream.Duplex = require('readable-stream/duplex.js');
26495Stream.Transform = require('readable-stream/transform.js');
26496Stream.PassThrough = require('readable-stream/passthrough.js');
26497
26498// Backwards-compat with node 0.4.x
26499Stream.Stream = Stream;
26500
26501
26502
26503// old-style streams. Note that the pipe method (the only relevant
26504// part of this class) is overridden in the Readable class.
26505
26506function Stream() {
26507 EE.call(this);
26508}
26509
26510Stream.prototype.pipe = function(dest, options) {
26511 var source = this;
26512
26513 function ondata(chunk) {
26514 if (dest.writable) {
26515 if (false === dest.write(chunk) && source.pause) {
26516 source.pause();
26517 }
26518 }
26519 }
26520
26521 source.on('data', ondata);
26522
26523 function ondrain() {
26524 if (source.readable && source.resume) {
26525 source.resume();
26526 }
26527 }
26528
26529 dest.on('drain', ondrain);
26530
26531 // If the 'end' option is not supplied, dest.end() will be called when
26532 // source gets the 'end' or 'close' events. Only dest.end() once.
26533 if (!dest._isStdio && (!options || options.end !== false)) {
26534 source.on('end', onend);
26535 source.on('close', onclose);
26536 }
26537
26538 var didOnEnd = false;
26539 function onend() {
26540 if (didOnEnd) return;
26541 didOnEnd = true;
26542
26543 dest.end();
26544 }
26545
26546
26547 function onclose() {
26548 if (didOnEnd) return;
26549 didOnEnd = true;
26550
26551 if (typeof dest.destroy === 'function') dest.destroy();
26552 }
26553
26554 // don't leave dangling pipes when there are errors.
26555 function onerror(er) {
26556 cleanup();
26557 if (EE.listenerCount(this, 'error') === 0) {
26558 throw er; // Unhandled stream error in pipe.
26559 }
26560 }
26561
26562 source.on('error', onerror);
26563 dest.on('error', onerror);
26564
26565 // remove all the event listeners that were added.
26566 function cleanup() {
26567 source.removeListener('data', ondata);
26568 dest.removeListener('drain', ondrain);
26569
26570 source.removeListener('end', onend);
26571 source.removeListener('close', onclose);
26572
26573 source.removeListener('error', onerror);
26574 dest.removeListener('error', onerror);
26575
26576 source.removeListener('end', cleanup);
26577 source.removeListener('close', cleanup);
26578
26579 dest.removeListener('close', cleanup);
26580 }
26581
26582 source.on('end', cleanup);
26583 source.on('close', cleanup);
26584
26585 dest.on('close', cleanup);
26586
26587 dest.emit('pipe', source);
26588
26589 // Allow for unix-like usage: A.pipe(B).pipe(C)
26590 return dest;
26591};
26592
26593},{"events":89,"inherits":107,"readable-stream/duplex.js":142,"readable-stream/passthrough.js":151,"readable-stream/readable.js":152,"readable-stream/transform.js":153,"readable-stream/writable.js":154}],173:[function(require,module,exports){
26594'use strict';
26595
26596var Buffer = require('safe-buffer').Buffer;
26597
26598var isEncoding = Buffer.isEncoding || function (encoding) {
26599 encoding = '' + encoding;
26600 switch (encoding && encoding.toLowerCase()) {
26601 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':
26602 return true;
26603 default:
26604 return false;
26605 }
26606};
26607
26608function _normalizeEncoding(enc) {
26609 if (!enc) return 'utf8';
26610 var retried;
26611 while (true) {
26612 switch (enc) {
26613 case 'utf8':
26614 case 'utf-8':
26615 return 'utf8';
26616 case 'ucs2':
26617 case 'ucs-2':
26618 case 'utf16le':
26619 case 'utf-16le':
26620 return 'utf16le';
26621 case 'latin1':
26622 case 'binary':
26623 return 'latin1';
26624 case 'base64':
26625 case 'ascii':
26626 case 'hex':
26627 return enc;
26628 default:
26629 if (retried) return; // undefined
26630 enc = ('' + enc).toLowerCase();
26631 retried = true;
26632 }
26633 }
26634};
26635
26636// Do not cache `Buffer.isEncoding` when checking encoding names as some
26637// modules monkey-patch it to support additional encodings
26638function normalizeEncoding(enc) {
26639 var nenc = _normalizeEncoding(enc);
26640 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
26641 return nenc || enc;
26642}
26643
26644// StringDecoder provides an interface for efficiently splitting a series of
26645// buffers into a series of JS strings without breaking apart multi-byte
26646// characters.
26647exports.StringDecoder = StringDecoder;
26648function StringDecoder(encoding) {
26649 this.encoding = normalizeEncoding(encoding);
26650 var nb;
26651 switch (this.encoding) {
26652 case 'utf16le':
26653 this.text = utf16Text;
26654 this.end = utf16End;
26655 nb = 4;
26656 break;
26657 case 'utf8':
26658 this.fillLast = utf8FillLast;
26659 nb = 4;
26660 break;
26661 case 'base64':
26662 this.text = base64Text;
26663 this.end = base64End;
26664 nb = 3;
26665 break;
26666 default:
26667 this.write = simpleWrite;
26668 this.end = simpleEnd;
26669 return;
26670 }
26671 this.lastNeed = 0;
26672 this.lastTotal = 0;
26673 this.lastChar = Buffer.allocUnsafe(nb);
26674}
26675
26676StringDecoder.prototype.write = function (buf) {
26677 if (buf.length === 0) return '';
26678 var r;
26679 var i;
26680 if (this.lastNeed) {
26681 r = this.fillLast(buf);
26682 if (r === undefined) return '';
26683 i = this.lastNeed;
26684 this.lastNeed = 0;
26685 } else {
26686 i = 0;
26687 }
26688 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
26689 return r || '';
26690};
26691
26692StringDecoder.prototype.end = utf8End;
26693
26694// Returns only complete characters in a Buffer
26695StringDecoder.prototype.text = utf8Text;
26696
26697// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
26698StringDecoder.prototype.fillLast = function (buf) {
26699 if (this.lastNeed <= buf.length) {
26700 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
26701 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
26702 }
26703 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
26704 this.lastNeed -= buf.length;
26705};
26706
26707// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
26708// continuation byte.
26709function utf8CheckByte(byte) {
26710 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;
26711 return -1;
26712}
26713
26714// Checks at most 3 bytes at the end of a Buffer in order to detect an
26715// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
26716// needed to complete the UTF-8 character (if applicable) are returned.
26717function utf8CheckIncomplete(self, buf, i) {
26718 var j = buf.length - 1;
26719 if (j < i) return 0;
26720 var nb = utf8CheckByte(buf[j]);
26721 if (nb >= 0) {
26722 if (nb > 0) self.lastNeed = nb - 1;
26723 return nb;
26724 }
26725 if (--j < i) return 0;
26726 nb = utf8CheckByte(buf[j]);
26727 if (nb >= 0) {
26728 if (nb > 0) self.lastNeed = nb - 2;
26729 return nb;
26730 }
26731 if (--j < i) return 0;
26732 nb = utf8CheckByte(buf[j]);
26733 if (nb >= 0) {
26734 if (nb > 0) {
26735 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
26736 }
26737 return nb;
26738 }
26739 return 0;
26740}
26741
26742// Validates as many continuation bytes for a multi-byte UTF-8 character as
26743// needed or are available. If we see a non-continuation byte where we expect
26744// one, we "replace" the validated continuation bytes we've seen so far with
26745// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
26746// behavior. The continuation byte check is included three times in the case
26747// where all of the continuation bytes for a character exist in the same buffer.
26748// It is also done this way as a slight performance increase instead of using a
26749// loop.
26750function utf8CheckExtraBytes(self, buf, p) {
26751 if ((buf[0] & 0xC0) !== 0x80) {
26752 self.lastNeed = 0;
26753 return '\ufffd'.repeat(p);
26754 }
26755 if (self.lastNeed > 1 && buf.length > 1) {
26756 if ((buf[1] & 0xC0) !== 0x80) {
26757 self.lastNeed = 1;
26758 return '\ufffd'.repeat(p + 1);
26759 }
26760 if (self.lastNeed > 2 && buf.length > 2) {
26761 if ((buf[2] & 0xC0) !== 0x80) {
26762 self.lastNeed = 2;
26763 return '\ufffd'.repeat(p + 2);
26764 }
26765 }
26766 }
26767}
26768
26769// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
26770function utf8FillLast(buf) {
26771 var p = this.lastTotal - this.lastNeed;
26772 var r = utf8CheckExtraBytes(this, buf, p);
26773 if (r !== undefined) return r;
26774 if (this.lastNeed <= buf.length) {
26775 buf.copy(this.lastChar, p, 0, this.lastNeed);
26776 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
26777 }
26778 buf.copy(this.lastChar, p, 0, buf.length);
26779 this.lastNeed -= buf.length;
26780}
26781
26782// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
26783// partial character, the character's bytes are buffered until the required
26784// number of bytes are available.
26785function utf8Text(buf, i) {
26786 var total = utf8CheckIncomplete(this, buf, i);
26787 if (!this.lastNeed) return buf.toString('utf8', i);
26788 this.lastTotal = total;
26789 var end = buf.length - (total - this.lastNeed);
26790 buf.copy(this.lastChar, 0, end);
26791 return buf.toString('utf8', i, end);
26792}
26793
26794// For UTF-8, a replacement character for each buffered byte of a (partial)
26795// character needs to be added to the output.
26796function utf8End(buf) {
26797 var r = buf && buf.length ? this.write(buf) : '';
26798 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
26799 return r;
26800}
26801
26802// UTF-16LE typically needs two bytes per character, but even if we have an even
26803// number of bytes available, we need to check if we end on a leading/high
26804// surrogate. In that case, we need to wait for the next two bytes in order to
26805// decode the last character properly.
26806function utf16Text(buf, i) {
26807 if ((buf.length - i) % 2 === 0) {
26808 var r = buf.toString('utf16le', i);
26809 if (r) {
26810 var c = r.charCodeAt(r.length - 1);
26811 if (c >= 0xD800 && c <= 0xDBFF) {
26812 this.lastNeed = 2;
26813 this.lastTotal = 4;
26814 this.lastChar[0] = buf[buf.length - 2];
26815 this.lastChar[1] = buf[buf.length - 1];
26816 return r.slice(0, -1);
26817 }
26818 }
26819 return r;
26820 }
26821 this.lastNeed = 1;
26822 this.lastTotal = 2;
26823 this.lastChar[0] = buf[buf.length - 1];
26824 return buf.toString('utf16le', i, buf.length - 1);
26825}
26826
26827// For UTF-16LE we do not explicitly append special replacement characters if we
26828// end on a partial character, we simply let v8 handle that.
26829function utf16End(buf) {
26830 var r = buf && buf.length ? this.write(buf) : '';
26831 if (this.lastNeed) {
26832 var end = this.lastTotal - this.lastNeed;
26833 return r + this.lastChar.toString('utf16le', 0, end);
26834 }
26835 return r;
26836}
26837
26838function base64Text(buf, i) {
26839 var n = (buf.length - i) % 3;
26840 if (n === 0) return buf.toString('base64', i);
26841 this.lastNeed = 3 - n;
26842 this.lastTotal = 3;
26843 if (n === 1) {
26844 this.lastChar[0] = buf[buf.length - 1];
26845 } else {
26846 this.lastChar[0] = buf[buf.length - 2];
26847 this.lastChar[1] = buf[buf.length - 1];
26848 }
26849 return buf.toString('base64', i, buf.length - n);
26850}
26851
26852function base64End(buf) {
26853 var r = buf && buf.length ? this.write(buf) : '';
26854 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
26855 return r;
26856}
26857
26858// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
26859function simpleWrite(buf) {
26860 return buf.toString(this.encoding);
26861}
26862
26863function simpleEnd(buf) {
26864 return buf && buf.length ? this.write(buf) : '';
26865}
26866},{"safe-buffer":156}],174:[function(require,module,exports){
26867(function (global){
26868
26869/**
26870 * Module exports.
26871 */
26872
26873module.exports = deprecate;
26874
26875/**
26876 * Mark that a method should not be used.
26877 * Returns a modified function which warns once by default.
26878 *
26879 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
26880 *
26881 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
26882 * will throw an Error when invoked.
26883 *
26884 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
26885 * will invoke `console.trace()` instead of `console.error()`.
26886 *
26887 * @param {Function} fn - the function to deprecate
26888 * @param {String} msg - the string to print to the console when `fn` is invoked
26889 * @returns {Function} a new "deprecated" version of `fn`
26890 * @api public
26891 */
26892
26893function deprecate (fn, msg) {
26894 if (config('noDeprecation')) {
26895 return fn;
26896 }
26897
26898 var warned = false;
26899 function deprecated() {
26900 if (!warned) {
26901 if (config('throwDeprecation')) {
26902 throw new Error(msg);
26903 } else if (config('traceDeprecation')) {
26904 console.trace(msg);
26905 } else {
26906 console.warn(msg);
26907 }
26908 warned = true;
26909 }
26910 return fn.apply(this, arguments);
26911 }
26912
26913 return deprecated;
26914}
26915
26916/**
26917 * Checks `localStorage` for boolean values for the given `name`.
26918 *
26919 * @param {String} name
26920 * @returns {Boolean}
26921 * @api private
26922 */
26923
26924function config (name) {
26925 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
26926 try {
26927 if (!global.localStorage) return false;
26928 } catch (_) {
26929 return false;
26930 }
26931 var val = global.localStorage[name];
26932 if (null == val) return false;
26933 return String(val).toLowerCase() === 'true';
26934}
26935
26936}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26937},{}],175:[function(require,module,exports){
26938var v1 = require('./v1');
26939var v4 = require('./v4');
26940
26941var uuid = v4;
26942uuid.v1 = v1;
26943uuid.v4 = v4;
26944
26945module.exports = uuid;
26946
26947},{"./v1":178,"./v4":179}],176:[function(require,module,exports){
26948/**
26949 * Convert array of 16 byte values to UUID string format of the form:
26950 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
26951 */
26952var byteToHex = [];
26953for (var i = 0; i < 256; ++i) {
26954 byteToHex[i] = (i + 0x100).toString(16).substr(1);
26955}
26956
26957function bytesToUuid(buf, offset) {
26958 var i = offset || 0;
26959 var bth = byteToHex;
26960 return bth[buf[i++]] + bth[buf[i++]] +
26961 bth[buf[i++]] + bth[buf[i++]] + '-' +
26962 bth[buf[i++]] + bth[buf[i++]] + '-' +
26963 bth[buf[i++]] + bth[buf[i++]] + '-' +
26964 bth[buf[i++]] + bth[buf[i++]] + '-' +
26965 bth[buf[i++]] + bth[buf[i++]] +
26966 bth[buf[i++]] + bth[buf[i++]] +
26967 bth[buf[i++]] + bth[buf[i++]];
26968}
26969
26970module.exports = bytesToUuid;
26971
26972},{}],177:[function(require,module,exports){
26973(function (global){
26974// Unique ID creation requires a high quality random # generator. In the
26975// browser this is a little complicated due to unknown quality of Math.random()
26976// and inconsistent support for the `crypto` API. We do the best we can via
26977// feature-detection
26978var rng;
26979
26980var crypto = global.crypto || global.msCrypto; // for IE 11
26981if (crypto && crypto.getRandomValues) {
26982 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
26983 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
26984 rng = function whatwgRNG() {
26985 crypto.getRandomValues(rnds8);
26986 return rnds8;
26987 };
26988}
26989
26990if (!rng) {
26991 // Math.random()-based (RNG)
26992 //
26993 // If all else fails, use Math.random(). It's fast, but is of unspecified
26994 // quality.
26995 var rnds = new Array(16);
26996 rng = function() {
26997 for (var i = 0, r; i < 16; i++) {
26998 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
26999 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
27000 }
27001
27002 return rnds;
27003 };
27004}
27005
27006module.exports = rng;
27007
27008}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
27009},{}],178:[function(require,module,exports){
27010var rng = require('./lib/rng');
27011var bytesToUuid = require('./lib/bytesToUuid');
27012
27013// **`v1()` - Generate time-based UUID**
27014//
27015// Inspired by https://github.com/LiosK/UUID.js
27016// and http://docs.python.org/library/uuid.html
27017
27018// random #'s we need to init node and clockseq
27019var _seedBytes = rng();
27020
27021// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
27022var _nodeId = [
27023 _seedBytes[0] | 0x01,
27024 _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
27025];
27026
27027// Per 4.2.2, randomize (14 bit) clockseq
27028var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
27029
27030// Previous uuid creation time
27031var _lastMSecs = 0, _lastNSecs = 0;
27032
27033// See https://github.com/broofa/node-uuid for API details
27034function v1(options, buf, offset) {
27035 var i = buf && offset || 0;
27036 var b = buf || [];
27037
27038 options = options || {};
27039
27040 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
27041
27042 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
27043 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
27044 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
27045 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
27046 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
27047
27048 // Per 4.2.1.2, use count of uuid's generated during the current clock
27049 // cycle to simulate higher resolution clock
27050 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
27051
27052 // Time since last uuid creation (in msecs)
27053 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
27054
27055 // Per 4.2.1.2, Bump clockseq on clock regression
27056 if (dt < 0 && options.clockseq === undefined) {
27057 clockseq = clockseq + 1 & 0x3fff;
27058 }
27059
27060 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
27061 // time interval
27062 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
27063 nsecs = 0;
27064 }
27065
27066 // Per 4.2.1.2 Throw error if too many uuids are requested
27067 if (nsecs >= 10000) {
27068 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
27069 }
27070
27071 _lastMSecs = msecs;
27072 _lastNSecs = nsecs;
27073 _clockseq = clockseq;
27074
27075 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
27076 msecs += 12219292800000;
27077
27078 // `time_low`
27079 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
27080 b[i++] = tl >>> 24 & 0xff;
27081 b[i++] = tl >>> 16 & 0xff;
27082 b[i++] = tl >>> 8 & 0xff;
27083 b[i++] = tl & 0xff;
27084
27085 // `time_mid`
27086 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
27087 b[i++] = tmh >>> 8 & 0xff;
27088 b[i++] = tmh & 0xff;
27089
27090 // `time_high_and_version`
27091 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
27092 b[i++] = tmh >>> 16 & 0xff;
27093
27094 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
27095 b[i++] = clockseq >>> 8 | 0x80;
27096
27097 // `clock_seq_low`
27098 b[i++] = clockseq & 0xff;
27099
27100 // `node`
27101 var node = options.node || _nodeId;
27102 for (var n = 0; n < 6; ++n) {
27103 b[i + n] = node[n];
27104 }
27105
27106 return buf ? buf : bytesToUuid(b);
27107}
27108
27109module.exports = v1;
27110
27111},{"./lib/bytesToUuid":176,"./lib/rng":177}],179:[function(require,module,exports){
27112var rng = require('./lib/rng');
27113var bytesToUuid = require('./lib/bytesToUuid');
27114
27115function v4(options, buf, offset) {
27116 var i = buf && offset || 0;
27117
27118 if (typeof(options) == 'string') {
27119 buf = options == 'binary' ? new Array(16) : null;
27120 options = null;
27121 }
27122 options = options || {};
27123
27124 var rnds = options.random || (options.rng || rng)();
27125
27126 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
27127 rnds[6] = (rnds[6] & 0x0f) | 0x40;
27128 rnds[8] = (rnds[8] & 0x3f) | 0x80;
27129
27130 // Copy bytes to buffer, if provided
27131 if (buf) {
27132 for (var ii = 0; ii < 16; ++ii) {
27133 buf[i + ii] = rnds[ii];
27134 }
27135 }
27136
27137 return buf || bytesToUuid(rnds);
27138}
27139
27140module.exports = v4;
27141
27142},{"./lib/bytesToUuid":176,"./lib/rng":177}],180:[function(require,module,exports){
27143var indexOf = require('indexof');
27144
27145var Object_keys = function (obj) {
27146 if (Object.keys) return Object.keys(obj)
27147 else {
27148 var res = [];
27149 for (var key in obj) res.push(key)
27150 return res;
27151 }
27152};
27153
27154var forEach = function (xs, fn) {
27155 if (xs.forEach) return xs.forEach(fn)
27156 else for (var i = 0; i < xs.length; i++) {
27157 fn(xs[i], i, xs);
27158 }
27159};
27160
27161var defineProp = (function() {
27162 try {
27163 Object.defineProperty({}, '_', {});
27164 return function(obj, name, value) {
27165 Object.defineProperty(obj, name, {
27166 writable: true,
27167 enumerable: false,
27168 configurable: true,
27169 value: value
27170 })
27171 };
27172 } catch(e) {
27173 return function(obj, name, value) {
27174 obj[name] = value;
27175 };
27176 }
27177}());
27178
27179var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
27180'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
27181'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
27182'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
27183'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
27184
27185function Context() {}
27186Context.prototype = {};
27187
27188var Script = exports.Script = function NodeScript (code) {
27189 if (!(this instanceof Script)) return new Script(code);
27190 this.code = code;
27191};
27192
27193Script.prototype.runInContext = function (context) {
27194 if (!(context instanceof Context)) {
27195 throw new TypeError("needs a 'context' argument.");
27196 }
27197
27198 var iframe = document.createElement('iframe');
27199 if (!iframe.style) iframe.style = {};
27200 iframe.style.display = 'none';
27201
27202 document.body.appendChild(iframe);
27203
27204 var win = iframe.contentWindow;
27205 var wEval = win.eval, wExecScript = win.execScript;
27206
27207 if (!wEval && wExecScript) {
27208 // win.eval() magically appears when this is called in IE:
27209 wExecScript.call(win, 'null');
27210 wEval = win.eval;
27211 }
27212
27213 forEach(Object_keys(context), function (key) {
27214 win[key] = context[key];
27215 });
27216 forEach(globals, function (key) {
27217 if (context[key]) {
27218 win[key] = context[key];
27219 }
27220 });
27221
27222 var winKeys = Object_keys(win);
27223
27224 var res = wEval.call(win, this.code);
27225
27226 forEach(Object_keys(win), function (key) {
27227 // Avoid copying circular objects like `top` and `window` by only
27228 // updating existing context properties or new properties in the `win`
27229 // that was only introduced after the eval.
27230 if (key in context || indexOf(winKeys, key) === -1) {
27231 context[key] = win[key];
27232 }
27233 });
27234
27235 forEach(globals, function (key) {
27236 if (!(key in context)) {
27237 defineProp(context, key, win[key]);
27238 }
27239 });
27240
27241 document.body.removeChild(iframe);
27242
27243 return res;
27244};
27245
27246Script.prototype.runInThisContext = function () {
27247 return eval(this.code); // maybe...
27248};
27249
27250Script.prototype.runInNewContext = function (context) {
27251 var ctx = Script.createContext(context);
27252 var res = this.runInContext(ctx);
27253
27254 forEach(Object_keys(ctx), function (key) {
27255 context[key] = ctx[key];
27256 });
27257
27258 return res;
27259};
27260
27261forEach(Object_keys(Script.prototype), function (name) {
27262 exports[name] = Script[name] = function (code) {
27263 var s = Script(code);
27264 return s[name].apply(s, [].slice.call(arguments, 1));
27265 };
27266});
27267
27268exports.createScript = function (code) {
27269 return exports.Script(code);
27270};
27271
27272exports.createContext = Script.createContext = function (context) {
27273 var copy = new Context();
27274 if(typeof context === 'object') {
27275 forEach(Object_keys(context), function (key) {
27276 copy[key] = context[key];
27277 });
27278 }
27279 return copy;
27280};
27281
27282},{"indexof":106}],"nebulas-account":[function(require,module,exports){
27283"use strict";
27284
27285var Buffer = require('safe-buffer').Buffer;
27286var Base58 = require('bs58');
27287var cryptoUtils = require('./utils/crypto-utils.js');
27288var utils = require('./utils/utils.js');
27289
27290var AddressLength = 26;
27291var AddressPrefix = 25;
27292var NormalType = 87;
27293var ContractType = 88;
27294
27295var KeyVersion3 = 3;
27296var KeyCurrentVersion = 4;
27297
27298/**
27299 * @typedef {Object} KeyOptions
27300 * @property {Buffer} salt
27301 * @property {Buffer} iv
27302 * @property {String} kdf
27303 * @property {Number} dklen
27304 * @property {Number} c
27305 * @property {Number} n
27306 * @property {Number} r
27307 * @property {Number} p
27308 * @property {String} cipher
27309 * @property {Buffer} uuid
27310 * @global
27311 */
27312
27313/**
27314 * Key Object.
27315 * @typedef {Object} Key
27316 * @property {Number} version
27317 * @property {Buffer} id
27318 * @property {HexString} address
27319 * @property {Object} crypto
27320 * @global
27321 */
27322
27323/**
27324 * Account constructor.
27325 * Class encapsulate main operation with account entity.
27326 * @constructor
27327 *
27328 * @param {Hash} priv Account private key.
27329 * @param {String} path
27330 *
27331 * @example var account = new Account(new Buffer("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6", "hex") );
27332 *
27333 */
27334var Account = function (priv, path) {
27335 priv = priv || cryptoUtils.crypto.randomBytes(32);
27336 this.setPrivateKey(priv);
27337 this.path = path;
27338};
27339
27340/**
27341 * Account factory method.
27342 * Create random account.
27343 * @static
27344 *
27345 * @return {Account} Instance of Account constructor.
27346 *
27347 * @example var account = Account.NewAccount();
27348 */
27349Account.NewAccount = function () {
27350 return new Account(cryptoUtils.crypto.randomBytes(32));
27351};
27352
27353/**
27354 * Address validation method.
27355 *
27356 * @static
27357 * @param {String/Hash} addr - Account address.
27358 * @param {Number} type - NormalType / ContractType
27359 *
27360 * @return {Boolean} Is address has correct format.
27361 *
27362 * @example
27363 * if ( Account.isValidAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5") ) {
27364 * // some code
27365 * };
27366 */
27367Account.isValidAddress = function (addr, type) {
27368 /*jshint maxcomplexity:10 */
27369
27370 if (utils.isString(addr)) {
27371 try {
27372 addr = Base58.decode(addr);
27373 } catch (e) {
27374 console.log("invalid address.");
27375 // if address can't be base58 decode, return false.
27376 return false;
27377 }
27378 } else if (!Buffer.isBuffer(addr)) {
27379 return false;
27380 }
27381 // address not equal to 26
27382 if (addr.length !== AddressLength) {
27383 return false;
27384 }
27385
27386 // check if address start with AddressPrefix
27387 var buff = Buffer.from(addr);
27388 if (buff.readUIntBE(0, 1) !== AddressPrefix) {
27389 return false;
27390 }
27391
27392 // check if address type is NormalType or ContractType
27393 var t = buff.readUIntBE(1, 1);
27394 if (utils.isNumber(type) && (type === NormalType || type === ContractType)) {
27395 if (t !== type) {
27396 return false;
27397 }
27398 } else if (t !== NormalType && t !== ContractType) {
27399 return false;
27400 }
27401 var content = addr.slice(0, 22);
27402 var checksum = addr.slice(-4);
27403 return Buffer.compare(cryptoUtils.sha3(content).slice(0, 4), checksum) === 0;
27404};
27405
27406/**
27407 * Restore account from address.
27408 * Receive addr or Account instance.
27409 * If addr is Account instance return new Account instance with same PrivateKey.
27410 *
27411 * @static
27412 * @param {(Hash|Object)} - Client address or Account instance.
27413 *
27414 * @return {Account} Instance of Account restored from address.
27415 *
27416 * @example var account = Account.fromAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5");
27417 */
27418Account.fromAddress = function (addr) {
27419 var acc = new Account();
27420 if (addr instanceof Account) {
27421 acc.setPrivateKey(addr.getPrivateKey());
27422 return acc;
27423 }
27424 if (utils.isString(addr) && this.isValidAddress(addr)) {
27425 acc.address = Base58.decode(addr);
27426 return acc;
27427 }
27428
27429 var buf = cryptoUtils.toBuffer(addr);
27430 if (this.isValidAddress(buf)) {
27431 acc.address = buf;
27432 return acc;
27433 }
27434 throw new Error("invalid address");
27435};
27436
27437/**
27438 * Restore account from public key.
27439 *
27440 * @static
27441 * @param {(String/Hash)} - Public key.
27442 *
27443 * @return {Account} Instance of Account restored from address.
27444 *
27445 * @example var account = Account.fromPubKey("f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7");
27446 */
27447Account.fromPubKey = function (publicKey) {
27448 var acc = new Account();
27449 acc.pubKey = cryptoUtils.toBuffer(publicKey);
27450 return acc;
27451};
27452
27453Account.getNormalType = function () {
27454 return NormalType;
27455};
27456
27457Account.getContractType = function () {
27458 return ContractType;
27459};
27460
27461Account.prototype = {
27462 /**
27463 * Private Key setter.
27464 *
27465 * @param {Hash} priv - Account private key.
27466 *
27467 * @example account.setPrivateKey("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6");
27468 */
27469 setPrivateKey: function (priv) {
27470 if (utils.isString(priv) || Buffer.isBuffer(priv)) {
27471 this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex');
27472 this.pubKey = null;
27473 this.address = null;
27474 }
27475 },
27476 /**
27477 * Private Key getter.
27478 *
27479 * @return {Buffer} Account private key.
27480 *
27481 * @example var privKey = account.getPrivateKey();
27482 * //<Buffer 5b ed 67 f9 9c b3 31 9e 0c 6f 6a 03 54 8b e3 c8 c5 2a 83 64 46 4f 88 6f> 24
27483 */
27484 getPrivateKey: function () {
27485 return this.privKey;
27486 },
27487 /**
27488 * Get Private Key in hex string format.
27489 *
27490 * @return {HexString} Account private key in String format.
27491 *
27492 * @example var privKey = account.getPrivateKeyString();
27493 * //"ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6"
27494 */
27495 getPrivateKeyString: function () {
27496 return this.getPrivateKey().toString('hex');
27497 },
27498 /**
27499 * Public Key getter.
27500 *
27501 * @return {Buffer} Account public key.
27502 *
27503 * @example var publicKey = account.getPublicKey();
27504 * //<Buffer c0 96 aa 4e 66 c7 4a 9a c7 18 31 f1 24 72 2a c1 3e b5 df 7f 97 1b 13 1d 46 a2 8a e6 81 c6 1d 96 f7 07 d0 aa e9 a7 67 436b 68 af a8 f0 96 65 17 24 29 ... >
27505 */
27506 getPublicKey: function () {
27507 if (utils.isNull(this.pubKey)) {
27508 this.pubKey = cryptoUtils.privateToPublic(this.privKey);
27509 }
27510 return this.pubKey;
27511 },
27512 /**
27513 * Get Public Key in hex string format.
27514 *
27515 * @return {HexString} Account public key in String format.
27516 *
27517 * @example var publicKey = account.getPublicKey();
27518 * //"f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7"
27519 */
27520 getPublicKeyString: function () {
27521 return this.getPublicKey().toString('hex');
27522 },
27523 /**
27524 * Accaunt address getter.
27525 *
27526 * @return {Buffer} Account address.
27527 *
27528 * @example var publicKey = account.getAddress();
27529 * //<Buffer 7f 87 83 58 46 96 12 7d 1a c0 57 1a 42 87 c6 25 36 08 ff 32 61 36 51 7c>
27530 */
27531 getAddress: function () {
27532 if (utils.isNull(this.address)) {
27533
27534 var pubKey = this.getPublicKey();
27535 if (pubKey.length !== 64) {
27536 pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1);
27537 }
27538
27539 // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus
27540 // the concatenation of the binary representation of the X coordinate plus the binary
27541 // representation of the y coordinate of the public point.
27542 pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]);
27543
27544 // Only take the lower 160bits of the hash
27545 var content = cryptoUtils.sha3(pubKey);
27546 content = cryptoUtils.ripemd160(content);
27547 // content = AddressPrefix + NormalType + content(local address only use normal type)
27548 content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]);
27549 var checksum = cryptoUtils.sha3(content).slice(0, 4);
27550 this.address = Buffer.concat([content, checksum]);
27551 }
27552 return this.address;
27553 },
27554 /**
27555 * Get account address in hex string format.
27556 *
27557 * @return {HexString} Account address in String format.
27558 *
27559 * @example var publicKey = account.getAddressString();
27560 * //"802d529bf55d6693b3ac72c59b4a7d159da53cae5a7bf99c"
27561 */
27562 getAddressString: function () {
27563 var addr = this.getAddress();
27564 return Base58.encode(addr);
27565 },
27566 /**
27567 * Generate key buy passphrase and options.
27568 *
27569 * @param {Password} password - Provided password.
27570 * @param {KeyOptions} opts - Key options.
27571 *
27572 * @return {Key} Key Object.
27573 *
27574 * @example var key = account.toKey("passphrase");
27575 */
27576 toKey: function (password, opts) {
27577 /*jshint maxcomplexity:17 */
27578
27579 opts = opts || {};
27580 var salt = opts.salt || cryptoUtils.crypto.randomBytes(32);
27581 var iv = opts.iv || cryptoUtils.crypto.randomBytes(16);
27582 var derivedKey;
27583 var kdf = opts.kdf || 'scrypt';
27584 var kdfparams = {
27585 dklen: opts.dklen || 32,
27586 salt: salt.toString('hex')
27587 };
27588 if (kdf === 'pbkdf2') {
27589 kdfparams.c = opts.c || 262144;
27590 kdfparams.prf = 'hmac-sha256';
27591 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256');
27592 } else if (kdf === 'scrypt') {
27593 kdfparams.n = opts.n || 4096;
27594 kdfparams.r = opts.r || 8;
27595 kdfparams.p = opts.p || 1;
27596 derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
27597 } else {
27598 throw new Error('Unsupported kdf');
27599 }
27600 var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv);
27601 if (!cipher) {
27602 throw new Error('Unsupported cipher');
27603 }
27604 var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]);
27605 // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated
27606 var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')]));
27607 return {
27608 version: KeyCurrentVersion,
27609 id: cryptoUtils.uuid.v4({
27610 random: opts.uuid || cryptoUtils.crypto.randomBytes(16)
27611 }),
27612 address: this.getAddressString(),
27613 crypto: {
27614 ciphertext: ciphertext.toString('hex'),
27615 cipherparams: {
27616 iv: iv.toString('hex')
27617 },
27618 cipher: opts.cipher || 'aes-128-ctr',
27619 kdf: kdf,
27620 kdfparams: kdfparams,
27621 mac: mac.toString('hex'),
27622 machash: "sha3256"
27623 }
27624 };
27625 },
27626 /**
27627 * Generate key buy passphrase and options.
27628 * Return in JSON format.
27629 *
27630 * @param {Password} password - Provided password.
27631 * @param {KeyOptions} opts - Key options.
27632 *
27633 * @return {String} JSON stringify Key.
27634 *
27635 * @example var key = account.toKeyString("passphrase");
27636 */
27637 toKeyString: function (password, opts) {
27638 return JSON.stringify(this.toKey(password, opts));
27639 },
27640 /**
27641 * Restore account from key and passphrase.
27642 *
27643 * @param {Key} input - Key Object.
27644 * @param {Password} password - Provided password.
27645 * @param {Boolean} nonStrict - Strict сase sensitivity flag.
27646 *
27647 * @return {@link Account} - Instance of Account restored from key and passphrase.
27648 */
27649 fromKey: function (input, password, nonStrict) {
27650 /*jshint maxcomplexity:10 */
27651
27652 var json = typeof input === 'object' ? input : JSON.parse(nonStrict ? input.toLowerCase() : input);
27653 if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) {
27654 throw new Error('Not supported wallet version');
27655 }
27656 var derivedKey;
27657 var kdfparams;
27658 if (json.crypto.kdf === 'scrypt') {
27659 kdfparams = json.crypto.kdfparams;
27660 derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
27661 } else if (json.crypto.kdf === 'pbkdf2') {
27662 kdfparams = json.crypto.kdfparams;
27663 if (kdfparams.prf !== 'hmac-sha256') {
27664 throw new Error('Unsupported parameters to PBKDF2');
27665 }
27666 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256');
27667 } else {
27668 throw new Error('Unsupported key derivation scheme');
27669 }
27670 var ciphertext = new Buffer(json.crypto.ciphertext, 'hex');
27671 var mac;
27672
27673 if (json.version === KeyCurrentVersion) {
27674 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)]));
27675 } else {
27676 // KeyVersion3
27677 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext]));
27678 }
27679
27680 if (mac.toString('hex') !== json.crypto.mac) {
27681 throw new Error('Key derivation failed - possibly wrong passphrase');
27682 }
27683 var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex'));
27684 var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
27685 while (seed.length < 32) {
27686 var nullBuff = new Buffer([0x00]);
27687 seed = Buffer.concat([nullBuff, seed]);
27688 }
27689 this.setPrivateKey(seed);
27690 return this;
27691 }
27692
27693};
27694
27695module.exports = Account;
27696
27697},{"./utils/crypto-utils.js":1,"./utils/utils.js":2,"bs58":51,"safe-buffer":156}]},{},[]);