aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/index.html1
-rw-r--r--src/js/index.js16
-rw-r--r--src/js/stellar-util.js41520
3 files changed, 41537 insertions, 0 deletions
diff --git a/src/index.html b/src/index.html
index b3f2d33..d3333b5 100644
--- a/src/index.html
+++ b/src/index.html
@@ -888,6 +888,7 @@
888 <script src="js/biginteger.js"></script> 888 <script src="js/biginteger.js"></script>
889 <script src="js/zxcvbn.js"></script> 889 <script src="js/zxcvbn.js"></script>
890 <script src="js/entropy.js"></script> 890 <script src="js/entropy.js"></script>
891 <script src="js/stellar-util.js"></script>
891 <script src="js/index.js"></script> 892 <script src="js/index.js"></script>
892 </body> 893 </body>
893</html> 894</html>
diff --git a/src/js/index.js b/src/js/index.js
index 5a1037b..9fbdca3 100644
--- a/src/js/index.js
+++ b/src/js/index.js
@@ -808,6 +808,14 @@
808 privkey = ethUtil.addHexPrefix(privkey); 808 privkey = ethUtil.addHexPrefix(privkey);
809 pubkey = ethUtil.addHexPrefix(pubkey); 809 pubkey = ethUtil.addHexPrefix(pubkey);
810 } 810 }
811 // Stellar is different
812 if (networks[DOM.network.val()].name == "XLM - Stellar") {
813 const path = "m/44'/148'/" + index + "'";
814 const keypair = stellarUtil.derivePath(path, seed);
815 indexText = path;
816 privkey = keypair.secret();
817 pubkey = address = keypair.publicKey();
818 }
811 // Ripple values are different 819 // Ripple values are different
812 if (networks[DOM.network.val()].name == "XRP - Ripple") { 820 if (networks[DOM.network.val()].name == "XRP - Ripple") {
813 privkey = convertRipplePriv(privkey); 821 privkey = convertRipplePriv(privkey);
@@ -1695,6 +1703,14 @@
1695 }, 1703 },
1696 }, 1704 },
1697 { 1705 {
1706 name: "XLM - Stellar",
1707 onSelect: function() {
1708 segwitAvailable: false,
1709 network = null;
1710 setHdCoin(148);
1711 },
1712 },
1713 {
1698 name: "XMY - Myriadcoin", 1714 name: "XMY - Myriadcoin",
1699 segwitAvailable: false, 1715 segwitAvailable: false,
1700 onSelect: function() { 1716 onSelect: function() {
diff --git a/src/js/stellar-util.js b/src/js/stellar-util.js
new file mode 100644
index 0000000..5d991db
--- /dev/null
+++ b/src/js/stellar-util.js
@@ -0,0 +1,41520 @@
1(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2var asn1 = exports;
3
4asn1.bignum = require('bn.js');
5
6asn1.define = require('./asn1/api').define;
7asn1.base = require('./asn1/base');
8asn1.constants = require('./asn1/constants');
9asn1.decoders = require('./asn1/decoders');
10asn1.encoders = require('./asn1/encoders');
11
12},{"./asn1/api":2,"./asn1/base":4,"./asn1/constants":8,"./asn1/decoders":10,"./asn1/encoders":13,"bn.js":18}],2:[function(require,module,exports){
13var asn1 = require('../asn1');
14var inherits = require('inherits');
15
16var api = exports;
17
18api.define = function define(name, body) {
19 return new Entity(name, body);
20};
21
22function Entity(name, body) {
23 this.name = name;
24 this.body = body;
25
26 this.decoders = {};
27 this.encoders = {};
28};
29
30Entity.prototype._createNamed = function createNamed(base) {
31 var named;
32 try {
33 named = require('vm').runInThisContext(
34 '(function ' + this.name + '(entity) {\n' +
35 ' this._initNamed(entity);\n' +
36 '})'
37 );
38 } catch (e) {
39 named = function (entity) {
40 this._initNamed(entity);
41 };
42 }
43 inherits(named, base);
44 named.prototype._initNamed = function initnamed(entity) {
45 base.call(this, entity);
46 };
47
48 return new named(this);
49};
50
51Entity.prototype._getDecoder = function _getDecoder(enc) {
52 enc = enc || 'der';
53 // Lazily create decoder
54 if (!this.decoders.hasOwnProperty(enc))
55 this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
56 return this.decoders[enc];
57};
58
59Entity.prototype.decode = function decode(data, enc, options) {
60 return this._getDecoder(enc).decode(data, options);
61};
62
63Entity.prototype._getEncoder = function _getEncoder(enc) {
64 enc = enc || 'der';
65 // Lazily create encoder
66 if (!this.encoders.hasOwnProperty(enc))
67 this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
68 return this.encoders[enc];
69};
70
71Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
72 return this._getEncoder(enc).encode(data, reporter);
73};
74
75},{"../asn1":1,"inherits":116,"vm":439}],3:[function(require,module,exports){
76var inherits = require('inherits');
77var Reporter = require('../base').Reporter;
78var Buffer = require('buffer').Buffer;
79
80function DecoderBuffer(base, options) {
81 Reporter.call(this, options);
82 if (!Buffer.isBuffer(base)) {
83 this.error('Input not Buffer');
84 return;
85 }
86
87 this.base = base;
88 this.offset = 0;
89 this.length = base.length;
90}
91inherits(DecoderBuffer, Reporter);
92exports.DecoderBuffer = DecoderBuffer;
93
94DecoderBuffer.prototype.save = function save() {
95 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
96};
97
98DecoderBuffer.prototype.restore = function restore(save) {
99 // Return skipped data
100 var res = new DecoderBuffer(this.base);
101 res.offset = save.offset;
102 res.length = this.offset;
103
104 this.offset = save.offset;
105 Reporter.prototype.restore.call(this, save.reporter);
106
107 return res;
108};
109
110DecoderBuffer.prototype.isEmpty = function isEmpty() {
111 return this.offset === this.length;
112};
113
114DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
115 if (this.offset + 1 <= this.length)
116 return this.base.readUInt8(this.offset++, true);
117 else
118 return this.error(fail || 'DecoderBuffer overrun');
119}
120
121DecoderBuffer.prototype.skip = function skip(bytes, fail) {
122 if (!(this.offset + bytes <= this.length))
123 return this.error(fail || 'DecoderBuffer overrun');
124
125 var res = new DecoderBuffer(this.base);
126
127 // Share reporter state
128 res._reporterState = this._reporterState;
129
130 res.offset = this.offset;
131 res.length = this.offset + bytes;
132 this.offset += bytes;
133 return res;
134}
135
136DecoderBuffer.prototype.raw = function raw(save) {
137 return this.base.slice(save ? save.offset : this.offset, this.length);
138}
139
140function EncoderBuffer(value, reporter) {
141 if (Array.isArray(value)) {
142 this.length = 0;
143 this.value = value.map(function(item) {
144 if (!(item instanceof EncoderBuffer))
145 item = new EncoderBuffer(item, reporter);
146 this.length += item.length;
147 return item;
148 }, this);
149 } else if (typeof value === 'number') {
150 if (!(0 <= value && value <= 0xff))
151 return reporter.error('non-byte EncoderBuffer value');
152 this.value = value;
153 this.length = 1;
154 } else if (typeof value === 'string') {
155 this.value = value;
156 this.length = Buffer.byteLength(value);
157 } else if (Buffer.isBuffer(value)) {
158 this.value = value;
159 this.length = value.length;
160 } else {
161 return reporter.error('Unsupported type: ' + typeof value);
162 }
163}
164exports.EncoderBuffer = EncoderBuffer;
165
166EncoderBuffer.prototype.join = function join(out, offset) {
167 if (!out)
168 out = new Buffer(this.length);
169 if (!offset)
170 offset = 0;
171
172 if (this.length === 0)
173 return out;
174
175 if (Array.isArray(this.value)) {
176 this.value.forEach(function(item) {
177 item.join(out, offset);
178 offset += item.length;
179 });
180 } else {
181 if (typeof this.value === 'number')
182 out[offset] = this.value;
183 else if (typeof this.value === 'string')
184 out.write(this.value, offset);
185 else if (Buffer.isBuffer(this.value))
186 this.value.copy(out, offset);
187 offset += this.length;
188 }
189
190 return out;
191};
192
193},{"../base":4,"buffer":49,"inherits":116}],4:[function(require,module,exports){
194var base = exports;
195
196base.Reporter = require('./reporter').Reporter;
197base.DecoderBuffer = require('./buffer').DecoderBuffer;
198base.EncoderBuffer = require('./buffer').EncoderBuffer;
199base.Node = require('./node');
200
201},{"./buffer":3,"./node":5,"./reporter":6}],5:[function(require,module,exports){
202var Reporter = require('../base').Reporter;
203var EncoderBuffer = require('../base').EncoderBuffer;
204var DecoderBuffer = require('../base').DecoderBuffer;
205var assert = require('minimalistic-assert');
206
207// Supported tags
208var tags = [
209 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
210 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
211 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
212 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
213];
214
215// Public methods list
216var methods = [
217 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
218 'any', 'contains'
219].concat(tags);
220
221// Overrided methods list
222var overrided = [
223 '_peekTag', '_decodeTag', '_use',
224 '_decodeStr', '_decodeObjid', '_decodeTime',
225 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
226
227 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
228 '_encodeNull', '_encodeInt', '_encodeBool'
229];
230
231function Node(enc, parent) {
232 var state = {};
233 this._baseState = state;
234
235 state.enc = enc;
236
237 state.parent = parent || null;
238 state.children = null;
239
240 // State
241 state.tag = null;
242 state.args = null;
243 state.reverseArgs = null;
244 state.choice = null;
245 state.optional = false;
246 state.any = false;
247 state.obj = false;
248 state.use = null;
249 state.useDecoder = null;
250 state.key = null;
251 state['default'] = null;
252 state.explicit = null;
253 state.implicit = null;
254 state.contains = null;
255
256 // Should create new instance on each method
257 if (!state.parent) {
258 state.children = [];
259 this._wrap();
260 }
261}
262module.exports = Node;
263
264var stateProps = [
265 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
266 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
267 'implicit', 'contains'
268];
269
270Node.prototype.clone = function clone() {
271 var state = this._baseState;
272 var cstate = {};
273 stateProps.forEach(function(prop) {
274 cstate[prop] = state[prop];
275 });
276 var res = new this.constructor(cstate.parent);
277 res._baseState = cstate;
278 return res;
279};
280
281Node.prototype._wrap = function wrap() {
282 var state = this._baseState;
283 methods.forEach(function(method) {
284 this[method] = function _wrappedMethod() {
285 var clone = new this.constructor(this);
286 state.children.push(clone);
287 return clone[method].apply(clone, arguments);
288 };
289 }, this);
290};
291
292Node.prototype._init = function init(body) {
293 var state = this._baseState;
294
295 assert(state.parent === null);
296 body.call(this);
297
298 // Filter children
299 state.children = state.children.filter(function(child) {
300 return child._baseState.parent === this;
301 }, this);
302 assert.equal(state.children.length, 1, 'Root node can have only one child');
303};
304
305Node.prototype._useArgs = function useArgs(args) {
306 var state = this._baseState;
307
308 // Filter children and args
309 var children = args.filter(function(arg) {
310 return arg instanceof this.constructor;
311 }, this);
312 args = args.filter(function(arg) {
313 return !(arg instanceof this.constructor);
314 }, this);
315
316 if (children.length !== 0) {
317 assert(state.children === null);
318 state.children = children;
319
320 // Replace parent to maintain backward link
321 children.forEach(function(child) {
322 child._baseState.parent = this;
323 }, this);
324 }
325 if (args.length !== 0) {
326 assert(state.args === null);
327 state.args = args;
328 state.reverseArgs = args.map(function(arg) {
329 if (typeof arg !== 'object' || arg.constructor !== Object)
330 return arg;
331
332 var res = {};
333 Object.keys(arg).forEach(function(key) {
334 if (key == (key | 0))
335 key |= 0;
336 var value = arg[key];
337 res[value] = key;
338 });
339 return res;
340 });
341 }
342};
343
344//
345// Overrided methods
346//
347
348overrided.forEach(function(method) {
349 Node.prototype[method] = function _overrided() {
350 var state = this._baseState;
351 throw new Error(method + ' not implemented for encoding: ' + state.enc);
352 };
353});
354
355//
356// Public methods
357//
358
359tags.forEach(function(tag) {
360 Node.prototype[tag] = function _tagMethod() {
361 var state = this._baseState;
362 var args = Array.prototype.slice.call(arguments);
363
364 assert(state.tag === null);
365 state.tag = tag;
366
367 this._useArgs(args);
368
369 return this;
370 };
371});
372
373Node.prototype.use = function use(item) {
374 assert(item);
375 var state = this._baseState;
376
377 assert(state.use === null);
378 state.use = item;
379
380 return this;
381};
382
383Node.prototype.optional = function optional() {
384 var state = this._baseState;
385
386 state.optional = true;
387
388 return this;
389};
390
391Node.prototype.def = function def(val) {
392 var state = this._baseState;
393
394 assert(state['default'] === null);
395 state['default'] = val;
396 state.optional = true;
397
398 return this;
399};
400
401Node.prototype.explicit = function explicit(num) {
402 var state = this._baseState;
403
404 assert(state.explicit === null && state.implicit === null);
405 state.explicit = num;
406
407 return this;
408};
409
410Node.prototype.implicit = function implicit(num) {
411 var state = this._baseState;
412
413 assert(state.explicit === null && state.implicit === null);
414 state.implicit = num;
415
416 return this;
417};
418
419Node.prototype.obj = function obj() {
420 var state = this._baseState;
421 var args = Array.prototype.slice.call(arguments);
422
423 state.obj = true;
424
425 if (args.length !== 0)
426 this._useArgs(args);
427
428 return this;
429};
430
431Node.prototype.key = function key(newKey) {
432 var state = this._baseState;
433
434 assert(state.key === null);
435 state.key = newKey;
436
437 return this;
438};
439
440Node.prototype.any = function any() {
441 var state = this._baseState;
442
443 state.any = true;
444
445 return this;
446};
447
448Node.prototype.choice = function choice(obj) {
449 var state = this._baseState;
450
451 assert(state.choice === null);
452 state.choice = obj;
453 this._useArgs(Object.keys(obj).map(function(key) {
454 return obj[key];
455 }));
456
457 return this;
458};
459
460Node.prototype.contains = function contains(item) {
461 var state = this._baseState;
462
463 assert(state.use === null);
464 state.contains = item;
465
466 return this;
467};
468
469//
470// Decoding
471//
472
473Node.prototype._decode = function decode(input, options) {
474 var state = this._baseState;
475
476 // Decode root node
477 if (state.parent === null)
478 return input.wrapResult(state.children[0]._decode(input, options));
479
480 var result = state['default'];
481 var present = true;
482
483 var prevKey = null;
484 if (state.key !== null)
485 prevKey = input.enterKey(state.key);
486
487 // Check if tag is there
488 if (state.optional) {
489 var tag = null;
490 if (state.explicit !== null)
491 tag = state.explicit;
492 else if (state.implicit !== null)
493 tag = state.implicit;
494 else if (state.tag !== null)
495 tag = state.tag;
496
497 if (tag === null && !state.any) {
498 // Trial and Error
499 var save = input.save();
500 try {
501 if (state.choice === null)
502 this._decodeGeneric(state.tag, input, options);
503 else
504 this._decodeChoice(input, options);
505 present = true;
506 } catch (e) {
507 present = false;
508 }
509 input.restore(save);
510 } else {
511 present = this._peekTag(input, tag, state.any);
512
513 if (input.isError(present))
514 return present;
515 }
516 }
517
518 // Push object on stack
519 var prevObj;
520 if (state.obj && present)
521 prevObj = input.enterObject();
522
523 if (present) {
524 // Unwrap explicit values
525 if (state.explicit !== null) {
526 var explicit = this._decodeTag(input, state.explicit);
527 if (input.isError(explicit))
528 return explicit;
529 input = explicit;
530 }
531
532 var start = input.offset;
533
534 // Unwrap implicit and normal values
535 if (state.use === null && state.choice === null) {
536 if (state.any)
537 var save = input.save();
538 var body = this._decodeTag(
539 input,
540 state.implicit !== null ? state.implicit : state.tag,
541 state.any
542 );
543 if (input.isError(body))
544 return body;
545
546 if (state.any)
547 result = input.raw(save);
548 else
549 input = body;
550 }
551
552 if (options && options.track && state.tag !== null)
553 options.track(input.path(), start, input.length, 'tagged');
554
555 if (options && options.track && state.tag !== null)
556 options.track(input.path(), input.offset, input.length, 'content');
557
558 // Select proper method for tag
559 if (state.any)
560 result = result;
561 else if (state.choice === null)
562 result = this._decodeGeneric(state.tag, input, options);
563 else
564 result = this._decodeChoice(input, options);
565
566 if (input.isError(result))
567 return result;
568
569 // Decode children
570 if (!state.any && state.choice === null && state.children !== null) {
571 state.children.forEach(function decodeChildren(child) {
572 // NOTE: We are ignoring errors here, to let parser continue with other
573 // parts of encoded data
574 child._decode(input, options);
575 });
576 }
577
578 // Decode contained/encoded by schema, only in bit or octet strings
579 if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
580 var data = new DecoderBuffer(result);
581 result = this._getUse(state.contains, input._reporterState.obj)
582 ._decode(data, options);
583 }
584 }
585
586 // Pop object
587 if (state.obj && present)
588 result = input.leaveObject(prevObj);
589
590 // Set key
591 if (state.key !== null && (result !== null || present === true))
592 input.leaveKey(prevKey, state.key, result);
593 else if (prevKey !== null)
594 input.exitKey(prevKey);
595
596 return result;
597};
598
599Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
600 var state = this._baseState;
601
602 if (tag === 'seq' || tag === 'set')
603 return null;
604 if (tag === 'seqof' || tag === 'setof')
605 return this._decodeList(input, tag, state.args[0], options);
606 else if (/str$/.test(tag))
607 return this._decodeStr(input, tag, options);
608 else if (tag === 'objid' && state.args)
609 return this._decodeObjid(input, state.args[0], state.args[1], options);
610 else if (tag === 'objid')
611 return this._decodeObjid(input, null, null, options);
612 else if (tag === 'gentime' || tag === 'utctime')
613 return this._decodeTime(input, tag, options);
614 else if (tag === 'null_')
615 return this._decodeNull(input, options);
616 else if (tag === 'bool')
617 return this._decodeBool(input, options);
618 else if (tag === 'objDesc')
619 return this._decodeStr(input, tag, options);
620 else if (tag === 'int' || tag === 'enum')
621 return this._decodeInt(input, state.args && state.args[0], options);
622
623 if (state.use !== null) {
624 return this._getUse(state.use, input._reporterState.obj)
625 ._decode(input, options);
626 } else {
627 return input.error('unknown tag: ' + tag);
628 }
629};
630
631Node.prototype._getUse = function _getUse(entity, obj) {
632
633 var state = this._baseState;
634 // Create altered use decoder if implicit is set
635 state.useDecoder = this._use(entity, obj);
636 assert(state.useDecoder._baseState.parent === null);
637 state.useDecoder = state.useDecoder._baseState.children[0];
638 if (state.implicit !== state.useDecoder._baseState.implicit) {
639 state.useDecoder = state.useDecoder.clone();
640 state.useDecoder._baseState.implicit = state.implicit;
641 }
642 return state.useDecoder;
643};
644
645Node.prototype._decodeChoice = function decodeChoice(input, options) {
646 var state = this._baseState;
647 var result = null;
648 var match = false;
649
650 Object.keys(state.choice).some(function(key) {
651 var save = input.save();
652 var node = state.choice[key];
653 try {
654 var value = node._decode(input, options);
655 if (input.isError(value))
656 return false;
657
658 result = { type: key, value: value };
659 match = true;
660 } catch (e) {
661 input.restore(save);
662 return false;
663 }
664 return true;
665 }, this);
666
667 if (!match)
668 return input.error('Choice not matched');
669
670 return result;
671};
672
673//
674// Encoding
675//
676
677Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
678 return new EncoderBuffer(data, this.reporter);
679};
680
681Node.prototype._encode = function encode(data, reporter, parent) {
682 var state = this._baseState;
683 if (state['default'] !== null && state['default'] === data)
684 return;
685
686 var result = this._encodeValue(data, reporter, parent);
687 if (result === undefined)
688 return;
689
690 if (this._skipDefault(result, reporter, parent))
691 return;
692
693 return result;
694};
695
696Node.prototype._encodeValue = function encode(data, reporter, parent) {
697 var state = this._baseState;
698
699 // Decode root node
700 if (state.parent === null)
701 return state.children[0]._encode(data, reporter || new Reporter());
702
703 var result = null;
704
705 // Set reporter to share it with a child class
706 this.reporter = reporter;
707
708 // Check if data is there
709 if (state.optional && data === undefined) {
710 if (state['default'] !== null)
711 data = state['default']
712 else
713 return;
714 }
715
716 // Encode children first
717 var content = null;
718 var primitive = false;
719 if (state.any) {
720 // Anything that was given is translated to buffer
721 result = this._createEncoderBuffer(data);
722 } else if (state.choice) {
723 result = this._encodeChoice(data, reporter);
724 } else if (state.contains) {
725 content = this._getUse(state.contains, parent)._encode(data, reporter);
726 primitive = true;
727 } else if (state.children) {
728 content = state.children.map(function(child) {
729 if (child._baseState.tag === 'null_')
730 return child._encode(null, reporter, data);
731
732 if (child._baseState.key === null)
733 return reporter.error('Child should have a key');
734 var prevKey = reporter.enterKey(child._baseState.key);
735
736 if (typeof data !== 'object')
737 return reporter.error('Child expected, but input is not object');
738
739 var res = child._encode(data[child._baseState.key], reporter, data);
740 reporter.leaveKey(prevKey);
741
742 return res;
743 }, this).filter(function(child) {
744 return child;
745 });
746 content = this._createEncoderBuffer(content);
747 } else {
748 if (state.tag === 'seqof' || state.tag === 'setof') {
749 // TODO(indutny): this should be thrown on DSL level
750 if (!(state.args && state.args.length === 1))
751 return reporter.error('Too many args for : ' + state.tag);
752
753 if (!Array.isArray(data))
754 return reporter.error('seqof/setof, but data is not Array');
755
756 var child = this.clone();
757 child._baseState.implicit = null;
758 content = this._createEncoderBuffer(data.map(function(item) {
759 var state = this._baseState;
760
761 return this._getUse(state.args[0], data)._encode(item, reporter);
762 }, child));
763 } else if (state.use !== null) {
764 result = this._getUse(state.use, parent)._encode(data, reporter);
765 } else {
766 content = this._encodePrimitive(state.tag, data);
767 primitive = true;
768 }
769 }
770
771 // Encode data itself
772 var result;
773 if (!state.any && state.choice === null) {
774 var tag = state.implicit !== null ? state.implicit : state.tag;
775 var cls = state.implicit === null ? 'universal' : 'context';
776
777 if (tag === null) {
778 if (state.use === null)
779 reporter.error('Tag could be omitted only for .use()');
780 } else {
781 if (state.use === null)
782 result = this._encodeComposite(tag, primitive, cls, content);
783 }
784 }
785
786 // Wrap in explicit
787 if (state.explicit !== null)
788 result = this._encodeComposite(state.explicit, false, 'context', result);
789
790 return result;
791};
792
793Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
794 var state = this._baseState;
795
796 var node = state.choice[data.type];
797 if (!node) {
798 assert(
799 false,
800 data.type + ' not found in ' +
801 JSON.stringify(Object.keys(state.choice)));
802 }
803 return node._encode(data.value, reporter);
804};
805
806Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
807 var state = this._baseState;
808
809 if (/str$/.test(tag))
810 return this._encodeStr(data, tag);
811 else if (tag === 'objid' && state.args)
812 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
813 else if (tag === 'objid')
814 return this._encodeObjid(data, null, null);
815 else if (tag === 'gentime' || tag === 'utctime')
816 return this._encodeTime(data, tag);
817 else if (tag === 'null_')
818 return this._encodeNull();
819 else if (tag === 'int' || tag === 'enum')
820 return this._encodeInt(data, state.args && state.reverseArgs[0]);
821 else if (tag === 'bool')
822 return this._encodeBool(data);
823 else if (tag === 'objDesc')
824 return this._encodeStr(data, tag);
825 else
826 throw new Error('Unsupported tag: ' + tag);
827};
828
829Node.prototype._isNumstr = function isNumstr(str) {
830 return /^[0-9 ]*$/.test(str);
831};
832
833Node.prototype._isPrintstr = function isPrintstr(str) {
834 return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
835};
836
837},{"../base":4,"minimalistic-assert":356}],6:[function(require,module,exports){
838var inherits = require('inherits');
839
840function Reporter(options) {
841 this._reporterState = {
842 obj: null,
843 path: [],
844 options: options || {},
845 errors: []
846 };
847}
848exports.Reporter = Reporter;
849
850Reporter.prototype.isError = function isError(obj) {
851 return obj instanceof ReporterError;
852};
853
854Reporter.prototype.save = function save() {
855 var state = this._reporterState;
856
857 return { obj: state.obj, pathLen: state.path.length };
858};
859
860Reporter.prototype.restore = function restore(data) {
861 var state = this._reporterState;
862
863 state.obj = data.obj;
864 state.path = state.path.slice(0, data.pathLen);
865};
866
867Reporter.prototype.enterKey = function enterKey(key) {
868 return this._reporterState.path.push(key);
869};
870
871Reporter.prototype.exitKey = function exitKey(index) {
872 var state = this._reporterState;
873
874 state.path = state.path.slice(0, index - 1);
875};
876
877Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
878 var state = this._reporterState;
879
880 this.exitKey(index);
881 if (state.obj !== null)
882 state.obj[key] = value;
883};
884
885Reporter.prototype.path = function path() {
886 return this._reporterState.path.join('/');
887};
888
889Reporter.prototype.enterObject = function enterObject() {
890 var state = this._reporterState;
891
892 var prev = state.obj;
893 state.obj = {};
894 return prev;
895};
896
897Reporter.prototype.leaveObject = function leaveObject(prev) {
898 var state = this._reporterState;
899
900 var now = state.obj;
901 state.obj = prev;
902 return now;
903};
904
905Reporter.prototype.error = function error(msg) {
906 var err;
907 var state = this._reporterState;
908
909 var inherited = msg instanceof ReporterError;
910 if (inherited) {
911 err = msg;
912 } else {
913 err = new ReporterError(state.path.map(function(elem) {
914 return '[' + JSON.stringify(elem) + ']';
915 }).join(''), msg.message || msg, msg.stack);
916 }
917
918 if (!state.options.partial)
919 throw err;
920
921 if (!inherited)
922 state.errors.push(err);
923
924 return err;
925};
926
927Reporter.prototype.wrapResult = function wrapResult(result) {
928 var state = this._reporterState;
929 if (!state.options.partial)
930 return result;
931
932 return {
933 result: this.isError(result) ? null : result,
934 errors: state.errors
935 };
936};
937
938function ReporterError(path, msg) {
939 this.path = path;
940 this.rethrow(msg);
941};
942inherits(ReporterError, Error);
943
944ReporterError.prototype.rethrow = function rethrow(msg) {
945 this.message = msg + ' at: ' + (this.path || '(shallow)');
946 if (Error.captureStackTrace)
947 Error.captureStackTrace(this, ReporterError);
948
949 if (!this.stack) {
950 try {
951 // IE only adds stack when thrown
952 throw new Error(this.message);
953 } catch (e) {
954 this.stack = e.stack;
955 }
956 }
957 return this;
958};
959
960},{"inherits":116}],7:[function(require,module,exports){
961var constants = require('../constants');
962
963exports.tagClass = {
964 0: 'universal',
965 1: 'application',
966 2: 'context',
967 3: 'private'
968};
969exports.tagClassByName = constants._reverse(exports.tagClass);
970
971exports.tag = {
972 0x00: 'end',
973 0x01: 'bool',
974 0x02: 'int',
975 0x03: 'bitstr',
976 0x04: 'octstr',
977 0x05: 'null_',
978 0x06: 'objid',
979 0x07: 'objDesc',
980 0x08: 'external',
981 0x09: 'real',
982 0x0a: 'enum',
983 0x0b: 'embed',
984 0x0c: 'utf8str',
985 0x0d: 'relativeOid',
986 0x10: 'seq',
987 0x11: 'set',
988 0x12: 'numstr',
989 0x13: 'printstr',
990 0x14: 't61str',
991 0x15: 'videostr',
992 0x16: 'ia5str',
993 0x17: 'utctime',
994 0x18: 'gentime',
995 0x19: 'graphstr',
996 0x1a: 'iso646str',
997 0x1b: 'genstr',
998 0x1c: 'unistr',
999 0x1d: 'charstr',
1000 0x1e: 'bmpstr'
1001};
1002exports.tagByName = constants._reverse(exports.tag);
1003
1004},{"../constants":8}],8:[function(require,module,exports){
1005var constants = exports;
1006
1007// Helper
1008constants._reverse = function reverse(map) {
1009 var res = {};
1010
1011 Object.keys(map).forEach(function(key) {
1012 // Convert key to integer if it is stringified
1013 if ((key | 0) == key)
1014 key = key | 0;
1015
1016 var value = map[key];
1017 res[value] = key;
1018 });
1019
1020 return res;
1021};
1022
1023constants.der = require('./der');
1024
1025},{"./der":7}],9:[function(require,module,exports){
1026var inherits = require('inherits');
1027
1028var asn1 = require('../../asn1');
1029var base = asn1.base;
1030var bignum = asn1.bignum;
1031
1032// Import DER constants
1033var der = asn1.constants.der;
1034
1035function DERDecoder(entity) {
1036 this.enc = 'der';
1037 this.name = entity.name;
1038 this.entity = entity;
1039
1040 // Construct base tree
1041 this.tree = new DERNode();
1042 this.tree._init(entity.body);
1043};
1044module.exports = DERDecoder;
1045
1046DERDecoder.prototype.decode = function decode(data, options) {
1047 if (!(data instanceof base.DecoderBuffer))
1048 data = new base.DecoderBuffer(data, options);
1049
1050 return this.tree._decode(data, options);
1051};
1052
1053// Tree methods
1054
1055function DERNode(parent) {
1056 base.Node.call(this, 'der', parent);
1057}
1058inherits(DERNode, base.Node);
1059
1060DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
1061 if (buffer.isEmpty())
1062 return false;
1063
1064 var state = buffer.save();
1065 var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
1066 if (buffer.isError(decodedTag))
1067 return decodedTag;
1068
1069 buffer.restore(state);
1070
1071 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
1072 (decodedTag.tagStr + 'of') === tag || any;
1073};
1074
1075DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
1076 var decodedTag = derDecodeTag(buffer,
1077 'Failed to decode tag of "' + tag + '"');
1078 if (buffer.isError(decodedTag))
1079 return decodedTag;
1080
1081 var len = derDecodeLen(buffer,
1082 decodedTag.primitive,
1083 'Failed to get length of "' + tag + '"');
1084
1085 // Failure
1086 if (buffer.isError(len))
1087 return len;
1088
1089 if (!any &&
1090 decodedTag.tag !== tag &&
1091 decodedTag.tagStr !== tag &&
1092 decodedTag.tagStr + 'of' !== tag) {
1093 return buffer.error('Failed to match tag: "' + tag + '"');
1094 }
1095
1096 if (decodedTag.primitive || len !== null)
1097 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
1098
1099 // Indefinite length... find END tag
1100 var state = buffer.save();
1101 var res = this._skipUntilEnd(
1102 buffer,
1103 'Failed to skip indefinite length body: "' + this.tag + '"');
1104 if (buffer.isError(res))
1105 return res;
1106
1107 len = buffer.offset - state.offset;
1108 buffer.restore(state);
1109 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
1110};
1111
1112DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
1113 while (true) {
1114 var tag = derDecodeTag(buffer, fail);
1115 if (buffer.isError(tag))
1116 return tag;
1117 var len = derDecodeLen(buffer, tag.primitive, fail);
1118 if (buffer.isError(len))
1119 return len;
1120
1121 var res;
1122 if (tag.primitive || len !== null)
1123 res = buffer.skip(len)
1124 else
1125 res = this._skipUntilEnd(buffer, fail);
1126
1127 // Failure
1128 if (buffer.isError(res))
1129 return res;
1130
1131 if (tag.tagStr === 'end')
1132 break;
1133 }
1134};
1135
1136DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
1137 options) {
1138 var result = [];
1139 while (!buffer.isEmpty()) {
1140 var possibleEnd = this._peekTag(buffer, 'end');
1141 if (buffer.isError(possibleEnd))
1142 return possibleEnd;
1143
1144 var res = decoder.decode(buffer, 'der', options);
1145 if (buffer.isError(res) && possibleEnd)
1146 break;
1147 result.push(res);
1148 }
1149 return result;
1150};
1151
1152DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
1153 if (tag === 'bitstr') {
1154 var unused = buffer.readUInt8();
1155 if (buffer.isError(unused))
1156 return unused;
1157 return { unused: unused, data: buffer.raw() };
1158 } else if (tag === 'bmpstr') {
1159 var raw = buffer.raw();
1160 if (raw.length % 2 === 1)
1161 return buffer.error('Decoding of string type: bmpstr length mismatch');
1162
1163 var str = '';
1164 for (var i = 0; i < raw.length / 2; i++) {
1165 str += String.fromCharCode(raw.readUInt16BE(i * 2));
1166 }
1167 return str;
1168 } else if (tag === 'numstr') {
1169 var numstr = buffer.raw().toString('ascii');
1170 if (!this._isNumstr(numstr)) {
1171 return buffer.error('Decoding of string type: ' +
1172 'numstr unsupported characters');
1173 }
1174 return numstr;
1175 } else if (tag === 'octstr') {
1176 return buffer.raw();
1177 } else if (tag === 'objDesc') {
1178 return buffer.raw();
1179 } else if (tag === 'printstr') {
1180 var printstr = buffer.raw().toString('ascii');
1181 if (!this._isPrintstr(printstr)) {
1182 return buffer.error('Decoding of string type: ' +
1183 'printstr unsupported characters');
1184 }
1185 return printstr;
1186 } else if (/str$/.test(tag)) {
1187 return buffer.raw().toString();
1188 } else {
1189 return buffer.error('Decoding of string type: ' + tag + ' unsupported');
1190 }
1191};
1192
1193DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
1194 var result;
1195 var identifiers = [];
1196 var ident = 0;
1197 while (!buffer.isEmpty()) {
1198 var subident = buffer.readUInt8();
1199 ident <<= 7;
1200 ident |= subident & 0x7f;
1201 if ((subident & 0x80) === 0) {
1202 identifiers.push(ident);
1203 ident = 0;
1204 }
1205 }
1206 if (subident & 0x80)
1207 identifiers.push(ident);
1208
1209 var first = (identifiers[0] / 40) | 0;
1210 var second = identifiers[0] % 40;
1211
1212 if (relative)
1213 result = identifiers;
1214 else
1215 result = [first, second].concat(identifiers.slice(1));
1216
1217 if (values) {
1218 var tmp = values[result.join(' ')];
1219 if (tmp === undefined)
1220 tmp = values[result.join('.')];
1221 if (tmp !== undefined)
1222 result = tmp;
1223 }
1224
1225 return result;
1226};
1227
1228DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
1229 var str = buffer.raw().toString();
1230 if (tag === 'gentime') {
1231 var year = str.slice(0, 4) | 0;
1232 var mon = str.slice(4, 6) | 0;
1233 var day = str.slice(6, 8) | 0;
1234 var hour = str.slice(8, 10) | 0;
1235 var min = str.slice(10, 12) | 0;
1236 var sec = str.slice(12, 14) | 0;
1237 } else if (tag === 'utctime') {
1238 var year = str.slice(0, 2) | 0;
1239 var mon = str.slice(2, 4) | 0;
1240 var day = str.slice(4, 6) | 0;
1241 var hour = str.slice(6, 8) | 0;
1242 var min = str.slice(8, 10) | 0;
1243 var sec = str.slice(10, 12) | 0;
1244 if (year < 70)
1245 year = 2000 + year;
1246 else
1247 year = 1900 + year;
1248 } else {
1249 return buffer.error('Decoding ' + tag + ' time is not supported yet');
1250 }
1251
1252 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
1253};
1254
1255DERNode.prototype._decodeNull = function decodeNull(buffer) {
1256 return null;
1257};
1258
1259DERNode.prototype._decodeBool = function decodeBool(buffer) {
1260 var res = buffer.readUInt8();
1261 if (buffer.isError(res))
1262 return res;
1263 else
1264 return res !== 0;
1265};
1266
1267DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
1268 // Bigint, return as it is (assume big endian)
1269 var raw = buffer.raw();
1270 var res = new bignum(raw);
1271
1272 if (values)
1273 res = values[res.toString(10)] || res;
1274
1275 return res;
1276};
1277
1278DERNode.prototype._use = function use(entity, obj) {
1279 if (typeof entity === 'function')
1280 entity = entity(obj);
1281 return entity._getDecoder('der').tree;
1282};
1283
1284// Utility methods
1285
1286function derDecodeTag(buf, fail) {
1287 var tag = buf.readUInt8(fail);
1288 if (buf.isError(tag))
1289 return tag;
1290
1291 var cls = der.tagClass[tag >> 6];
1292 var primitive = (tag & 0x20) === 0;
1293
1294 // Multi-octet tag - load
1295 if ((tag & 0x1f) === 0x1f) {
1296 var oct = tag;
1297 tag = 0;
1298 while ((oct & 0x80) === 0x80) {
1299 oct = buf.readUInt8(fail);
1300 if (buf.isError(oct))
1301 return oct;
1302
1303 tag <<= 7;
1304 tag |= oct & 0x7f;
1305 }
1306 } else {
1307 tag &= 0x1f;
1308 }
1309 var tagStr = der.tag[tag];
1310
1311 return {
1312 cls: cls,
1313 primitive: primitive,
1314 tag: tag,
1315 tagStr: tagStr
1316 };
1317}
1318
1319function derDecodeLen(buf, primitive, fail) {
1320 var len = buf.readUInt8(fail);
1321 if (buf.isError(len))
1322 return len;
1323
1324 // Indefinite form
1325 if (!primitive && len === 0x80)
1326 return null;
1327
1328 // Definite form
1329 if ((len & 0x80) === 0) {
1330 // Short form
1331 return len;
1332 }
1333
1334 // Long form
1335 var num = len & 0x7f;
1336 if (num > 4)
1337 return buf.error('length octect is too long');
1338
1339 len = 0;
1340 for (var i = 0; i < num; i++) {
1341 len <<= 8;
1342 var j = buf.readUInt8(fail);
1343 if (buf.isError(j))
1344 return j;
1345 len |= j;
1346 }
1347
1348 return len;
1349}
1350
1351},{"../../asn1":1,"inherits":116}],10:[function(require,module,exports){
1352var decoders = exports;
1353
1354decoders.der = require('./der');
1355decoders.pem = require('./pem');
1356
1357},{"./der":9,"./pem":11}],11:[function(require,module,exports){
1358var inherits = require('inherits');
1359var Buffer = require('buffer').Buffer;
1360
1361var DERDecoder = require('./der');
1362
1363function PEMDecoder(entity) {
1364 DERDecoder.call(this, entity);
1365 this.enc = 'pem';
1366};
1367inherits(PEMDecoder, DERDecoder);
1368module.exports = PEMDecoder;
1369
1370PEMDecoder.prototype.decode = function decode(data, options) {
1371 var lines = data.toString().split(/[\r\n]+/g);
1372
1373 var label = options.label.toUpperCase();
1374
1375 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
1376 var start = -1;
1377 var end = -1;
1378 for (var i = 0; i < lines.length; i++) {
1379 var match = lines[i].match(re);
1380 if (match === null)
1381 continue;
1382
1383 if (match[2] !== label)
1384 continue;
1385
1386 if (start === -1) {
1387 if (match[1] !== 'BEGIN')
1388 break;
1389 start = i;
1390 } else {
1391 if (match[1] !== 'END')
1392 break;
1393 end = i;
1394 break;
1395 }
1396 }
1397 if (start === -1 || end === -1)
1398 throw new Error('PEM section not found for: ' + label);
1399
1400 var base64 = lines.slice(start + 1, end).join('');
1401 // Remove excessive symbols
1402 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
1403
1404 var input = new Buffer(base64, 'base64');
1405 return DERDecoder.prototype.decode.call(this, input, options);
1406};
1407
1408},{"./der":9,"buffer":49,"inherits":116}],12:[function(require,module,exports){
1409var inherits = require('inherits');
1410var Buffer = require('buffer').Buffer;
1411
1412var asn1 = require('../../asn1');
1413var base = asn1.base;
1414
1415// Import DER constants
1416var der = asn1.constants.der;
1417
1418function DEREncoder(entity) {
1419 this.enc = 'der';
1420 this.name = entity.name;
1421 this.entity = entity;
1422
1423 // Construct base tree
1424 this.tree = new DERNode();
1425 this.tree._init(entity.body);
1426};
1427module.exports = DEREncoder;
1428
1429DEREncoder.prototype.encode = function encode(data, reporter) {
1430 return this.tree._encode(data, reporter).join();
1431};
1432
1433// Tree methods
1434
1435function DERNode(parent) {
1436 base.Node.call(this, 'der', parent);
1437}
1438inherits(DERNode, base.Node);
1439
1440DERNode.prototype._encodeComposite = function encodeComposite(tag,
1441 primitive,
1442 cls,
1443 content) {
1444 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
1445
1446 // Short form
1447 if (content.length < 0x80) {
1448 var header = new Buffer(2);
1449 header[0] = encodedTag;
1450 header[1] = content.length;
1451 return this._createEncoderBuffer([ header, content ]);
1452 }
1453
1454 // Long form
1455 // Count octets required to store length
1456 var lenOctets = 1;
1457 for (var i = content.length; i >= 0x100; i >>= 8)
1458 lenOctets++;
1459
1460 var header = new Buffer(1 + 1 + lenOctets);
1461 header[0] = encodedTag;
1462 header[1] = 0x80 | lenOctets;
1463
1464 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
1465 header[i] = j & 0xff;
1466
1467 return this._createEncoderBuffer([ header, content ]);
1468};
1469
1470DERNode.prototype._encodeStr = function encodeStr(str, tag) {
1471 if (tag === 'bitstr') {
1472 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
1473 } else if (tag === 'bmpstr') {
1474 var buf = new Buffer(str.length * 2);
1475 for (var i = 0; i < str.length; i++) {
1476 buf.writeUInt16BE(str.charCodeAt(i), i * 2);
1477 }
1478 return this._createEncoderBuffer(buf);
1479 } else if (tag === 'numstr') {
1480 if (!this._isNumstr(str)) {
1481 return this.reporter.error('Encoding of string type: numstr supports ' +
1482 'only digits and space');
1483 }
1484 return this._createEncoderBuffer(str);
1485 } else if (tag === 'printstr') {
1486 if (!this._isPrintstr(str)) {
1487 return this.reporter.error('Encoding of string type: printstr supports ' +
1488 'only latin upper and lower case letters, ' +
1489 'digits, space, apostrophe, left and rigth ' +
1490 'parenthesis, plus sign, comma, hyphen, ' +
1491 'dot, slash, colon, equal sign, ' +
1492 'question mark');
1493 }
1494 return this._createEncoderBuffer(str);
1495 } else if (/str$/.test(tag)) {
1496 return this._createEncoderBuffer(str);
1497 } else if (tag === 'objDesc') {
1498 return this._createEncoderBuffer(str);
1499 } else {
1500 return this.reporter.error('Encoding of string type: ' + tag +
1501 ' unsupported');
1502 }
1503};
1504
1505DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
1506 if (typeof id === 'string') {
1507 if (!values)
1508 return this.reporter.error('string objid given, but no values map found');
1509 if (!values.hasOwnProperty(id))
1510 return this.reporter.error('objid not found in values map');
1511 id = values[id].split(/[\s\.]+/g);
1512 for (var i = 0; i < id.length; i++)
1513 id[i] |= 0;
1514 } else if (Array.isArray(id)) {
1515 id = id.slice();
1516 for (var i = 0; i < id.length; i++)
1517 id[i] |= 0;
1518 }
1519
1520 if (!Array.isArray(id)) {
1521 return this.reporter.error('objid() should be either array or string, ' +
1522 'got: ' + JSON.stringify(id));
1523 }
1524
1525 if (!relative) {
1526 if (id[1] >= 40)
1527 return this.reporter.error('Second objid identifier OOB');
1528 id.splice(0, 2, id[0] * 40 + id[1]);
1529 }
1530
1531 // Count number of octets
1532 var size = 0;
1533 for (var i = 0; i < id.length; i++) {
1534 var ident = id[i];
1535 for (size++; ident >= 0x80; ident >>= 7)
1536 size++;
1537 }
1538
1539 var objid = new Buffer(size);
1540 var offset = objid.length - 1;
1541 for (var i = id.length - 1; i >= 0; i--) {
1542 var ident = id[i];
1543 objid[offset--] = ident & 0x7f;
1544 while ((ident >>= 7) > 0)
1545 objid[offset--] = 0x80 | (ident & 0x7f);
1546 }
1547
1548 return this._createEncoderBuffer(objid);
1549};
1550
1551function two(num) {
1552 if (num < 10)
1553 return '0' + num;
1554 else
1555 return num;
1556}
1557
1558DERNode.prototype._encodeTime = function encodeTime(time, tag) {
1559 var str;
1560 var date = new Date(time);
1561
1562 if (tag === 'gentime') {
1563 str = [
1564 two(date.getFullYear()),
1565 two(date.getUTCMonth() + 1),
1566 two(date.getUTCDate()),
1567 two(date.getUTCHours()),
1568 two(date.getUTCMinutes()),
1569 two(date.getUTCSeconds()),
1570 'Z'
1571 ].join('');
1572 } else if (tag === 'utctime') {
1573 str = [
1574 two(date.getFullYear() % 100),
1575 two(date.getUTCMonth() + 1),
1576 two(date.getUTCDate()),
1577 two(date.getUTCHours()),
1578 two(date.getUTCMinutes()),
1579 two(date.getUTCSeconds()),
1580 'Z'
1581 ].join('');
1582 } else {
1583 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
1584 }
1585
1586 return this._encodeStr(str, 'octstr');
1587};
1588
1589DERNode.prototype._encodeNull = function encodeNull() {
1590 return this._createEncoderBuffer('');
1591};
1592
1593DERNode.prototype._encodeInt = function encodeInt(num, values) {
1594 if (typeof num === 'string') {
1595 if (!values)
1596 return this.reporter.error('String int or enum given, but no values map');
1597 if (!values.hasOwnProperty(num)) {
1598 return this.reporter.error('Values map doesn\'t contain: ' +
1599 JSON.stringify(num));
1600 }
1601 num = values[num];
1602 }
1603
1604 // Bignum, assume big endian
1605 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
1606 var numArray = num.toArray();
1607 if (!num.sign && numArray[0] & 0x80) {
1608 numArray.unshift(0);
1609 }
1610 num = new Buffer(numArray);
1611 }
1612
1613 if (Buffer.isBuffer(num)) {
1614 var size = num.length;
1615 if (num.length === 0)
1616 size++;
1617
1618 var out = new Buffer(size);
1619 num.copy(out);
1620 if (num.length === 0)
1621 out[0] = 0
1622 return this._createEncoderBuffer(out);
1623 }
1624
1625 if (num < 0x80)
1626 return this._createEncoderBuffer(num);
1627
1628 if (num < 0x100)
1629 return this._createEncoderBuffer([0, num]);
1630
1631 var size = 1;
1632 for (var i = num; i >= 0x100; i >>= 8)
1633 size++;
1634
1635 var out = new Array(size);
1636 for (var i = out.length - 1; i >= 0; i--) {
1637 out[i] = num & 0xff;
1638 num >>= 8;
1639 }
1640 if(out[0] & 0x80) {
1641 out.unshift(0);
1642 }
1643
1644 return this._createEncoderBuffer(new Buffer(out));
1645};
1646
1647DERNode.prototype._encodeBool = function encodeBool(value) {
1648 return this._createEncoderBuffer(value ? 0xff : 0);
1649};
1650
1651DERNode.prototype._use = function use(entity, obj) {
1652 if (typeof entity === 'function')
1653 entity = entity(obj);
1654 return entity._getEncoder('der').tree;
1655};
1656
1657DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
1658 var state = this._baseState;
1659 var i;
1660 if (state['default'] === null)
1661 return false;
1662
1663 var data = dataBuffer.join();
1664 if (state.defaultBuffer === undefined)
1665 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
1666
1667 if (data.length !== state.defaultBuffer.length)
1668 return false;
1669
1670 for (i=0; i < data.length; i++)
1671 if (data[i] !== state.defaultBuffer[i])
1672 return false;
1673
1674 return true;
1675};
1676
1677// Utility methods
1678
1679function encodeTag(tag, primitive, cls, reporter) {
1680 var res;
1681
1682 if (tag === 'seqof')
1683 tag = 'seq';
1684 else if (tag === 'setof')
1685 tag = 'set';
1686
1687 if (der.tagByName.hasOwnProperty(tag))
1688 res = der.tagByName[tag];
1689 else if (typeof tag === 'number' && (tag | 0) === tag)
1690 res = tag;
1691 else
1692 return reporter.error('Unknown tag: ' + tag);
1693
1694 if (res >= 0x1f)
1695 return reporter.error('Multi-octet tag encoding unsupported');
1696
1697 if (!primitive)
1698 res |= 0x20;
1699
1700 res |= (der.tagClassByName[cls || 'universal'] << 6);
1701
1702 return res;
1703}
1704
1705},{"../../asn1":1,"buffer":49,"inherits":116}],13:[function(require,module,exports){
1706var encoders = exports;
1707
1708encoders.der = require('./der');
1709encoders.pem = require('./pem');
1710
1711},{"./der":12,"./pem":14}],14:[function(require,module,exports){
1712var inherits = require('inherits');
1713
1714var DEREncoder = require('./der');
1715
1716function PEMEncoder(entity) {
1717 DEREncoder.call(this, entity);
1718 this.enc = 'pem';
1719};
1720inherits(PEMEncoder, DEREncoder);
1721module.exports = PEMEncoder;
1722
1723PEMEncoder.prototype.encode = function encode(data, options) {
1724 var buf = DEREncoder.prototype.encode.call(this, data);
1725
1726 var p = buf.toString('base64');
1727 var out = [ '-----BEGIN ' + options.label + '-----' ];
1728 for (var i = 0; i < p.length; i += 64)
1729 out.push(p.slice(i, i + 64));
1730 out.push('-----END ' + options.label + '-----');
1731 return out.join('\n');
1732};
1733
1734},{"./der":12,"inherits":116}],15:[function(require,module,exports){
1735"use strict";
1736
1737/**
1738 * Generate a character map.
1739 * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
1740 * @param {object} mappings map overrides from key to value
1741 * @method
1742 */
1743
1744var charmap = function (alphabet, mappings) {
1745 mappings || (mappings = {});
1746 alphabet.split("").forEach(function (c, i) {
1747 if (!(c in mappings)) mappings[c] = i;
1748 });
1749 return mappings;
1750}
1751
1752/**
1753 * The RFC 4648 base 32 alphabet and character map.
1754 * @see {@link https://tools.ietf.org/html/rfc4648}
1755 */
1756
1757var rfc4648 = {
1758 alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
1759 charmap: {
1760 0: 14,
1761 1: 8
1762 }
1763};
1764
1765rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap);
1766
1767/**
1768 * The Crockford base 32 alphabet and character map.
1769 * @see {@link http://www.crockford.com/wrmg/base32.html}
1770 */
1771
1772var crockford = {
1773 alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ",
1774 charmap: {
1775 O: 0,
1776 I: 1,
1777 L: 1
1778 }
1779};
1780
1781crockford.charmap = charmap(crockford.alphabet, crockford.charmap);
1782
1783/**
1784 * base32hex
1785 * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex}
1786 */
1787
1788var base32hex = {
1789 alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
1790 charmap: {}
1791};
1792
1793base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap);
1794
1795/**
1796 * Create a new `Decoder` with the given options.
1797 *
1798 * @param {object} [options]
1799 * @param {string} [type] Supported Base-32 variants are "rfc4648" and
1800 * "crockford".
1801 * @param {object} [charmap] Override the character map used in decoding.
1802 * @constructor
1803 */
1804
1805function Decoder (options) {
1806 this.buf = [];
1807 this.shift = 8;
1808 this.carry = 0;
1809
1810 if (options) {
1811
1812 switch (options.type) {
1813 case "rfc4648":
1814 this.charmap = exports.rfc4648.charmap;
1815 break;
1816 case "crockford":
1817 this.charmap = exports.crockford.charmap;
1818 break;
1819 case "base32hex":
1820 this.charmap = exports.base32hex.charmap;
1821 break;
1822 default:
1823 throw new Error("invalid type");
1824 }
1825
1826 if (options.charmap) this.charmap = options.charmap;
1827 }
1828}
1829
1830/**
1831 * The default character map coresponds to RFC4648.
1832 */
1833
1834Decoder.prototype.charmap = rfc4648.charmap;
1835
1836/**
1837 * Decode a string, continuing from the previous state.
1838 *
1839 * @param {string} str
1840 * @return {Decoder} this
1841 */
1842
1843Decoder.prototype.write = function (str) {
1844 var charmap = this.charmap;
1845 var buf = this.buf;
1846 var shift = this.shift;
1847 var carry = this.carry;
1848
1849 // decode string
1850 str.toUpperCase().split("").forEach(function (char) {
1851
1852 // ignore padding
1853 if (char == "=") return;
1854
1855 // lookup symbol
1856 var symbol = charmap[char] & 0xff;
1857
1858 // 1: 00000 000
1859 // 2: 00 00000 0
1860 // 3: 0000 0000
1861 // 4: 0 00000 00
1862 // 5: 000 00000
1863 // 6: 00000 000
1864 // 7: 00 00000 0
1865
1866 shift -= 5;
1867 if (shift > 0) {
1868 carry |= symbol << shift;
1869 } else if (shift < 0) {
1870 buf.push(carry | (symbol >> -shift));
1871 shift += 8;
1872 carry = (symbol << shift) & 0xff;
1873 } else {
1874 buf.push(carry | symbol);
1875 shift = 8;
1876 carry = 0;
1877 }
1878 });
1879
1880 // save state
1881 this.shift = shift;
1882 this.carry = carry;
1883
1884 // for chaining
1885 return this;
1886};
1887
1888/**
1889 * Finish decoding.
1890 *
1891 * @param {string} [str] The final string to decode.
1892 * @return {Array} Decoded byte array.
1893 */
1894
1895Decoder.prototype.finalize = function (str) {
1896 if (str) {
1897 this.write(str);
1898 }
1899 if (this.shift !== 8 && this.carry !== 0) {
1900 this.buf.push(this.carry);
1901 this.shift = 8;
1902 this.carry = 0;
1903 }
1904 return this.buf;
1905};
1906
1907/**
1908 * Create a new `Encoder` with the given options.
1909 *
1910 * @param {object} [options]
1911 * @param {string} [type] Supported Base-32 variants are "rfc4648" and
1912 * "crockford".
1913 * @param {object} [alphabet] Override the alphabet used in encoding.
1914 * @constructor
1915 */
1916
1917function Encoder (options) {
1918 this.buf = "";
1919 this.shift = 3;
1920 this.carry = 0;
1921
1922 if (options) {
1923
1924 switch (options.type) {
1925 case "rfc4648":
1926 this.alphabet = exports.rfc4648.alphabet;
1927 break;
1928 case "crockford":
1929 this.alphabet = exports.crockford.alphabet;
1930 break;
1931 case "base32hex":
1932 this.alphabet = exports.base32hex.alphabet;
1933 break;
1934 default:
1935 throw new Error("invalid type");
1936 }
1937
1938 if (options.alphabet) this.alphabet = options.alphabet;
1939 else if (options.lc) this.alphabet = this.alphabet.toLowerCase();
1940 }
1941}
1942
1943/**
1944 * The default alphabet coresponds to RFC4648.
1945 */
1946
1947Encoder.prototype.alphabet = rfc4648.alphabet;
1948
1949/**
1950 * Encode a byte array, continuing from the previous state.
1951 *
1952 * @param {byte[]} buf The byte array to encode.
1953 * @return {Encoder} this
1954 */
1955
1956Encoder.prototype.write = function (buf) {
1957 var shift = this.shift;
1958 var carry = this.carry;
1959 var symbol;
1960 var byte;
1961 var i;
1962
1963 // encode each byte in buf
1964 for (i = 0; i < buf.length; i++) {
1965 byte = buf[i];
1966
1967 // 1: 00000 000
1968 // 2: 00 00000 0
1969 // 3: 0000 0000
1970 // 4: 0 00000 00
1971 // 5: 000 00000
1972 // 6: 00000 000
1973 // 7: 00 00000 0
1974
1975 symbol = carry | (byte >> shift);
1976 this.buf += this.alphabet[symbol & 0x1f];
1977
1978 if (shift > 5) {
1979 shift -= 5;
1980 symbol = byte >> shift;
1981 this.buf += this.alphabet[symbol & 0x1f];
1982 }
1983
1984 shift = 5 - shift;
1985 carry = byte << shift;
1986 shift = 8 - shift;
1987 }
1988
1989 // save state
1990 this.shift = shift;
1991 this.carry = carry;
1992
1993 // for chaining
1994 return this;
1995};
1996
1997/**
1998 * Finish encoding.
1999 *
2000 * @param {byte[]} [buf] The final byte array to encode.
2001 * @return {string} The encoded byte array.
2002 */
2003
2004Encoder.prototype.finalize = function (buf) {
2005 if (buf) {
2006 this.write(buf);
2007 }
2008 if (this.shift !== 3) {
2009 this.buf += this.alphabet[this.carry & 0x1f];
2010 this.shift = 3;
2011 this.carry = 0;
2012 }
2013 return this.buf;
2014};
2015
2016/**
2017 * Convenience encoder.
2018 *
2019 * @param {byte[]} buf The byte array to encode.
2020 * @param {object} [options] Options to pass to the encoder.
2021 * @return {string} The encoded string.
2022 */
2023
2024exports.encode = function (buf, options) {
2025 return new Encoder(options).finalize(buf);
2026};
2027
2028/**
2029 * Convenience decoder.
2030 *
2031 * @param {string} str The string to decode.
2032 * @param {object} [options] Options to pass to the decoder.
2033 * @return {byte[]} The decoded byte array.
2034 */
2035
2036exports.decode = function (str, options) {
2037 return new Decoder(options).finalize(str);
2038};
2039
2040// Exports.
2041exports.Decoder = Decoder;
2042exports.Encoder = Encoder;
2043exports.charmap = charmap;
2044exports.crockford = crockford;
2045exports.rfc4648 = rfc4648;
2046exports.base32hex = base32hex;
2047
2048},{}],16:[function(require,module,exports){
2049'use strict'
2050
2051exports.byteLength = byteLength
2052exports.toByteArray = toByteArray
2053exports.fromByteArray = fromByteArray
2054
2055var lookup = []
2056var revLookup = []
2057var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
2058
2059var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
2060for (var i = 0, len = code.length; i < len; ++i) {
2061 lookup[i] = code[i]
2062 revLookup[code.charCodeAt(i)] = i
2063}
2064
2065// Support decoding URL-safe base64 strings, as Node.js does.
2066// See: https://en.wikipedia.org/wiki/Base64#URL_applications
2067revLookup['-'.charCodeAt(0)] = 62
2068revLookup['_'.charCodeAt(0)] = 63
2069
2070function getLens (b64) {
2071 var len = b64.length
2072
2073 if (len % 4 > 0) {
2074 throw new Error('Invalid string. Length must be a multiple of 4')
2075 }
2076
2077 // Trim off extra bytes after placeholder bytes are found
2078 // See: https://github.com/beatgammit/base64-js/issues/42
2079 var validLen = b64.indexOf('=')
2080 if (validLen === -1) validLen = len
2081
2082 var placeHoldersLen = validLen === len
2083 ? 0
2084 : 4 - (validLen % 4)
2085
2086 return [validLen, placeHoldersLen]
2087}
2088
2089// base64 is 4/3 + up to two characters of the original data
2090function byteLength (b64) {
2091 var lens = getLens(b64)
2092 var validLen = lens[0]
2093 var placeHoldersLen = lens[1]
2094 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
2095}
2096
2097function _byteLength (b64, validLen, placeHoldersLen) {
2098 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
2099}
2100
2101function toByteArray (b64) {
2102 var tmp
2103 var lens = getLens(b64)
2104 var validLen = lens[0]
2105 var placeHoldersLen = lens[1]
2106
2107 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
2108
2109 var curByte = 0
2110
2111 // if there are placeholders, only get up to the last complete 4 chars
2112 var len = placeHoldersLen > 0
2113 ? validLen - 4
2114 : validLen
2115
2116 for (var i = 0; i < len; i += 4) {
2117 tmp =
2118 (revLookup[b64.charCodeAt(i)] << 18) |
2119 (revLookup[b64.charCodeAt(i + 1)] << 12) |
2120 (revLookup[b64.charCodeAt(i + 2)] << 6) |
2121 revLookup[b64.charCodeAt(i + 3)]
2122 arr[curByte++] = (tmp >> 16) & 0xFF
2123 arr[curByte++] = (tmp >> 8) & 0xFF
2124 arr[curByte++] = tmp & 0xFF
2125 }
2126
2127 if (placeHoldersLen === 2) {
2128 tmp =
2129 (revLookup[b64.charCodeAt(i)] << 2) |
2130 (revLookup[b64.charCodeAt(i + 1)] >> 4)
2131 arr[curByte++] = tmp & 0xFF
2132 }
2133
2134 if (placeHoldersLen === 1) {
2135 tmp =
2136 (revLookup[b64.charCodeAt(i)] << 10) |
2137 (revLookup[b64.charCodeAt(i + 1)] << 4) |
2138 (revLookup[b64.charCodeAt(i + 2)] >> 2)
2139 arr[curByte++] = (tmp >> 8) & 0xFF
2140 arr[curByte++] = tmp & 0xFF
2141 }
2142
2143 return arr
2144}
2145
2146function tripletToBase64 (num) {
2147 return lookup[num >> 18 & 0x3F] +
2148 lookup[num >> 12 & 0x3F] +
2149 lookup[num >> 6 & 0x3F] +
2150 lookup[num & 0x3F]
2151}
2152
2153function encodeChunk (uint8, start, end) {
2154 var tmp
2155 var output = []
2156 for (var i = start; i < end; i += 3) {
2157 tmp =
2158 ((uint8[i] << 16) & 0xFF0000) +
2159 ((uint8[i + 1] << 8) & 0xFF00) +
2160 (uint8[i + 2] & 0xFF)
2161 output.push(tripletToBase64(tmp))
2162 }
2163 return output.join('')
2164}
2165
2166function fromByteArray (uint8) {
2167 var tmp
2168 var len = uint8.length
2169 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
2170 var parts = []
2171 var maxChunkLength = 16383 // must be multiple of 3
2172
2173 // go through the array every three bytes, we'll deal with trailing stuff later
2174 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
2175 parts.push(encodeChunk(
2176 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
2177 ))
2178 }
2179
2180 // pad the end with zeros, but make sure to not forget the extra bytes
2181 if (extraBytes === 1) {
2182 tmp = uint8[len - 1]
2183 parts.push(
2184 lookup[tmp >> 2] +
2185 lookup[(tmp << 4) & 0x3F] +
2186 '=='
2187 )
2188 } else if (extraBytes === 2) {
2189 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
2190 parts.push(
2191 lookup[tmp >> 10] +
2192 lookup[(tmp >> 4) & 0x3F] +
2193 lookup[(tmp << 2) & 0x3F] +
2194 '='
2195 )
2196 }
2197
2198 return parts.join('')
2199}
2200
2201},{}],17:[function(require,module,exports){
2202/*! bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
2203
2204;(function (globalObj) {
2205 'use strict';
2206
2207 /*
2208 bignumber.js v4.1.0
2209 A JavaScript library for arbitrary-precision arithmetic.
2210 https://github.com/MikeMcl/bignumber.js
2211 Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
2212 MIT Expat Licence
2213 */
2214
2215
2216 var BigNumber,
2217 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
2218 mathceil = Math.ceil,
2219 mathfloor = Math.floor,
2220 notBool = ' not a boolean or binary digit',
2221 roundingMode = 'rounding mode',
2222 tooManyDigits = 'number type has more than 15 significant digits',
2223 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
2224 BASE = 1e14,
2225 LOG_BASE = 14,
2226 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
2227 // MAX_INT32 = 0x7fffffff, // 2^31 - 1
2228 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
2229 SQRT_BASE = 1e7,
2230
2231 /*
2232 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
2233 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
2234 * exception is thrown (if ERRORS is true).
2235 */
2236 MAX = 1E9; // 0 to MAX_INT32
2237
2238
2239 /*
2240 * Create and return a BigNumber constructor.
2241 */
2242 function constructorFactory(config) {
2243 var div, parseNumeric,
2244
2245 // id tracks the caller function, so its name can be included in error messages.
2246 id = 0,
2247 P = BigNumber.prototype,
2248 ONE = new BigNumber(1),
2249
2250
2251 /********************************* EDITABLE DEFAULTS **********************************/
2252
2253
2254 /*
2255 * The default values below must be integers within the inclusive ranges stated.
2256 * The values can also be changed at run-time using BigNumber.config.
2257 */
2258
2259 // The maximum number of decimal places for operations involving division.
2260 DECIMAL_PLACES = 20, // 0 to MAX
2261
2262 /*
2263 * The rounding mode used when rounding to the above decimal places, and when using
2264 * toExponential, toFixed, toFormat and toPrecision, and round (default value).
2265 * UP 0 Away from zero.
2266 * DOWN 1 Towards zero.
2267 * CEIL 2 Towards +Infinity.
2268 * FLOOR 3 Towards -Infinity.
2269 * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
2270 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
2271 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
2272 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
2273 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
2274 */
2275 ROUNDING_MODE = 4, // 0 to 8
2276
2277 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
2278
2279 // The exponent value at and beneath which toString returns exponential notation.
2280 // Number type: -7
2281 TO_EXP_NEG = -7, // 0 to -MAX
2282
2283 // The exponent value at and above which toString returns exponential notation.
2284 // Number type: 21
2285 TO_EXP_POS = 21, // 0 to MAX
2286
2287 // RANGE : [MIN_EXP, MAX_EXP]
2288
2289 // The minimum exponent value, beneath which underflow to zero occurs.
2290 // Number type: -324 (5e-324)
2291 MIN_EXP = -1e7, // -1 to -MAX
2292
2293 // The maximum exponent value, above which overflow to Infinity occurs.
2294 // Number type: 308 (1.7976931348623157e+308)
2295 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
2296 MAX_EXP = 1e7, // 1 to MAX
2297
2298 // Whether BigNumber Errors are ever thrown.
2299 ERRORS = true, // true or false
2300
2301 // Change to intValidatorNoErrors if ERRORS is false.
2302 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
2303
2304 // Whether to use cryptographically-secure random number generation, if available.
2305 CRYPTO = false, // true or false
2306
2307 /*
2308 * The modulo mode used when calculating the modulus: a mod n.
2309 * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
2310 * The remainder (r) is calculated as: r = a - n * q.
2311 *
2312 * UP 0 The remainder is positive if the dividend is negative, else is negative.
2313 * DOWN 1 The remainder has the same sign as the dividend.
2314 * This modulo mode is commonly known as 'truncated division' and is
2315 * equivalent to (a % n) in JavaScript.
2316 * FLOOR 3 The remainder has the same sign as the divisor (Python %).
2317 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
2318 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
2319 * The remainder is always positive.
2320 *
2321 * The truncated division, floored division, Euclidian division and IEEE 754 remainder
2322 * modes are commonly used for the modulus operation.
2323 * Although the other rounding modes can also be used, they may not give useful results.
2324 */
2325 MODULO_MODE = 1, // 0 to 9
2326
2327 // The maximum number of significant digits of the result of the toPower operation.
2328 // If POW_PRECISION is 0, there will be unlimited significant digits.
2329 POW_PRECISION = 0, // 0 to MAX
2330
2331 // The format specification used by the BigNumber.prototype.toFormat method.
2332 FORMAT = {
2333 decimalSeparator: '.',
2334 groupSeparator: ',',
2335 groupSize: 3,
2336 secondaryGroupSize: 0,
2337 fractionGroupSeparator: '\xA0', // non-breaking space
2338 fractionGroupSize: 0
2339 };
2340
2341
2342 /******************************************************************************************/
2343
2344
2345 // CONSTRUCTOR
2346
2347
2348 /*
2349 * The BigNumber constructor and exported function.
2350 * Create and return a new instance of a BigNumber object.
2351 *
2352 * n {number|string|BigNumber} A numeric value.
2353 * [b] {number} The base of n. Integer, 2 to 64 inclusive.
2354 */
2355 function BigNumber( n, b ) {
2356 var c, e, i, num, len, str,
2357 x = this;
2358
2359 // Enable constructor usage without new.
2360 if ( !( x instanceof BigNumber ) ) {
2361
2362 // 'BigNumber() constructor call without new: {n}'
2363 if (ERRORS) raise( 26, 'constructor call without new', n );
2364 return new BigNumber( n, b );
2365 }
2366
2367 // 'new BigNumber() base not an integer: {b}'
2368 // 'new BigNumber() base out of range: {b}'
2369 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
2370
2371 // Duplicate.
2372 if ( n instanceof BigNumber ) {
2373 x.s = n.s;
2374 x.e = n.e;
2375 x.c = ( n = n.c ) ? n.slice() : n;
2376 id = 0;
2377 return;
2378 }
2379
2380 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
2381 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
2382
2383 // Fast path for integers.
2384 if ( n === ~~n ) {
2385 for ( e = 0, i = n; i >= 10; i /= 10, e++ );
2386 x.e = e;
2387 x.c = [n];
2388 id = 0;
2389 return;
2390 }
2391
2392 str = n + '';
2393 } else {
2394 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
2395 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
2396 }
2397 } else {
2398 b = b | 0;
2399 str = n + '';
2400
2401 // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
2402 // Allow exponential notation to be used with base 10 argument.
2403 if ( b == 10 ) {
2404 x = new BigNumber( n instanceof BigNumber ? n : str );
2405 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
2406 }
2407
2408 // Avoid potential interpretation of Infinity and NaN as base 44+ values.
2409 // Any number in exponential form will fail due to the [Ee][+-].
2410 if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
2411 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
2412 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
2413 return parseNumeric( x, str, num, b );
2414 }
2415
2416 if (num) {
2417 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
2418
2419 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
2420
2421 // 'new BigNumber() number type has more than 15 significant digits: {n}'
2422 raise( id, tooManyDigits, n );
2423 }
2424
2425 // Prevent later check for length on converted number.
2426 num = false;
2427 } else {
2428 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
2429 }
2430
2431 str = convertBase( str, 10, b, x.s );
2432 }
2433
2434 // Decimal point?
2435 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
2436
2437 // Exponential form?
2438 if ( ( i = str.search( /e/i ) ) > 0 ) {
2439
2440 // Determine exponent.
2441 if ( e < 0 ) e = i;
2442 e += +str.slice( i + 1 );
2443 str = str.substring( 0, i );
2444 } else if ( e < 0 ) {
2445
2446 // Integer.
2447 e = str.length;
2448 }
2449
2450 // Determine leading zeros.
2451 for ( i = 0; str.charCodeAt(i) === 48; i++ );
2452
2453 // Determine trailing zeros.
2454 for ( len = str.length; str.charCodeAt(--len) === 48; );
2455 str = str.slice( i, len + 1 );
2456
2457 if (str) {
2458 len = str.length;
2459
2460 // Disallow numbers with over 15 significant digits if number type.
2461 // 'new BigNumber() number type has more than 15 significant digits: {n}'
2462 if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
2463 raise( id, tooManyDigits, x.s * n );
2464 }
2465
2466 e = e - i - 1;
2467
2468 // Overflow?
2469 if ( e > MAX_EXP ) {
2470
2471 // Infinity.
2472 x.c = x.e = null;
2473
2474 // Underflow?
2475 } else if ( e < MIN_EXP ) {
2476
2477 // Zero.
2478 x.c = [ x.e = 0 ];
2479 } else {
2480 x.e = e;
2481 x.c = [];
2482
2483 // Transform base
2484
2485 // e is the base 10 exponent.
2486 // i is where to slice str to get the first element of the coefficient array.
2487 i = ( e + 1 ) % LOG_BASE;
2488 if ( e < 0 ) i += LOG_BASE;
2489
2490 if ( i < len ) {
2491 if (i) x.c.push( +str.slice( 0, i ) );
2492
2493 for ( len -= LOG_BASE; i < len; ) {
2494 x.c.push( +str.slice( i, i += LOG_BASE ) );
2495 }
2496
2497 str = str.slice(i);
2498 i = LOG_BASE - str.length;
2499 } else {
2500 i -= len;
2501 }
2502
2503 for ( ; i--; str += '0' );
2504 x.c.push( +str );
2505 }
2506 } else {
2507
2508 // Zero.
2509 x.c = [ x.e = 0 ];
2510 }
2511
2512 id = 0;
2513 }
2514
2515
2516 // CONSTRUCTOR PROPERTIES
2517
2518
2519 BigNumber.another = constructorFactory;
2520
2521 BigNumber.ROUND_UP = 0;
2522 BigNumber.ROUND_DOWN = 1;
2523 BigNumber.ROUND_CEIL = 2;
2524 BigNumber.ROUND_FLOOR = 3;
2525 BigNumber.ROUND_HALF_UP = 4;
2526 BigNumber.ROUND_HALF_DOWN = 5;
2527 BigNumber.ROUND_HALF_EVEN = 6;
2528 BigNumber.ROUND_HALF_CEIL = 7;
2529 BigNumber.ROUND_HALF_FLOOR = 8;
2530 BigNumber.EUCLID = 9;
2531
2532
2533 /*
2534 * Configure infrequently-changing library-wide settings.
2535 *
2536 * Accept an object or an argument list, with one or many of the following properties or
2537 * parameters respectively:
2538 *
2539 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
2540 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
2541 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
2542 * [integer -MAX to 0 incl., 0 to MAX incl.]
2543 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
2544 * [integer -MAX to -1 incl., integer 1 to MAX incl.]
2545 * ERRORS {boolean|number} true, false, 1 or 0
2546 * CRYPTO {boolean|number} true, false, 1 or 0
2547 * MODULO_MODE {number} 0 to 9 inclusive
2548 * POW_PRECISION {number} 0 to MAX inclusive
2549 * FORMAT {object} See BigNumber.prototype.toFormat
2550 * decimalSeparator {string}
2551 * groupSeparator {string}
2552 * groupSize {number}
2553 * secondaryGroupSize {number}
2554 * fractionGroupSeparator {string}
2555 * fractionGroupSize {number}
2556 *
2557 * (The values assigned to the above FORMAT object properties are not checked for validity.)
2558 *
2559 * E.g.
2560 * BigNumber.config(20, 4) is equivalent to
2561 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
2562 *
2563 * Ignore properties/parameters set to null or undefined.
2564 * Return an object with the properties current values.
2565 */
2566 BigNumber.config = BigNumber.set = function () {
2567 var v, p,
2568 i = 0,
2569 r = {},
2570 a = arguments,
2571 o = a[0],
2572 has = o && typeof o == 'object'
2573 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
2574 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
2575
2576 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
2577 // 'config() DECIMAL_PLACES not an integer: {v}'
2578 // 'config() DECIMAL_PLACES out of range: {v}'
2579 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
2580 DECIMAL_PLACES = v | 0;
2581 }
2582 r[p] = DECIMAL_PLACES;
2583
2584 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
2585 // 'config() ROUNDING_MODE not an integer: {v}'
2586 // 'config() ROUNDING_MODE out of range: {v}'
2587 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
2588 ROUNDING_MODE = v | 0;
2589 }
2590 r[p] = ROUNDING_MODE;
2591
2592 // EXPONENTIAL_AT {number|number[]}
2593 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
2594 // 'config() EXPONENTIAL_AT not an integer: {v}'
2595 // 'config() EXPONENTIAL_AT out of range: {v}'
2596 if ( has( p = 'EXPONENTIAL_AT' ) ) {
2597
2598 if ( isArray(v) ) {
2599 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
2600 TO_EXP_NEG = v[0] | 0;
2601 TO_EXP_POS = v[1] | 0;
2602 }
2603 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
2604 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
2605 }
2606 }
2607 r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
2608
2609 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
2610 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
2611 // 'config() RANGE not an integer: {v}'
2612 // 'config() RANGE cannot be zero: {v}'
2613 // 'config() RANGE out of range: {v}'
2614 if ( has( p = 'RANGE' ) ) {
2615
2616 if ( isArray(v) ) {
2617 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
2618 MIN_EXP = v[0] | 0;
2619 MAX_EXP = v[1] | 0;
2620 }
2621 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
2622 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
2623 else if (ERRORS) raise( 2, p + ' cannot be zero', v );
2624 }
2625 }
2626 r[p] = [ MIN_EXP, MAX_EXP ];
2627
2628 // ERRORS {boolean|number} true, false, 1 or 0.
2629 // 'config() ERRORS not a boolean or binary digit: {v}'
2630 if ( has( p = 'ERRORS' ) ) {
2631
2632 if ( v === !!v || v === 1 || v === 0 ) {
2633 id = 0;
2634 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
2635 } else if (ERRORS) {
2636 raise( 2, p + notBool, v );
2637 }
2638 }
2639 r[p] = ERRORS;
2640
2641 // CRYPTO {boolean|number} true, false, 1 or 0.
2642 // 'config() CRYPTO not a boolean or binary digit: {v}'
2643 // 'config() crypto unavailable: {crypto}'
2644 if ( has( p = 'CRYPTO' ) ) {
2645
2646 if ( v === true || v === false || v === 1 || v === 0 ) {
2647 if (v) {
2648 v = typeof crypto == 'undefined';
2649 if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
2650 CRYPTO = true;
2651 } else if (ERRORS) {
2652 raise( 2, 'crypto unavailable', v ? void 0 : crypto );
2653 } else {
2654 CRYPTO = false;
2655 }
2656 } else {
2657 CRYPTO = false;
2658 }
2659 } else if (ERRORS) {
2660 raise( 2, p + notBool, v );
2661 }
2662 }
2663 r[p] = CRYPTO;
2664
2665 // MODULO_MODE {number} Integer, 0 to 9 inclusive.
2666 // 'config() MODULO_MODE not an integer: {v}'
2667 // 'config() MODULO_MODE out of range: {v}'
2668 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
2669 MODULO_MODE = v | 0;
2670 }
2671 r[p] = MODULO_MODE;
2672
2673 // POW_PRECISION {number} Integer, 0 to MAX inclusive.
2674 // 'config() POW_PRECISION not an integer: {v}'
2675 // 'config() POW_PRECISION out of range: {v}'
2676 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
2677 POW_PRECISION = v | 0;
2678 }
2679 r[p] = POW_PRECISION;
2680
2681 // FORMAT {object}
2682 // 'config() FORMAT not an object: {v}'
2683 if ( has( p = 'FORMAT' ) ) {
2684
2685 if ( typeof v == 'object' ) {
2686 FORMAT = v;
2687 } else if (ERRORS) {
2688 raise( 2, p + ' not an object', v );
2689 }
2690 }
2691 r[p] = FORMAT;
2692
2693 return r;
2694 };
2695
2696
2697 /*
2698 * Return a new BigNumber whose value is the maximum of the arguments.
2699 *
2700 * arguments {number|string|BigNumber}
2701 */
2702 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
2703
2704
2705 /*
2706 * Return a new BigNumber whose value is the minimum of the arguments.
2707 *
2708 * arguments {number|string|BigNumber}
2709 */
2710 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
2711
2712
2713 /*
2714 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
2715 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
2716 * zeros are produced).
2717 *
2718 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
2719 *
2720 * 'random() decimal places not an integer: {dp}'
2721 * 'random() decimal places out of range: {dp}'
2722 * 'random() crypto unavailable: {crypto}'
2723 */
2724 BigNumber.random = (function () {
2725 var pow2_53 = 0x20000000000000;
2726
2727 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
2728 // Check if Math.random() produces more than 32 bits of randomness.
2729 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
2730 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
2731 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
2732 ? function () { return mathfloor( Math.random() * pow2_53 ); }
2733 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
2734 (Math.random() * 0x800000 | 0); };
2735
2736 return function (dp) {
2737 var a, b, e, k, v,
2738 i = 0,
2739 c = [],
2740 rand = new BigNumber(ONE);
2741
2742 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
2743 k = mathceil( dp / LOG_BASE );
2744
2745 if (CRYPTO) {
2746
2747 // Browsers supporting crypto.getRandomValues.
2748 if (crypto.getRandomValues) {
2749
2750 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
2751
2752 for ( ; i < k; ) {
2753
2754 // 53 bits:
2755 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
2756 // 11111 11111111 11111111 11111111 11100000 00000000 00000000
2757 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
2758 // 11111 11111111 11111111
2759 // 0x20000 is 2^21.
2760 v = a[i] * 0x20000 + (a[i + 1] >>> 11);
2761
2762 // Rejection sampling:
2763 // 0 <= v < 9007199254740992
2764 // Probability that v >= 9e15, is
2765 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
2766 if ( v >= 9e15 ) {
2767 b = crypto.getRandomValues( new Uint32Array(2) );
2768 a[i] = b[0];
2769 a[i + 1] = b[1];
2770 } else {
2771
2772 // 0 <= v <= 8999999999999999
2773 // 0 <= (v % 1e14) <= 99999999999999
2774 c.push( v % 1e14 );
2775 i += 2;
2776 }
2777 }
2778 i = k / 2;
2779
2780 // Node.js supporting crypto.randomBytes.
2781 } else if (crypto.randomBytes) {
2782
2783 // buffer
2784 a = crypto.randomBytes( k *= 7 );
2785
2786 for ( ; i < k; ) {
2787
2788 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
2789 // 0x100000000 is 2^32, 0x1000000 is 2^24
2790 // 11111 11111111 11111111 11111111 11111111 11111111 11111111
2791 // 0 <= v < 9007199254740992
2792 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
2793 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
2794 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
2795
2796 if ( v >= 9e15 ) {
2797 crypto.randomBytes(7).copy( a, i );
2798 } else {
2799
2800 // 0 <= (v % 1e14) <= 99999999999999
2801 c.push( v % 1e14 );
2802 i += 7;
2803 }
2804 }
2805 i = k / 7;
2806 } else {
2807 CRYPTO = false;
2808 if (ERRORS) raise( 14, 'crypto unavailable', crypto );
2809 }
2810 }
2811
2812 // Use Math.random.
2813 if (!CRYPTO) {
2814
2815 for ( ; i < k; ) {
2816 v = random53bitInt();
2817 if ( v < 9e15 ) c[i++] = v % 1e14;
2818 }
2819 }
2820
2821 k = c[--i];
2822 dp %= LOG_BASE;
2823
2824 // Convert trailing digits to zeros according to dp.
2825 if ( k && dp ) {
2826 v = POWS_TEN[LOG_BASE - dp];
2827 c[i] = mathfloor( k / v ) * v;
2828 }
2829
2830 // Remove trailing elements which are zero.
2831 for ( ; c[i] === 0; c.pop(), i-- );
2832
2833 // Zero?
2834 if ( i < 0 ) {
2835 c = [ e = 0 ];
2836 } else {
2837
2838 // Remove leading elements which are zero and adjust exponent accordingly.
2839 for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
2840
2841 // Count the digits of the first element of c to determine leading zeros, and...
2842 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
2843
2844 // adjust the exponent accordingly.
2845 if ( i < LOG_BASE ) e -= LOG_BASE - i;
2846 }
2847
2848 rand.e = e;
2849 rand.c = c;
2850 return rand;
2851 };
2852 })();
2853
2854
2855 // PRIVATE FUNCTIONS
2856
2857
2858 // Convert a numeric string of baseIn to a numeric string of baseOut.
2859 function convertBase( str, baseOut, baseIn, sign ) {
2860 var d, e, k, r, x, xc, y,
2861 i = str.indexOf( '.' ),
2862 dp = DECIMAL_PLACES,
2863 rm = ROUNDING_MODE;
2864
2865 if ( baseIn < 37 ) str = str.toLowerCase();
2866
2867 // Non-integer.
2868 if ( i >= 0 ) {
2869 k = POW_PRECISION;
2870
2871 // Unlimited precision.
2872 POW_PRECISION = 0;
2873 str = str.replace( '.', '' );
2874 y = new BigNumber(baseIn);
2875 x = y.pow( str.length - i );
2876 POW_PRECISION = k;
2877
2878 // Convert str as if an integer, then restore the fraction part by dividing the
2879 // result by its base raised to a power.
2880 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
2881 y.e = y.c.length;
2882 }
2883
2884 // Convert the number as integer.
2885 xc = toBaseOut( str, baseIn, baseOut );
2886 e = k = xc.length;
2887
2888 // Remove trailing zeros.
2889 for ( ; xc[--k] == 0; xc.pop() );
2890 if ( !xc[0] ) return '0';
2891
2892 if ( i < 0 ) {
2893 --e;
2894 } else {
2895 x.c = xc;
2896 x.e = e;
2897
2898 // sign is needed for correct rounding.
2899 x.s = sign;
2900 x = div( x, y, dp, rm, baseOut );
2901 xc = x.c;
2902 r = x.r;
2903 e = x.e;
2904 }
2905
2906 d = e + dp + 1;
2907
2908 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
2909 i = xc[d];
2910 k = baseOut / 2;
2911 r = r || d < 0 || xc[d + 1] != null;
2912
2913 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
2914 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
2915 rm == ( x.s < 0 ? 8 : 7 ) );
2916
2917 if ( d < 1 || !xc[0] ) {
2918
2919 // 1^-dp or 0.
2920 str = r ? toFixedPoint( '1', -dp ) : '0';
2921 } else {
2922 xc.length = d;
2923
2924 if (r) {
2925
2926 // Rounding up may mean the previous digit has to be rounded up and so on.
2927 for ( --baseOut; ++xc[--d] > baseOut; ) {
2928 xc[d] = 0;
2929
2930 if ( !d ) {
2931 ++e;
2932 xc = [1].concat(xc);
2933 }
2934 }
2935 }
2936
2937 // Determine trailing zeros.
2938 for ( k = xc.length; !xc[--k]; );
2939
2940 // E.g. [4, 11, 15] becomes 4bf.
2941 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
2942 str = toFixedPoint( str, e );
2943 }
2944
2945 // The caller will add the sign.
2946 return str;
2947 }
2948
2949
2950 // Perform division in the specified base. Called by div and convertBase.
2951 div = (function () {
2952
2953 // Assume non-zero x and k.
2954 function multiply( x, k, base ) {
2955 var m, temp, xlo, xhi,
2956 carry = 0,
2957 i = x.length,
2958 klo = k % SQRT_BASE,
2959 khi = k / SQRT_BASE | 0;
2960
2961 for ( x = x.slice(); i--; ) {
2962 xlo = x[i] % SQRT_BASE;
2963 xhi = x[i] / SQRT_BASE | 0;
2964 m = khi * xlo + xhi * klo;
2965 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
2966 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
2967 x[i] = temp % base;
2968 }
2969
2970 if (carry) x = [carry].concat(x);
2971
2972 return x;
2973 }
2974
2975 function compare( a, b, aL, bL ) {
2976 var i, cmp;
2977
2978 if ( aL != bL ) {
2979 cmp = aL > bL ? 1 : -1;
2980 } else {
2981
2982 for ( i = cmp = 0; i < aL; i++ ) {
2983
2984 if ( a[i] != b[i] ) {
2985 cmp = a[i] > b[i] ? 1 : -1;
2986 break;
2987 }
2988 }
2989 }
2990 return cmp;
2991 }
2992
2993 function subtract( a, b, aL, base ) {
2994 var i = 0;
2995
2996 // Subtract b from a.
2997 for ( ; aL--; ) {
2998 a[aL] -= i;
2999 i = a[aL] < b[aL] ? 1 : 0;
3000 a[aL] = i * base + a[aL] - b[aL];
3001 }
3002
3003 // Remove leading zeros.
3004 for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
3005 }
3006
3007 // x: dividend, y: divisor.
3008 return function ( x, y, dp, rm, base ) {
3009 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
3010 yL, yz,
3011 s = x.s == y.s ? 1 : -1,
3012 xc = x.c,
3013 yc = y.c;
3014
3015 // Either NaN, Infinity or 0?
3016 if ( !xc || !xc[0] || !yc || !yc[0] ) {
3017
3018 return new BigNumber(
3019
3020 // Return NaN if either NaN, or both Infinity or 0.
3021 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
3022
3023 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
3024 xc && xc[0] == 0 || !yc ? s * 0 : s / 0
3025 );
3026 }
3027
3028 q = new BigNumber(s);
3029 qc = q.c = [];
3030 e = x.e - y.e;
3031 s = dp + e + 1;
3032
3033 if ( !base ) {
3034 base = BASE;
3035 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
3036 s = s / LOG_BASE | 0;
3037 }
3038
3039 // Result exponent may be one less then the current value of e.
3040 // The coefficients of the BigNumbers from convertBase may have trailing zeros.
3041 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
3042 if ( yc[i] > ( xc[i] || 0 ) ) e--;
3043
3044 if ( s < 0 ) {
3045 qc.push(1);
3046 more = true;
3047 } else {
3048 xL = xc.length;
3049 yL = yc.length;
3050 i = 0;
3051 s += 2;
3052
3053 // Normalise xc and yc so highest order digit of yc is >= base / 2.
3054
3055 n = mathfloor( base / ( yc[0] + 1 ) );
3056
3057 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
3058 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
3059 if ( n > 1 ) {
3060 yc = multiply( yc, n, base );
3061 xc = multiply( xc, n, base );
3062 yL = yc.length;
3063 xL = xc.length;
3064 }
3065
3066 xi = yL;
3067 rem = xc.slice( 0, yL );
3068 remL = rem.length;
3069
3070 // Add zeros to make remainder as long as divisor.
3071 for ( ; remL < yL; rem[remL++] = 0 );
3072 yz = yc.slice();
3073 yz = [0].concat(yz);
3074 yc0 = yc[0];
3075 if ( yc[1] >= base / 2 ) yc0++;
3076 // Not necessary, but to prevent trial digit n > base, when using base 3.
3077 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
3078
3079 do {
3080 n = 0;
3081
3082 // Compare divisor and remainder.
3083 cmp = compare( yc, rem, yL, remL );
3084
3085 // If divisor < remainder.
3086 if ( cmp < 0 ) {
3087
3088 // Calculate trial digit, n.
3089
3090 rem0 = rem[0];
3091 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
3092
3093 // n is how many times the divisor goes into the current remainder.
3094 n = mathfloor( rem0 / yc0 );
3095
3096 // Algorithm:
3097 // 1. product = divisor * trial digit (n)
3098 // 2. if product > remainder: product -= divisor, n--
3099 // 3. remainder -= product
3100 // 4. if product was < remainder at 2:
3101 // 5. compare new remainder and divisor
3102 // 6. If remainder > divisor: remainder -= divisor, n++
3103
3104 if ( n > 1 ) {
3105
3106 // n may be > base only when base is 3.
3107 if (n >= base) n = base - 1;
3108
3109 // product = divisor * trial digit.
3110 prod = multiply( yc, n, base );
3111 prodL = prod.length;
3112 remL = rem.length;
3113
3114 // Compare product and remainder.
3115 // If product > remainder.
3116 // Trial digit n too high.
3117 // n is 1 too high about 5% of the time, and is not known to have
3118 // ever been more than 1 too high.
3119 while ( compare( prod, rem, prodL, remL ) == 1 ) {
3120 n--;
3121
3122 // Subtract divisor from product.
3123 subtract( prod, yL < prodL ? yz : yc, prodL, base );
3124 prodL = prod.length;
3125 cmp = 1;
3126 }
3127 } else {
3128
3129 // n is 0 or 1, cmp is -1.
3130 // If n is 0, there is no need to compare yc and rem again below,
3131 // so change cmp to 1 to avoid it.
3132 // If n is 1, leave cmp as -1, so yc and rem are compared again.
3133 if ( n == 0 ) {
3134
3135 // divisor < remainder, so n must be at least 1.
3136 cmp = n = 1;
3137 }
3138
3139 // product = divisor
3140 prod = yc.slice();
3141 prodL = prod.length;
3142 }
3143
3144 if ( prodL < remL ) prod = [0].concat(prod);
3145
3146 // Subtract product from remainder.
3147 subtract( rem, prod, remL, base );
3148 remL = rem.length;
3149
3150 // If product was < remainder.
3151 if ( cmp == -1 ) {
3152
3153 // Compare divisor and new remainder.
3154 // If divisor < new remainder, subtract divisor from remainder.
3155 // Trial digit n too low.
3156 // n is 1 too low about 5% of the time, and very rarely 2 too low.
3157 while ( compare( yc, rem, yL, remL ) < 1 ) {
3158 n++;
3159
3160 // Subtract divisor from remainder.
3161 subtract( rem, yL < remL ? yz : yc, remL, base );
3162 remL = rem.length;
3163 }
3164 }
3165 } else if ( cmp === 0 ) {
3166 n++;
3167 rem = [0];
3168 } // else cmp === 1 and n will be 0
3169
3170 // Add the next digit, n, to the result array.
3171 qc[i++] = n;
3172
3173 // Update the remainder.
3174 if ( rem[0] ) {
3175 rem[remL++] = xc[xi] || 0;
3176 } else {
3177 rem = [ xc[xi] ];
3178 remL = 1;
3179 }
3180 } while ( ( xi++ < xL || rem[0] != null ) && s-- );
3181
3182 more = rem[0] != null;
3183
3184 // Leading zero?
3185 if ( !qc[0] ) qc.splice(0, 1);
3186 }
3187
3188 if ( base == BASE ) {
3189
3190 // To calculate q.e, first get the number of digits of qc[0].
3191 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
3192 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
3193
3194 // Caller is convertBase.
3195 } else {
3196 q.e = e;
3197 q.r = +more;
3198 }
3199
3200 return q;
3201 };
3202 })();
3203
3204
3205 /*
3206 * Return a string representing the value of BigNumber n in fixed-point or exponential
3207 * notation rounded to the specified decimal places or significant digits.
3208 *
3209 * n is a BigNumber.
3210 * i is the index of the last digit required (i.e. the digit that may be rounded up).
3211 * rm is the rounding mode.
3212 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
3213 */
3214 function format( n, i, rm, caller ) {
3215 var c0, e, ne, len, str;
3216
3217 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
3218 ? rm | 0 : ROUNDING_MODE;
3219
3220 if ( !n.c ) return n.toString();
3221 c0 = n.c[0];
3222 ne = n.e;
3223
3224 if ( i == null ) {
3225 str = coeffToString( n.c );
3226 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
3227 ? toExponential( str, ne )
3228 : toFixedPoint( str, ne );
3229 } else {
3230 n = round( new BigNumber(n), i, rm );
3231
3232 // n.e may have changed if the value was rounded up.
3233 e = n.e;
3234
3235 str = coeffToString( n.c );
3236 len = str.length;
3237
3238 // toPrecision returns exponential notation if the number of significant digits
3239 // specified is less than the number of digits necessary to represent the integer
3240 // part of the value in fixed-point notation.
3241
3242 // Exponential notation.
3243 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
3244
3245 // Append zeros?
3246 for ( ; len < i; str += '0', len++ );
3247 str = toExponential( str, e );
3248
3249 // Fixed-point notation.
3250 } else {
3251 i -= ne;
3252 str = toFixedPoint( str, e );
3253
3254 // Append zeros?
3255 if ( e + 1 > len ) {
3256 if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
3257 } else {
3258 i += e - len;
3259 if ( i > 0 ) {
3260 if ( e + 1 == len ) str += '.';
3261 for ( ; i--; str += '0' );
3262 }
3263 }
3264 }
3265 }
3266
3267 return n.s < 0 && c0 ? '-' + str : str;
3268 }
3269
3270
3271 // Handle BigNumber.max and BigNumber.min.
3272 function maxOrMin( args, method ) {
3273 var m, n,
3274 i = 0;
3275
3276 if ( isArray( args[0] ) ) args = args[0];
3277 m = new BigNumber( args[0] );
3278
3279 for ( ; ++i < args.length; ) {
3280 n = new BigNumber( args[i] );
3281
3282 // If any number is NaN, return NaN.
3283 if ( !n.s ) {
3284 m = n;
3285 break;
3286 } else if ( method.call( m, n ) ) {
3287 m = n;
3288 }
3289 }
3290
3291 return m;
3292 }
3293
3294
3295 /*
3296 * Return true if n is an integer in range, otherwise throw.
3297 * Use for argument validation when ERRORS is true.
3298 */
3299 function intValidatorWithErrors( n, min, max, caller, name ) {
3300 if ( n < min || n > max || n != truncate(n) ) {
3301 raise( caller, ( name || 'decimal places' ) +
3302 ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
3303 }
3304
3305 return true;
3306 }
3307
3308
3309 /*
3310 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
3311 * Called by minus, plus and times.
3312 */
3313 function normalise( n, c, e ) {
3314 var i = 1,
3315 j = c.length;
3316
3317 // Remove trailing zeros.
3318 for ( ; !c[--j]; c.pop() );
3319
3320 // Calculate the base 10 exponent. First get the number of digits of c[0].
3321 for ( j = c[0]; j >= 10; j /= 10, i++ );
3322
3323 // Overflow?
3324 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
3325
3326 // Infinity.
3327 n.c = n.e = null;
3328
3329 // Underflow?
3330 } else if ( e < MIN_EXP ) {
3331
3332 // Zero.
3333 n.c = [ n.e = 0 ];
3334 } else {
3335 n.e = e;
3336 n.c = c;
3337 }
3338
3339 return n;
3340 }
3341
3342
3343 // Handle values that fail the validity test in BigNumber.
3344 parseNumeric = (function () {
3345 var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
3346 dotAfter = /^([^.]+)\.$/,
3347 dotBefore = /^\.([^.]+)$/,
3348 isInfinityOrNaN = /^-?(Infinity|NaN)$/,
3349 whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
3350
3351 return function ( x, str, num, b ) {
3352 var base,
3353 s = num ? str : str.replace( whitespaceOrPlus, '' );
3354
3355 // No exception on ±Infinity or NaN.
3356 if ( isInfinityOrNaN.test(s) ) {
3357 x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
3358 } else {
3359 if ( !num ) {
3360
3361 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
3362 s = s.replace( basePrefix, function ( m, p1, p2 ) {
3363 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
3364 return !b || b == base ? p1 : m;
3365 });
3366
3367 if (b) {
3368 base = b;
3369
3370 // E.g. '1.' to '1', '.1' to '0.1'
3371 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
3372 }
3373
3374 if ( str != s ) return new BigNumber( s, base );
3375 }
3376
3377 // 'new BigNumber() not a number: {n}'
3378 // 'new BigNumber() not a base {b} number: {n}'
3379 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
3380 x.s = null;
3381 }
3382
3383 x.c = x.e = null;
3384 id = 0;
3385 }
3386 })();
3387
3388
3389 // Throw a BigNumber Error.
3390 function raise( caller, msg, val ) {
3391 var error = new Error( [
3392 'new BigNumber', // 0
3393 'cmp', // 1
3394 'config', // 2
3395 'div', // 3
3396 'divToInt', // 4
3397 'eq', // 5
3398 'gt', // 6
3399 'gte', // 7
3400 'lt', // 8
3401 'lte', // 9
3402 'minus', // 10
3403 'mod', // 11
3404 'plus', // 12
3405 'precision', // 13
3406 'random', // 14
3407 'round', // 15
3408 'shift', // 16
3409 'times', // 17
3410 'toDigits', // 18
3411 'toExponential', // 19
3412 'toFixed', // 20
3413 'toFormat', // 21
3414 'toFraction', // 22
3415 'pow', // 23
3416 'toPrecision', // 24
3417 'toString', // 25
3418 'BigNumber' // 26
3419 ][caller] + '() ' + msg + ': ' + val );
3420
3421 error.name = 'BigNumber Error';
3422 id = 0;
3423 throw error;
3424 }
3425
3426
3427 /*
3428 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
3429 * If r is truthy, it is known that there are more digits after the rounding digit.
3430 */
3431 function round( x, sd, rm, r ) {
3432 var d, i, j, k, n, ni, rd,
3433 xc = x.c,
3434 pows10 = POWS_TEN;
3435
3436 // if x is not Infinity or NaN...
3437 if (xc) {
3438
3439 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
3440 // n is a base 1e14 number, the value of the element of array x.c containing rd.
3441 // ni is the index of n within x.c.
3442 // d is the number of digits of n.
3443 // i is the index of rd within n including leading zeros.
3444 // j is the actual index of rd within n (if < 0, rd is a leading zero).
3445 out: {
3446
3447 // Get the number of digits of the first element of xc.
3448 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
3449 i = sd - d;
3450
3451 // If the rounding digit is in the first element of xc...
3452 if ( i < 0 ) {
3453 i += LOG_BASE;
3454 j = sd;
3455 n = xc[ ni = 0 ];
3456
3457 // Get the rounding digit at index j of n.
3458 rd = n / pows10[ d - j - 1 ] % 10 | 0;
3459 } else {
3460 ni = mathceil( ( i + 1 ) / LOG_BASE );
3461
3462 if ( ni >= xc.length ) {
3463
3464 if (r) {
3465
3466 // Needed by sqrt.
3467 for ( ; xc.length <= ni; xc.push(0) );
3468 n = rd = 0;
3469 d = 1;
3470 i %= LOG_BASE;
3471 j = i - LOG_BASE + 1;
3472 } else {
3473 break out;
3474 }
3475 } else {
3476 n = k = xc[ni];
3477
3478 // Get the number of digits of n.
3479 for ( d = 1; k >= 10; k /= 10, d++ );
3480
3481 // Get the index of rd within n.
3482 i %= LOG_BASE;
3483
3484 // Get the index of rd within n, adjusted for leading zeros.
3485 // The number of leading zeros of n is given by LOG_BASE - d.
3486 j = i - LOG_BASE + d;
3487
3488 // Get the rounding digit at index j of n.
3489 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
3490 }
3491 }
3492
3493 r = r || sd < 0 ||
3494
3495 // Are there any non-zero digits after the rounding digit?
3496 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
3497 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
3498 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
3499
3500 r = rm < 4
3501 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
3502 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
3503
3504 // Check whether the digit to the left of the rounding digit is odd.
3505 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
3506 rm == ( x.s < 0 ? 8 : 7 ) );
3507
3508 if ( sd < 1 || !xc[0] ) {
3509 xc.length = 0;
3510
3511 if (r) {
3512
3513 // Convert sd to decimal places.
3514 sd -= x.e + 1;
3515
3516 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
3517 xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
3518 x.e = -sd || 0;
3519 } else {
3520
3521 // Zero.
3522 xc[0] = x.e = 0;
3523 }
3524
3525 return x;
3526 }
3527
3528 // Remove excess digits.
3529 if ( i == 0 ) {
3530 xc.length = ni;
3531 k = 1;
3532 ni--;
3533 } else {
3534 xc.length = ni + 1;
3535 k = pows10[ LOG_BASE - i ];
3536
3537 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
3538 // j > 0 means i > number of leading zeros of n.
3539 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
3540 }
3541
3542 // Round up?
3543 if (r) {
3544
3545 for ( ; ; ) {
3546
3547 // If the digit to be rounded up is in the first element of xc...
3548 if ( ni == 0 ) {
3549
3550 // i will be the length of xc[0] before k is added.
3551 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
3552 j = xc[0] += k;
3553 for ( k = 1; j >= 10; j /= 10, k++ );
3554
3555 // if i != k the length has increased.
3556 if ( i != k ) {
3557 x.e++;
3558 if ( xc[0] == BASE ) xc[0] = 1;
3559 }
3560
3561 break;
3562 } else {
3563 xc[ni] += k;
3564 if ( xc[ni] != BASE ) break;
3565 xc[ni--] = 0;
3566 k = 1;
3567 }
3568 }
3569 }
3570
3571 // Remove trailing zeros.
3572 for ( i = xc.length; xc[--i] === 0; xc.pop() );
3573 }
3574
3575 // Overflow? Infinity.
3576 if ( x.e > MAX_EXP ) {
3577 x.c = x.e = null;
3578
3579 // Underflow? Zero.
3580 } else if ( x.e < MIN_EXP ) {
3581 x.c = [ x.e = 0 ];
3582 }
3583 }
3584
3585 return x;
3586 }
3587
3588
3589 // PROTOTYPE/INSTANCE METHODS
3590
3591
3592 /*
3593 * Return a new BigNumber whose value is the absolute value of this BigNumber.
3594 */
3595 P.absoluteValue = P.abs = function () {
3596 var x = new BigNumber(this);
3597 if ( x.s < 0 ) x.s = 1;
3598 return x;
3599 };
3600
3601
3602 /*
3603 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
3604 * number in the direction of Infinity.
3605 */
3606 P.ceil = function () {
3607 return round( new BigNumber(this), this.e + 1, 2 );
3608 };
3609
3610
3611 /*
3612 * Return
3613 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
3614 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
3615 * 0 if they have the same value,
3616 * or null if the value of either is NaN.
3617 */
3618 P.comparedTo = P.cmp = function ( y, b ) {
3619 id = 1;
3620 return compare( this, new BigNumber( y, b ) );
3621 };
3622
3623
3624 /*
3625 * Return the number of decimal places of the value of this BigNumber, or null if the value
3626 * of this BigNumber is ±Infinity or NaN.
3627 */
3628 P.decimalPlaces = P.dp = function () {
3629 var n, v,
3630 c = this.c;
3631
3632 if ( !c ) return null;
3633 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
3634
3635 // Subtract the number of trailing zeros of the last number.
3636 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
3637 if ( n < 0 ) n = 0;
3638
3639 return n;
3640 };
3641
3642
3643 /*
3644 * n / 0 = I
3645 * n / N = N
3646 * n / I = 0
3647 * 0 / n = 0
3648 * 0 / 0 = N
3649 * 0 / N = N
3650 * 0 / I = 0
3651 * N / n = N
3652 * N / 0 = N
3653 * N / N = N
3654 * N / I = N
3655 * I / n = I
3656 * I / 0 = I
3657 * I / N = N
3658 * I / I = N
3659 *
3660 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
3661 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
3662 */
3663 P.dividedBy = P.div = function ( y, b ) {
3664 id = 3;
3665 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
3666 };
3667
3668
3669 /*
3670 * Return a new BigNumber whose value is the integer part of dividing the value of this
3671 * BigNumber by the value of BigNumber(y, b).
3672 */
3673 P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
3674 id = 4;
3675 return div( this, new BigNumber( y, b ), 0, 1 );
3676 };
3677
3678
3679 /*
3680 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
3681 * otherwise returns false.
3682 */
3683 P.equals = P.eq = function ( y, b ) {
3684 id = 5;
3685 return compare( this, new BigNumber( y, b ) ) === 0;
3686 };
3687
3688
3689 /*
3690 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
3691 * number in the direction of -Infinity.
3692 */
3693 P.floor = function () {
3694 return round( new BigNumber(this), this.e + 1, 3 );
3695 };
3696
3697
3698 /*
3699 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
3700 * otherwise returns false.
3701 */
3702 P.greaterThan = P.gt = function ( y, b ) {
3703 id = 6;
3704 return compare( this, new BigNumber( y, b ) ) > 0;
3705 };
3706
3707
3708 /*
3709 * Return true if the value of this BigNumber is greater than or equal to the value of
3710 * BigNumber(y, b), otherwise returns false.
3711 */
3712 P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
3713 id = 7;
3714 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
3715
3716 };
3717
3718
3719 /*
3720 * Return true if the value of this BigNumber is a finite number, otherwise returns false.
3721 */
3722 P.isFinite = function () {
3723 return !!this.c;
3724 };
3725
3726
3727 /*
3728 * Return true if the value of this BigNumber is an integer, otherwise return false.
3729 */
3730 P.isInteger = P.isInt = function () {
3731 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
3732 };
3733
3734
3735 /*
3736 * Return true if the value of this BigNumber is NaN, otherwise returns false.
3737 */
3738 P.isNaN = function () {
3739 return !this.s;
3740 };
3741
3742
3743 /*
3744 * Return true if the value of this BigNumber is negative, otherwise returns false.
3745 */
3746 P.isNegative = P.isNeg = function () {
3747 return this.s < 0;
3748 };
3749
3750
3751 /*
3752 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
3753 */
3754 P.isZero = function () {
3755 return !!this.c && this.c[0] == 0;
3756 };
3757
3758
3759 /*
3760 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
3761 * otherwise returns false.
3762 */
3763 P.lessThan = P.lt = function ( y, b ) {
3764 id = 8;
3765 return compare( this, new BigNumber( y, b ) ) < 0;
3766 };
3767
3768
3769 /*
3770 * Return true if the value of this BigNumber is less than or equal to the value of
3771 * BigNumber(y, b), otherwise returns false.
3772 */
3773 P.lessThanOrEqualTo = P.lte = function ( y, b ) {
3774 id = 9;
3775 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
3776 };
3777
3778
3779 /*
3780 * n - 0 = n
3781 * n - N = N
3782 * n - I = -I
3783 * 0 - n = -n
3784 * 0 - 0 = 0
3785 * 0 - N = N
3786 * 0 - I = -I
3787 * N - n = N
3788 * N - 0 = N
3789 * N - N = N
3790 * N - I = N
3791 * I - n = I
3792 * I - 0 = I
3793 * I - N = N
3794 * I - I = N
3795 *
3796 * Return a new BigNumber whose value is the value of this BigNumber minus the value of
3797 * BigNumber(y, b).
3798 */
3799 P.minus = P.sub = function ( y, b ) {
3800 var i, j, t, xLTy,
3801 x = this,
3802 a = x.s;
3803
3804 id = 10;
3805 y = new BigNumber( y, b );
3806 b = y.s;
3807
3808 // Either NaN?
3809 if ( !a || !b ) return new BigNumber(NaN);
3810
3811 // Signs differ?
3812 if ( a != b ) {
3813 y.s = -b;
3814 return x.plus(y);
3815 }
3816
3817 var xe = x.e / LOG_BASE,
3818 ye = y.e / LOG_BASE,
3819 xc = x.c,
3820 yc = y.c;
3821
3822 if ( !xe || !ye ) {
3823
3824 // Either Infinity?
3825 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
3826
3827 // Either zero?
3828 if ( !xc[0] || !yc[0] ) {
3829
3830 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
3831 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
3832
3833 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
3834 ROUNDING_MODE == 3 ? -0 : 0 );
3835 }
3836 }
3837
3838 xe = bitFloor(xe);
3839 ye = bitFloor(ye);
3840 xc = xc.slice();
3841
3842 // Determine which is the bigger number.
3843 if ( a = xe - ye ) {
3844
3845 if ( xLTy = a < 0 ) {
3846 a = -a;
3847 t = xc;
3848 } else {
3849 ye = xe;
3850 t = yc;
3851 }
3852
3853 t.reverse();
3854
3855 // Prepend zeros to equalise exponents.
3856 for ( b = a; b--; t.push(0) );
3857 t.reverse();
3858 } else {
3859
3860 // Exponents equal. Check digit by digit.
3861 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
3862
3863 for ( a = b = 0; b < j; b++ ) {
3864
3865 if ( xc[b] != yc[b] ) {
3866 xLTy = xc[b] < yc[b];
3867 break;
3868 }
3869 }
3870 }
3871
3872 // x < y? Point xc to the array of the bigger number.
3873 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
3874
3875 b = ( j = yc.length ) - ( i = xc.length );
3876
3877 // Append zeros to xc if shorter.
3878 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
3879 if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
3880 b = BASE - 1;
3881
3882 // Subtract yc from xc.
3883 for ( ; j > a; ) {
3884
3885 if ( xc[--j] < yc[j] ) {
3886 for ( i = j; i && !xc[--i]; xc[i] = b );
3887 --xc[i];
3888 xc[j] += BASE;
3889 }
3890
3891 xc[j] -= yc[j];
3892 }
3893
3894 // Remove leading zeros and adjust exponent accordingly.
3895 for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
3896
3897 // Zero?
3898 if ( !xc[0] ) {
3899
3900 // Following IEEE 754 (2008) 6.3,
3901 // n - n = +0 but n - n = -0 when rounding towards -Infinity.
3902 y.s = ROUNDING_MODE == 3 ? -1 : 1;
3903 y.c = [ y.e = 0 ];
3904 return y;
3905 }
3906
3907 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
3908 // for finite x and y.
3909 return normalise( y, xc, ye );
3910 };
3911
3912
3913 /*
3914 * n % 0 = N
3915 * n % N = N
3916 * n % I = n
3917 * 0 % n = 0
3918 * -0 % n = -0
3919 * 0 % 0 = N
3920 * 0 % N = N
3921 * 0 % I = 0
3922 * N % n = N
3923 * N % 0 = N
3924 * N % N = N
3925 * N % I = N
3926 * I % n = N
3927 * I % 0 = N
3928 * I % N = N
3929 * I % I = N
3930 *
3931 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
3932 * BigNumber(y, b). The result depends on the value of MODULO_MODE.
3933 */
3934 P.modulo = P.mod = function ( y, b ) {
3935 var q, s,
3936 x = this;
3937
3938 id = 11;
3939 y = new BigNumber( y, b );
3940
3941 // Return NaN if x is Infinity or NaN, or y is NaN or zero.
3942 if ( !x.c || !y.s || y.c && !y.c[0] ) {
3943 return new BigNumber(NaN);
3944
3945 // Return x if y is Infinity or x is zero.
3946 } else if ( !y.c || x.c && !x.c[0] ) {
3947 return new BigNumber(x);
3948 }
3949
3950 if ( MODULO_MODE == 9 ) {
3951
3952 // Euclidian division: q = sign(y) * floor(x / abs(y))
3953 // r = x - qy where 0 <= r < abs(y)
3954 s = y.s;
3955 y.s = 1;
3956 q = div( x, y, 0, 3 );
3957 y.s = s;
3958 q.s *= s;
3959 } else {
3960 q = div( x, y, 0, MODULO_MODE );
3961 }
3962
3963 return x.minus( q.times(y) );
3964 };
3965
3966
3967 /*
3968 * Return a new BigNumber whose value is the value of this BigNumber negated,
3969 * i.e. multiplied by -1.
3970 */
3971 P.negated = P.neg = function () {
3972 var x = new BigNumber(this);
3973 x.s = -x.s || null;
3974 return x;
3975 };
3976
3977
3978 /*
3979 * n + 0 = n
3980 * n + N = N
3981 * n + I = I
3982 * 0 + n = n
3983 * 0 + 0 = 0
3984 * 0 + N = N
3985 * 0 + I = I
3986 * N + n = N
3987 * N + 0 = N
3988 * N + N = N
3989 * N + I = N
3990 * I + n = I
3991 * I + 0 = I
3992 * I + N = N
3993 * I + I = I
3994 *
3995 * Return a new BigNumber whose value is the value of this BigNumber plus the value of
3996 * BigNumber(y, b).
3997 */
3998 P.plus = P.add = function ( y, b ) {
3999 var t,
4000 x = this,
4001 a = x.s;
4002
4003 id = 12;
4004 y = new BigNumber( y, b );
4005 b = y.s;
4006
4007 // Either NaN?
4008 if ( !a || !b ) return new BigNumber(NaN);
4009
4010 // Signs differ?
4011 if ( a != b ) {
4012 y.s = -b;
4013 return x.minus(y);
4014 }
4015
4016 var xe = x.e / LOG_BASE,
4017 ye = y.e / LOG_BASE,
4018 xc = x.c,
4019 yc = y.c;
4020
4021 if ( !xe || !ye ) {
4022
4023 // Return ±Infinity if either ±Infinity.
4024 if ( !xc || !yc ) return new BigNumber( a / 0 );
4025
4026 // Either zero?
4027 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
4028 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
4029 }
4030
4031 xe = bitFloor(xe);
4032 ye = bitFloor(ye);
4033 xc = xc.slice();
4034
4035 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
4036 if ( a = xe - ye ) {
4037 if ( a > 0 ) {
4038 ye = xe;
4039 t = yc;
4040 } else {
4041 a = -a;
4042 t = xc;
4043 }
4044
4045 t.reverse();
4046 for ( ; a--; t.push(0) );
4047 t.reverse();
4048 }
4049
4050 a = xc.length;
4051 b = yc.length;
4052
4053 // Point xc to the longer array, and b to the shorter length.
4054 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
4055
4056 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
4057 for ( a = 0; b; ) {
4058 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
4059 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
4060 }
4061
4062 if (a) {
4063 xc = [a].concat(xc);
4064 ++ye;
4065 }
4066
4067 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
4068 // ye = MAX_EXP + 1 possible
4069 return normalise( y, xc, ye );
4070 };
4071
4072
4073 /*
4074 * Return the number of significant digits of the value of this BigNumber.
4075 *
4076 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
4077 */
4078 P.precision = P.sd = function (z) {
4079 var n, v,
4080 x = this,
4081 c = x.c;
4082
4083 // 'precision() argument not a boolean or binary digit: {z}'
4084 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
4085 if (ERRORS) raise( 13, 'argument' + notBool, z );
4086 if ( z != !!z ) z = null;
4087 }
4088
4089 if ( !c ) return null;
4090 v = c.length - 1;
4091 n = v * LOG_BASE + 1;
4092
4093 if ( v = c[v] ) {
4094
4095 // Subtract the number of trailing zeros of the last element.
4096 for ( ; v % 10 == 0; v /= 10, n-- );
4097
4098 // Add the number of digits of the first element.
4099 for ( v = c[0]; v >= 10; v /= 10, n++ );
4100 }
4101
4102 if ( z && x.e + 1 > n ) n = x.e + 1;
4103
4104 return n;
4105 };
4106
4107
4108 /*
4109 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
4110 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
4111 * omitted.
4112 *
4113 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4114 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4115 *
4116 * 'round() decimal places out of range: {dp}'
4117 * 'round() decimal places not an integer: {dp}'
4118 * 'round() rounding mode not an integer: {rm}'
4119 * 'round() rounding mode out of range: {rm}'
4120 */
4121 P.round = function ( dp, rm ) {
4122 var n = new BigNumber(this);
4123
4124 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
4125 round( n, ~~dp + this.e + 1, rm == null ||
4126 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
4127 }
4128
4129 return n;
4130 };
4131
4132
4133 /*
4134 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
4135 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
4136 *
4137 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
4138 *
4139 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
4140 * otherwise.
4141 *
4142 * 'shift() argument not an integer: {k}'
4143 * 'shift() argument out of range: {k}'
4144 */
4145 P.shift = function (k) {
4146 var n = this;
4147 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
4148
4149 // k < 1e+21, or truncate(k) will produce exponential notation.
4150 ? n.times( '1e' + truncate(k) )
4151 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
4152 ? n.s * ( k < 0 ? 0 : 1 / 0 )
4153 : n );
4154 };
4155
4156
4157 /*
4158 * sqrt(-n) = N
4159 * sqrt( N) = N
4160 * sqrt(-I) = N
4161 * sqrt( I) = I
4162 * sqrt( 0) = 0
4163 * sqrt(-0) = -0
4164 *
4165 * Return a new BigNumber whose value is the square root of the value of this BigNumber,
4166 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
4167 */
4168 P.squareRoot = P.sqrt = function () {
4169 var m, n, r, rep, t,
4170 x = this,
4171 c = x.c,
4172 s = x.s,
4173 e = x.e,
4174 dp = DECIMAL_PLACES + 4,
4175 half = new BigNumber('0.5');
4176
4177 // Negative/NaN/Infinity/zero?
4178 if ( s !== 1 || !c || !c[0] ) {
4179 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
4180 }
4181
4182 // Initial estimate.
4183 s = Math.sqrt( +x );
4184
4185 // Math.sqrt underflow/overflow?
4186 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
4187 if ( s == 0 || s == 1 / 0 ) {
4188 n = coeffToString(c);
4189 if ( ( n.length + e ) % 2 == 0 ) n += '0';
4190 s = Math.sqrt(n);
4191 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
4192
4193 if ( s == 1 / 0 ) {
4194 n = '1e' + e;
4195 } else {
4196 n = s.toExponential();
4197 n = n.slice( 0, n.indexOf('e') + 1 ) + e;
4198 }
4199
4200 r = new BigNumber(n);
4201 } else {
4202 r = new BigNumber( s + '' );
4203 }
4204
4205 // Check for zero.
4206 // r could be zero if MIN_EXP is changed after the this value was created.
4207 // This would cause a division by zero (x/t) and hence Infinity below, which would cause
4208 // coeffToString to throw.
4209 if ( r.c[0] ) {
4210 e = r.e;
4211 s = e + dp;
4212 if ( s < 3 ) s = 0;
4213
4214 // Newton-Raphson iteration.
4215 for ( ; ; ) {
4216 t = r;
4217 r = half.times( t.plus( div( x, t, dp, 1 ) ) );
4218
4219 if ( coeffToString( t.c ).slice( 0, s ) === ( n =
4220 coeffToString( r.c ) ).slice( 0, s ) ) {
4221
4222 // The exponent of r may here be one less than the final result exponent,
4223 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
4224 // are indexed correctly.
4225 if ( r.e < e ) --s;
4226 n = n.slice( s - 3, s + 1 );
4227
4228 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
4229 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
4230 // iteration.
4231 if ( n == '9999' || !rep && n == '4999' ) {
4232
4233 // On the first iteration only, check to see if rounding up gives the
4234 // exact result as the nines may infinitely repeat.
4235 if ( !rep ) {
4236 round( t, t.e + DECIMAL_PLACES + 2, 0 );
4237
4238 if ( t.times(t).eq(x) ) {
4239 r = t;
4240 break;
4241 }
4242 }
4243
4244 dp += 4;
4245 s += 4;
4246 rep = 1;
4247 } else {
4248
4249 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
4250 // result. If not, then there are further digits and m will be truthy.
4251 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
4252
4253 // Truncate to the first rounding digit.
4254 round( r, r.e + DECIMAL_PLACES + 2, 1 );
4255 m = !r.times(r).eq(x);
4256 }
4257
4258 break;
4259 }
4260 }
4261 }
4262 }
4263
4264 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
4265 };
4266
4267
4268 /*
4269 * n * 0 = 0
4270 * n * N = N
4271 * n * I = I
4272 * 0 * n = 0
4273 * 0 * 0 = 0
4274 * 0 * N = N
4275 * 0 * I = N
4276 * N * n = N
4277 * N * 0 = N
4278 * N * N = N
4279 * N * I = N
4280 * I * n = I
4281 * I * 0 = N
4282 * I * N = N
4283 * I * I = I
4284 *
4285 * Return a new BigNumber whose value is the value of this BigNumber times the value of
4286 * BigNumber(y, b).
4287 */
4288 P.times = P.mul = function ( y, b ) {
4289 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
4290 base, sqrtBase,
4291 x = this,
4292 xc = x.c,
4293 yc = ( id = 17, y = new BigNumber( y, b ) ).c;
4294
4295 // Either NaN, ±Infinity or ±0?
4296 if ( !xc || !yc || !xc[0] || !yc[0] ) {
4297
4298 // Return NaN if either is NaN, or one is 0 and the other is Infinity.
4299 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
4300 y.c = y.e = y.s = null;
4301 } else {
4302 y.s *= x.s;
4303
4304 // Return ±Infinity if either is ±Infinity.
4305 if ( !xc || !yc ) {
4306 y.c = y.e = null;
4307
4308 // Return ±0 if either is ±0.
4309 } else {
4310 y.c = [0];
4311 y.e = 0;
4312 }
4313 }
4314
4315 return y;
4316 }
4317
4318 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
4319 y.s *= x.s;
4320 xcL = xc.length;
4321 ycL = yc.length;
4322
4323 // Ensure xc points to longer array and xcL to its length.
4324 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
4325
4326 // Initialise the result array with zeros.
4327 for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
4328
4329 base = BASE;
4330 sqrtBase = SQRT_BASE;
4331
4332 for ( i = ycL; --i >= 0; ) {
4333 c = 0;
4334 ylo = yc[i] % sqrtBase;
4335 yhi = yc[i] / sqrtBase | 0;
4336
4337 for ( k = xcL, j = i + k; j > i; ) {
4338 xlo = xc[--k] % sqrtBase;
4339 xhi = xc[k] / sqrtBase | 0;
4340 m = yhi * xlo + xhi * ylo;
4341 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
4342 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
4343 zc[j--] = xlo % base;
4344 }
4345
4346 zc[j] = c;
4347 }
4348
4349 if (c) {
4350 ++e;
4351 } else {
4352 zc.splice(0, 1);
4353 }
4354
4355 return normalise( y, zc, e );
4356 };
4357
4358
4359 /*
4360 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
4361 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
4362 *
4363 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
4364 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4365 *
4366 * 'toDigits() precision out of range: {sd}'
4367 * 'toDigits() precision not an integer: {sd}'
4368 * 'toDigits() rounding mode not an integer: {rm}'
4369 * 'toDigits() rounding mode out of range: {rm}'
4370 */
4371 P.toDigits = function ( sd, rm ) {
4372 var n = new BigNumber(this);
4373 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
4374 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
4375 return sd ? round( n, sd, rm ) : n;
4376 };
4377
4378
4379 /*
4380 * Return a string representing the value of this BigNumber in exponential notation and
4381 * rounded using ROUNDING_MODE to dp fixed decimal places.
4382 *
4383 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4384 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4385 *
4386 * 'toExponential() decimal places not an integer: {dp}'
4387 * 'toExponential() decimal places out of range: {dp}'
4388 * 'toExponential() rounding mode not an integer: {rm}'
4389 * 'toExponential() rounding mode out of range: {rm}'
4390 */
4391 P.toExponential = function ( dp, rm ) {
4392 return format( this,
4393 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
4394 };
4395
4396
4397 /*
4398 * Return a string representing the value of this BigNumber in fixed-point notation rounding
4399 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
4400 *
4401 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
4402 * but e.g. (-0.00001).toFixed(0) is '-0'.
4403 *
4404 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4405 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4406 *
4407 * 'toFixed() decimal places not an integer: {dp}'
4408 * 'toFixed() decimal places out of range: {dp}'
4409 * 'toFixed() rounding mode not an integer: {rm}'
4410 * 'toFixed() rounding mode out of range: {rm}'
4411 */
4412 P.toFixed = function ( dp, rm ) {
4413 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
4414 ? ~~dp + this.e + 1 : null, rm, 20 );
4415 };
4416
4417
4418 /*
4419 * Return a string representing the value of this BigNumber in fixed-point notation rounded
4420 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
4421 * of the FORMAT object (see BigNumber.config).
4422 *
4423 * FORMAT = {
4424 * decimalSeparator : '.',
4425 * groupSeparator : ',',
4426 * groupSize : 3,
4427 * secondaryGroupSize : 0,
4428 * fractionGroupSeparator : '\xA0', // non-breaking space
4429 * fractionGroupSize : 0
4430 * };
4431 *
4432 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4433 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4434 *
4435 * 'toFormat() decimal places not an integer: {dp}'
4436 * 'toFormat() decimal places out of range: {dp}'
4437 * 'toFormat() rounding mode not an integer: {rm}'
4438 * 'toFormat() rounding mode out of range: {rm}'
4439 */
4440 P.toFormat = function ( dp, rm ) {
4441 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
4442 ? ~~dp + this.e + 1 : null, rm, 21 );
4443
4444 if ( this.c ) {
4445 var i,
4446 arr = str.split('.'),
4447 g1 = +FORMAT.groupSize,
4448 g2 = +FORMAT.secondaryGroupSize,
4449 groupSeparator = FORMAT.groupSeparator,
4450 intPart = arr[0],
4451 fractionPart = arr[1],
4452 isNeg = this.s < 0,
4453 intDigits = isNeg ? intPart.slice(1) : intPart,
4454 len = intDigits.length;
4455
4456 if (g2) i = g1, g1 = g2, g2 = i, len -= i;
4457
4458 if ( g1 > 0 && len > 0 ) {
4459 i = len % g1 || g1;
4460 intPart = intDigits.substr( 0, i );
4461
4462 for ( ; i < len; i += g1 ) {
4463 intPart += groupSeparator + intDigits.substr( i, g1 );
4464 }
4465
4466 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
4467 if (isNeg) intPart = '-' + intPart;
4468 }
4469
4470 str = fractionPart
4471 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
4472 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
4473 '$&' + FORMAT.fractionGroupSeparator )
4474 : fractionPart )
4475 : intPart;
4476 }
4477
4478 return str;
4479 };
4480
4481
4482 /*
4483 * Return a string array representing the value of this BigNumber as a simple fraction with
4484 * an integer numerator and an integer denominator. The denominator will be a positive
4485 * non-zero value less than or equal to the specified maximum denominator. If a maximum
4486 * denominator is not specified, the denominator will be the lowest value necessary to
4487 * represent the number exactly.
4488 *
4489 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
4490 *
4491 * 'toFraction() max denominator not an integer: {md}'
4492 * 'toFraction() max denominator out of range: {md}'
4493 */
4494 P.toFraction = function (md) {
4495 var arr, d0, d2, e, exp, n, n0, q, s,
4496 k = ERRORS,
4497 x = this,
4498 xc = x.c,
4499 d = new BigNumber(ONE),
4500 n1 = d0 = new BigNumber(ONE),
4501 d1 = n0 = new BigNumber(ONE);
4502
4503 if ( md != null ) {
4504 ERRORS = false;
4505 n = new BigNumber(md);
4506 ERRORS = k;
4507
4508 if ( !( k = n.isInt() ) || n.lt(ONE) ) {
4509
4510 if (ERRORS) {
4511 raise( 22,
4512 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
4513 }
4514
4515 // ERRORS is false:
4516 // If md is a finite non-integer >= 1, round it to an integer and use it.
4517 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
4518 }
4519 }
4520
4521 if ( !xc ) return x.toString();
4522 s = coeffToString(xc);
4523
4524 // Determine initial denominator.
4525 // d is a power of 10 and the minimum max denominator that specifies the value exactly.
4526 e = d.e = s.length - x.e - 1;
4527 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
4528 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
4529
4530 exp = MAX_EXP;
4531 MAX_EXP = 1 / 0;
4532 n = new BigNumber(s);
4533
4534 // n0 = d1 = 0
4535 n0.c[0] = 0;
4536
4537 for ( ; ; ) {
4538 q = div( n, d, 0, 1 );
4539 d2 = d0.plus( q.times(d1) );
4540 if ( d2.cmp(md) == 1 ) break;
4541 d0 = d1;
4542 d1 = d2;
4543 n1 = n0.plus( q.times( d2 = n1 ) );
4544 n0 = d2;
4545 d = n.minus( q.times( d2 = d ) );
4546 n = d2;
4547 }
4548
4549 d2 = div( md.minus(d0), d1, 0, 1 );
4550 n0 = n0.plus( d2.times(n1) );
4551 d0 = d0.plus( d2.times(d1) );
4552 n0.s = n1.s = x.s;
4553 e *= 2;
4554
4555 // Determine which fraction is closer to x, n0/d0 or n1/d1
4556 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
4557 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
4558 ? [ n1.toString(), d1.toString() ]
4559 : [ n0.toString(), d0.toString() ];
4560
4561 MAX_EXP = exp;
4562 return arr;
4563 };
4564
4565
4566 /*
4567 * Return the value of this BigNumber converted to a number primitive.
4568 */
4569 P.toNumber = function () {
4570 return +this;
4571 };
4572
4573
4574 /*
4575 * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
4576 * If m is present, return the result modulo m.
4577 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
4578 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
4579 * ROUNDING_MODE.
4580 *
4581 * The modular power operation works efficiently when x, n, and m are positive integers,
4582 * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
4583 *
4584 * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
4585 * [m] {number|string|BigNumber} The modulus.
4586 *
4587 * 'pow() exponent not an integer: {n}'
4588 * 'pow() exponent out of range: {n}'
4589 *
4590 * Performs 54 loop iterations for n of 9007199254740991.
4591 */
4592 P.toPower = P.pow = function ( n, m ) {
4593 var k, y, z,
4594 i = mathfloor( n < 0 ? -n : +n ),
4595 x = this;
4596
4597 if ( m != null ) {
4598 id = 23;
4599 m = new BigNumber(m);
4600 }
4601
4602 // Pass ±Infinity to Math.pow if exponent is out of range.
4603 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
4604 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
4605 parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
4606 k = Math.pow( +x, n );
4607 return new BigNumber( m ? k % m : k );
4608 }
4609
4610 if (m) {
4611 if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
4612 x = x.mod(m);
4613 } else {
4614 z = m;
4615
4616 // Nullify m so only a single mod operation is performed at the end.
4617 m = null;
4618 }
4619 } else if (POW_PRECISION) {
4620
4621 // Truncating each coefficient array to a length of k after each multiplication
4622 // equates to truncating significant digits to POW_PRECISION + [28, 41],
4623 // i.e. there will be a minimum of 28 guard digits retained.
4624 // (Using + 1.5 would give [9, 21] guard digits.)
4625 k = mathceil( POW_PRECISION / LOG_BASE + 2 );
4626 }
4627
4628 y = new BigNumber(ONE);
4629
4630 for ( ; ; ) {
4631 if ( i % 2 ) {
4632 y = y.times(x);
4633 if ( !y.c ) break;
4634 if (k) {
4635 if ( y.c.length > k ) y.c.length = k;
4636 } else if (m) {
4637 y = y.mod(m);
4638 }
4639 }
4640
4641 i = mathfloor( i / 2 );
4642 if ( !i ) break;
4643 x = x.times(x);
4644 if (k) {
4645 if ( x.c && x.c.length > k ) x.c.length = k;
4646 } else if (m) {
4647 x = x.mod(m);
4648 }
4649 }
4650
4651 if (m) return y;
4652 if ( n < 0 ) y = ONE.div(y);
4653
4654 return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
4655 };
4656
4657
4658 /*
4659 * Return a string representing the value of this BigNumber rounded to sd significant digits
4660 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
4661 * necessary to represent the integer part of the value in fixed-point notation, then use
4662 * exponential notation.
4663 *
4664 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
4665 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4666 *
4667 * 'toPrecision() precision not an integer: {sd}'
4668 * 'toPrecision() precision out of range: {sd}'
4669 * 'toPrecision() rounding mode not an integer: {rm}'
4670 * 'toPrecision() rounding mode out of range: {rm}'
4671 */
4672 P.toPrecision = function ( sd, rm ) {
4673 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
4674 ? sd | 0 : null, rm, 24 );
4675 };
4676
4677
4678 /*
4679 * Return a string representing the value of this BigNumber in base b, or base 10 if b is
4680 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
4681 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
4682 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
4683 * TO_EXP_NEG, return exponential notation.
4684 *
4685 * [b] {number} Integer, 2 to 64 inclusive.
4686 *
4687 * 'toString() base not an integer: {b}'
4688 * 'toString() base out of range: {b}'
4689 */
4690 P.toString = function (b) {
4691 var str,
4692 n = this,
4693 s = n.s,
4694 e = n.e;
4695
4696 // Infinity or NaN?
4697 if ( e === null ) {
4698
4699 if (s) {
4700 str = 'Infinity';
4701 if ( s < 0 ) str = '-' + str;
4702 } else {
4703 str = 'NaN';
4704 }
4705 } else {
4706 str = coeffToString( n.c );
4707
4708 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
4709 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
4710 ? toExponential( str, e )
4711 : toFixedPoint( str, e );
4712 } else {
4713 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
4714 }
4715
4716 if ( s < 0 && n.c[0] ) str = '-' + str;
4717 }
4718
4719 return str;
4720 };
4721
4722
4723 /*
4724 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
4725 * number.
4726 */
4727 P.truncated = P.trunc = function () {
4728 return round( new BigNumber(this), this.e + 1, 1 );
4729 };
4730
4731
4732 /*
4733 * Return as toString, but do not accept a base argument, and include the minus sign for
4734 * negative zero.
4735 */
4736 P.valueOf = P.toJSON = function () {
4737 var str,
4738 n = this,
4739 e = n.e;
4740
4741 if ( e === null ) return n.toString();
4742
4743 str = coeffToString( n.c );
4744
4745 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
4746 ? toExponential( str, e )
4747 : toFixedPoint( str, e );
4748
4749 return n.s < 0 ? '-' + str : str;
4750 };
4751
4752
4753 P.isBigNumber = true;
4754
4755 if ( config != null ) BigNumber.config(config);
4756
4757 return BigNumber;
4758 }
4759
4760
4761 // PRIVATE HELPER FUNCTIONS
4762
4763
4764 function bitFloor(n) {
4765 var i = n | 0;
4766 return n > 0 || n === i ? i : i - 1;
4767 }
4768
4769
4770 // Return a coefficient array as a string of base 10 digits.
4771 function coeffToString(a) {
4772 var s, z,
4773 i = 1,
4774 j = a.length,
4775 r = a[0] + '';
4776
4777 for ( ; i < j; ) {
4778 s = a[i++] + '';
4779 z = LOG_BASE - s.length;
4780 for ( ; z--; s = '0' + s );
4781 r += s;
4782 }
4783
4784 // Determine trailing zeros.
4785 for ( j = r.length; r.charCodeAt(--j) === 48; );
4786 return r.slice( 0, j + 1 || 1 );
4787 }
4788
4789
4790 // Compare the value of BigNumbers x and y.
4791 function compare( x, y ) {
4792 var a, b,
4793 xc = x.c,
4794 yc = y.c,
4795 i = x.s,
4796 j = y.s,
4797 k = x.e,
4798 l = y.e;
4799
4800 // Either NaN?
4801 if ( !i || !j ) return null;
4802
4803 a = xc && !xc[0];
4804 b = yc && !yc[0];
4805
4806 // Either zero?
4807 if ( a || b ) return a ? b ? 0 : -j : i;
4808
4809 // Signs differ?
4810 if ( i != j ) return i;
4811
4812 a = i < 0;
4813 b = k == l;
4814
4815 // Either Infinity?
4816 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
4817
4818 // Compare exponents.
4819 if ( !b ) return k > l ^ a ? 1 : -1;
4820
4821 j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
4822
4823 // Compare digit by digit.
4824 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
4825
4826 // Compare lengths.
4827 return k == l ? 0 : k > l ^ a ? 1 : -1;
4828 }
4829
4830
4831 /*
4832 * Return true if n is a valid number in range, otherwise false.
4833 * Use for argument validation when ERRORS is false.
4834 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
4835 */
4836 function intValidatorNoErrors( n, min, max ) {
4837 return ( n = truncate(n) ) >= min && n <= max;
4838 }
4839
4840
4841 function isArray(obj) {
4842 return Object.prototype.toString.call(obj) == '[object Array]';
4843 }
4844
4845
4846 /*
4847 * Convert string of baseIn to an array of numbers of baseOut.
4848 * Eg. convertBase('255', 10, 16) returns [15, 15].
4849 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
4850 */
4851 function toBaseOut( str, baseIn, baseOut ) {
4852 var j,
4853 arr = [0],
4854 arrL,
4855 i = 0,
4856 len = str.length;
4857
4858 for ( ; i < len; ) {
4859 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
4860 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
4861
4862 for ( ; j < arr.length; j++ ) {
4863
4864 if ( arr[j] > baseOut - 1 ) {
4865 if ( arr[j + 1] == null ) arr[j + 1] = 0;
4866 arr[j + 1] += arr[j] / baseOut | 0;
4867 arr[j] %= baseOut;
4868 }
4869 }
4870 }
4871
4872 return arr.reverse();
4873 }
4874
4875
4876 function toExponential( str, e ) {
4877 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
4878 ( e < 0 ? 'e' : 'e+' ) + e;
4879 }
4880
4881
4882 function toFixedPoint( str, e ) {
4883 var len, z;
4884
4885 // Negative exponent?
4886 if ( e < 0 ) {
4887
4888 // Prepend zeros.
4889 for ( z = '0.'; ++e; z += '0' );
4890 str = z + str;
4891
4892 // Positive exponent
4893 } else {
4894 len = str.length;
4895
4896 // Append zeros.
4897 if ( ++e > len ) {
4898 for ( z = '0', e -= len; --e; z += '0' );
4899 str += z;
4900 } else if ( e < len ) {
4901 str = str.slice( 0, e ) + '.' + str.slice(e);
4902 }
4903 }
4904
4905 return str;
4906 }
4907
4908
4909 function truncate(n) {
4910 n = parseFloat(n);
4911 return n < 0 ? mathceil(n) : mathfloor(n);
4912 }
4913
4914
4915 // EXPORT
4916
4917
4918 BigNumber = constructorFactory();
4919 BigNumber['default'] = BigNumber.BigNumber = BigNumber;
4920
4921
4922 // AMD.
4923 if ( typeof define == 'function' && define.amd ) {
4924 define( function () { return BigNumber; } );
4925
4926 // Node.js and other environments that support module.exports.
4927 } else if ( typeof module != 'undefined' && module.exports ) {
4928 module.exports = BigNumber;
4929
4930 // Browser.
4931 } else {
4932 if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
4933 globalObj.BigNumber = BigNumber;
4934 }
4935})(this);
4936
4937},{}],18:[function(require,module,exports){
4938(function (module, exports) {
4939 'use strict';
4940
4941 // Utils
4942 function assert (val, msg) {
4943 if (!val) throw new Error(msg || 'Assertion failed');
4944 }
4945
4946 // Could use `inherits` module, but don't want to move from single file
4947 // architecture yet.
4948 function inherits (ctor, superCtor) {
4949 ctor.super_ = superCtor;
4950 var TempCtor = function () {};
4951 TempCtor.prototype = superCtor.prototype;
4952 ctor.prototype = new TempCtor();
4953 ctor.prototype.constructor = ctor;
4954 }
4955
4956 // BN
4957
4958 function BN (number, base, endian) {
4959 if (BN.isBN(number)) {
4960 return number;
4961 }
4962
4963 this.negative = 0;
4964 this.words = null;
4965 this.length = 0;
4966
4967 // Reduction context
4968 this.red = null;
4969
4970 if (number !== null) {
4971 if (base === 'le' || base === 'be') {
4972 endian = base;
4973 base = 10;
4974 }
4975
4976 this._init(number || 0, base || 10, endian || 'be');
4977 }
4978 }
4979 if (typeof module === 'object') {
4980 module.exports = BN;
4981 } else {
4982 exports.BN = BN;
4983 }
4984
4985 BN.BN = BN;
4986 BN.wordSize = 26;
4987
4988 var Buffer;
4989 try {
4990 Buffer = require('buffer').Buffer;
4991 } catch (e) {
4992 }
4993
4994 BN.isBN = function isBN (num) {
4995 if (num instanceof BN) {
4996 return true;
4997 }
4998
4999 return num !== null && typeof num === 'object' &&
5000 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
5001 };
5002
5003 BN.max = function max (left, right) {
5004 if (left.cmp(right) > 0) return left;
5005 return right;
5006 };
5007
5008 BN.min = function min (left, right) {
5009 if (left.cmp(right) < 0) return left;
5010 return right;
5011 };
5012
5013 BN.prototype._init = function init (number, base, endian) {
5014 if (typeof number === 'number') {
5015 return this._initNumber(number, base, endian);
5016 }
5017
5018 if (typeof number === 'object') {
5019 return this._initArray(number, base, endian);
5020 }
5021
5022 if (base === 'hex') {
5023 base = 16;
5024 }
5025 assert(base === (base | 0) && base >= 2 && base <= 36);
5026
5027 number = number.toString().replace(/\s+/g, '');
5028 var start = 0;
5029 if (number[0] === '-') {
5030 start++;
5031 }
5032
5033 if (base === 16) {
5034 this._parseHex(number, start);
5035 } else {
5036 this._parseBase(number, base, start);
5037 }
5038
5039 if (number[0] === '-') {
5040 this.negative = 1;
5041 }
5042
5043 this.strip();
5044
5045 if (endian !== 'le') return;
5046
5047 this._initArray(this.toArray(), base, endian);
5048 };
5049
5050 BN.prototype._initNumber = function _initNumber (number, base, endian) {
5051 if (number < 0) {
5052 this.negative = 1;
5053 number = -number;
5054 }
5055 if (number < 0x4000000) {
5056 this.words = [ number & 0x3ffffff ];
5057 this.length = 1;
5058 } else if (number < 0x10000000000000) {
5059 this.words = [
5060 number & 0x3ffffff,
5061 (number / 0x4000000) & 0x3ffffff
5062 ];
5063 this.length = 2;
5064 } else {
5065 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
5066 this.words = [
5067 number & 0x3ffffff,
5068 (number / 0x4000000) & 0x3ffffff,
5069 1
5070 ];
5071 this.length = 3;
5072 }
5073
5074 if (endian !== 'le') return;
5075
5076 // Reverse the bytes
5077 this._initArray(this.toArray(), base, endian);
5078 };
5079
5080 BN.prototype._initArray = function _initArray (number, base, endian) {
5081 // Perhaps a Uint8Array
5082 assert(typeof number.length === 'number');
5083 if (number.length <= 0) {
5084 this.words = [ 0 ];
5085 this.length = 1;
5086 return this;
5087 }
5088
5089 this.length = Math.ceil(number.length / 3);
5090 this.words = new Array(this.length);
5091 for (var i = 0; i < this.length; i++) {
5092 this.words[i] = 0;
5093 }
5094
5095 var j, w;
5096 var off = 0;
5097 if (endian === 'be') {
5098 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
5099 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
5100 this.words[j] |= (w << off) & 0x3ffffff;
5101 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
5102 off += 24;
5103 if (off >= 26) {
5104 off -= 26;
5105 j++;
5106 }
5107 }
5108 } else if (endian === 'le') {
5109 for (i = 0, j = 0; i < number.length; i += 3) {
5110 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
5111 this.words[j] |= (w << off) & 0x3ffffff;
5112 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
5113 off += 24;
5114 if (off >= 26) {
5115 off -= 26;
5116 j++;
5117 }
5118 }
5119 }
5120 return this.strip();
5121 };
5122
5123 function parseHex (str, start, end) {
5124 var r = 0;
5125 var len = Math.min(str.length, end);
5126 for (var i = start; i < len; i++) {
5127 var c = str.charCodeAt(i) - 48;
5128
5129 r <<= 4;
5130
5131 // 'a' - 'f'
5132 if (c >= 49 && c <= 54) {
5133 r |= c - 49 + 0xa;
5134
5135 // 'A' - 'F'
5136 } else if (c >= 17 && c <= 22) {
5137 r |= c - 17 + 0xa;
5138
5139 // '0' - '9'
5140 } else {
5141 r |= c & 0xf;
5142 }
5143 }
5144 return r;
5145 }
5146
5147 BN.prototype._parseHex = function _parseHex (number, start) {
5148 // Create possibly bigger array to ensure that it fits the number
5149 this.length = Math.ceil((number.length - start) / 6);
5150 this.words = new Array(this.length);
5151 for (var i = 0; i < this.length; i++) {
5152 this.words[i] = 0;
5153 }
5154
5155 var j, w;
5156 // Scan 24-bit chunks and add them to the number
5157 var off = 0;
5158 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
5159 w = parseHex(number, i, i + 6);
5160 this.words[j] |= (w << off) & 0x3ffffff;
5161 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
5162 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
5163 off += 24;
5164 if (off >= 26) {
5165 off -= 26;
5166 j++;
5167 }
5168 }
5169 if (i + 6 !== start) {
5170 w = parseHex(number, start, i + 6);
5171 this.words[j] |= (w << off) & 0x3ffffff;
5172 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
5173 }
5174 this.strip();
5175 };
5176
5177 function parseBase (str, start, end, mul) {
5178 var r = 0;
5179 var len = Math.min(str.length, end);
5180 for (var i = start; i < len; i++) {
5181 var c = str.charCodeAt(i) - 48;
5182
5183 r *= mul;
5184
5185 // 'a'
5186 if (c >= 49) {
5187 r += c - 49 + 0xa;
5188
5189 // 'A'
5190 } else if (c >= 17) {
5191 r += c - 17 + 0xa;
5192
5193 // '0' - '9'
5194 } else {
5195 r += c;
5196 }
5197 }
5198 return r;
5199 }
5200
5201 BN.prototype._parseBase = function _parseBase (number, base, start) {
5202 // Initialize as zero
5203 this.words = [ 0 ];
5204 this.length = 1;
5205
5206 // Find length of limb in base
5207 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
5208 limbLen++;
5209 }
5210 limbLen--;
5211 limbPow = (limbPow / base) | 0;
5212
5213 var total = number.length - start;
5214 var mod = total % limbLen;
5215 var end = Math.min(total, total - mod) + start;
5216
5217 var word = 0;
5218 for (var i = start; i < end; i += limbLen) {
5219 word = parseBase(number, i, i + limbLen, base);
5220
5221 this.imuln(limbPow);
5222 if (this.words[0] + word < 0x4000000) {
5223 this.words[0] += word;
5224 } else {
5225 this._iaddn(word);
5226 }
5227 }
5228
5229 if (mod !== 0) {
5230 var pow = 1;
5231 word = parseBase(number, i, number.length, base);
5232
5233 for (i = 0; i < mod; i++) {
5234 pow *= base;
5235 }
5236
5237 this.imuln(pow);
5238 if (this.words[0] + word < 0x4000000) {
5239 this.words[0] += word;
5240 } else {
5241 this._iaddn(word);
5242 }
5243 }
5244 };
5245
5246 BN.prototype.copy = function copy (dest) {
5247 dest.words = new Array(this.length);
5248 for (var i = 0; i < this.length; i++) {
5249 dest.words[i] = this.words[i];
5250 }
5251 dest.length = this.length;
5252 dest.negative = this.negative;
5253 dest.red = this.red;
5254 };
5255
5256 BN.prototype.clone = function clone () {
5257 var r = new BN(null);
5258 this.copy(r);
5259 return r;
5260 };
5261
5262 BN.prototype._expand = function _expand (size) {
5263 while (this.length < size) {
5264 this.words[this.length++] = 0;
5265 }
5266 return this;
5267 };
5268
5269 // Remove leading `0` from `this`
5270 BN.prototype.strip = function strip () {
5271 while (this.length > 1 && this.words[this.length - 1] === 0) {
5272 this.length--;
5273 }
5274 return this._normSign();
5275 };
5276
5277 BN.prototype._normSign = function _normSign () {
5278 // -0 = 0
5279 if (this.length === 1 && this.words[0] === 0) {
5280 this.negative = 0;
5281 }
5282 return this;
5283 };
5284
5285 BN.prototype.inspect = function inspect () {
5286 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
5287 };
5288
5289 /*
5290
5291 var zeros = [];
5292 var groupSizes = [];
5293 var groupBases = [];
5294
5295 var s = '';
5296 var i = -1;
5297 while (++i < BN.wordSize) {
5298 zeros[i] = s;
5299 s += '0';
5300 }
5301 groupSizes[0] = 0;
5302 groupSizes[1] = 0;
5303 groupBases[0] = 0;
5304 groupBases[1] = 0;
5305 var base = 2 - 1;
5306 while (++base < 36 + 1) {
5307 var groupSize = 0;
5308 var groupBase = 1;
5309 while (groupBase < (1 << BN.wordSize) / base) {
5310 groupBase *= base;
5311 groupSize += 1;
5312 }
5313 groupSizes[base] = groupSize;
5314 groupBases[base] = groupBase;
5315 }
5316
5317 */
5318
5319 var zeros = [
5320 '',
5321 '0',
5322 '00',
5323 '000',
5324 '0000',
5325 '00000',
5326 '000000',
5327 '0000000',
5328 '00000000',
5329 '000000000',
5330 '0000000000',
5331 '00000000000',
5332 '000000000000',
5333 '0000000000000',
5334 '00000000000000',
5335 '000000000000000',
5336 '0000000000000000',
5337 '00000000000000000',
5338 '000000000000000000',
5339 '0000000000000000000',
5340 '00000000000000000000',
5341 '000000000000000000000',
5342 '0000000000000000000000',
5343 '00000000000000000000000',
5344 '000000000000000000000000',
5345 '0000000000000000000000000'
5346 ];
5347
5348 var groupSizes = [
5349 0, 0,
5350 25, 16, 12, 11, 10, 9, 8,
5351 8, 7, 7, 7, 7, 6, 6,
5352 6, 6, 6, 6, 6, 5, 5,
5353 5, 5, 5, 5, 5, 5, 5,
5354 5, 5, 5, 5, 5, 5, 5
5355 ];
5356
5357 var groupBases = [
5358 0, 0,
5359 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
5360 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
5361 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
5362 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
5363 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
5364 ];
5365
5366 BN.prototype.toString = function toString (base, padding) {
5367 base = base || 10;
5368 padding = padding | 0 || 1;
5369
5370 var out;
5371 if (base === 16 || base === 'hex') {
5372 out = '';
5373 var off = 0;
5374 var carry = 0;
5375 for (var i = 0; i < this.length; i++) {
5376 var w = this.words[i];
5377 var word = (((w << off) | carry) & 0xffffff).toString(16);
5378 carry = (w >>> (24 - off)) & 0xffffff;
5379 if (carry !== 0 || i !== this.length - 1) {
5380 out = zeros[6 - word.length] + word + out;
5381 } else {
5382 out = word + out;
5383 }
5384 off += 2;
5385 if (off >= 26) {
5386 off -= 26;
5387 i--;
5388 }
5389 }
5390 if (carry !== 0) {
5391 out = carry.toString(16) + out;
5392 }
5393 while (out.length % padding !== 0) {
5394 out = '0' + out;
5395 }
5396 if (this.negative !== 0) {
5397 out = '-' + out;
5398 }
5399 return out;
5400 }
5401
5402 if (base === (base | 0) && base >= 2 && base <= 36) {
5403 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
5404 var groupSize = groupSizes[base];
5405 // var groupBase = Math.pow(base, groupSize);
5406 var groupBase = groupBases[base];
5407 out = '';
5408 var c = this.clone();
5409 c.negative = 0;
5410 while (!c.isZero()) {
5411 var r = c.modn(groupBase).toString(base);
5412 c = c.idivn(groupBase);
5413
5414 if (!c.isZero()) {
5415 out = zeros[groupSize - r.length] + r + out;
5416 } else {
5417 out = r + out;
5418 }
5419 }
5420 if (this.isZero()) {
5421 out = '0' + out;
5422 }
5423 while (out.length % padding !== 0) {
5424 out = '0' + out;
5425 }
5426 if (this.negative !== 0) {
5427 out = '-' + out;
5428 }
5429 return out;
5430 }
5431
5432 assert(false, 'Base should be between 2 and 36');
5433 };
5434
5435 BN.prototype.toNumber = function toNumber () {
5436 var ret = this.words[0];
5437 if (this.length === 2) {
5438 ret += this.words[1] * 0x4000000;
5439 } else if (this.length === 3 && this.words[2] === 0x01) {
5440 // NOTE: at this stage it is known that the top bit is set
5441 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
5442 } else if (this.length > 2) {
5443 assert(false, 'Number can only safely store up to 53 bits');
5444 }
5445 return (this.negative !== 0) ? -ret : ret;
5446 };
5447
5448 BN.prototype.toJSON = function toJSON () {
5449 return this.toString(16);
5450 };
5451
5452 BN.prototype.toBuffer = function toBuffer (endian, length) {
5453 assert(typeof Buffer !== 'undefined');
5454 return this.toArrayLike(Buffer, endian, length);
5455 };
5456
5457 BN.prototype.toArray = function toArray (endian, length) {
5458 return this.toArrayLike(Array, endian, length);
5459 };
5460
5461 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
5462 var byteLength = this.byteLength();
5463 var reqLength = length || Math.max(1, byteLength);
5464 assert(byteLength <= reqLength, 'byte array longer than desired length');
5465 assert(reqLength > 0, 'Requested array length <= 0');
5466
5467 this.strip();
5468 var littleEndian = endian === 'le';
5469 var res = new ArrayType(reqLength);
5470
5471 var b, i;
5472 var q = this.clone();
5473 if (!littleEndian) {
5474 // Assume big-endian
5475 for (i = 0; i < reqLength - byteLength; i++) {
5476 res[i] = 0;
5477 }
5478
5479 for (i = 0; !q.isZero(); i++) {
5480 b = q.andln(0xff);
5481 q.iushrn(8);
5482
5483 res[reqLength - i - 1] = b;
5484 }
5485 } else {
5486 for (i = 0; !q.isZero(); i++) {
5487 b = q.andln(0xff);
5488 q.iushrn(8);
5489
5490 res[i] = b;
5491 }
5492
5493 for (; i < reqLength; i++) {
5494 res[i] = 0;
5495 }
5496 }
5497
5498 return res;
5499 };
5500
5501 if (Math.clz32) {
5502 BN.prototype._countBits = function _countBits (w) {
5503 return 32 - Math.clz32(w);
5504 };
5505 } else {
5506 BN.prototype._countBits = function _countBits (w) {
5507 var t = w;
5508 var r = 0;
5509 if (t >= 0x1000) {
5510 r += 13;
5511 t >>>= 13;
5512 }
5513 if (t >= 0x40) {
5514 r += 7;
5515 t >>>= 7;
5516 }
5517 if (t >= 0x8) {
5518 r += 4;
5519 t >>>= 4;
5520 }
5521 if (t >= 0x02) {
5522 r += 2;
5523 t >>>= 2;
5524 }
5525 return r + t;
5526 };
5527 }
5528
5529 BN.prototype._zeroBits = function _zeroBits (w) {
5530 // Short-cut
5531 if (w === 0) return 26;
5532
5533 var t = w;
5534 var r = 0;
5535 if ((t & 0x1fff) === 0) {
5536 r += 13;
5537 t >>>= 13;
5538 }
5539 if ((t & 0x7f) === 0) {
5540 r += 7;
5541 t >>>= 7;
5542 }
5543 if ((t & 0xf) === 0) {
5544 r += 4;
5545 t >>>= 4;
5546 }
5547 if ((t & 0x3) === 0) {
5548 r += 2;
5549 t >>>= 2;
5550 }
5551 if ((t & 0x1) === 0) {
5552 r++;
5553 }
5554 return r;
5555 };
5556
5557 // Return number of used bits in a BN
5558 BN.prototype.bitLength = function bitLength () {
5559 var w = this.words[this.length - 1];
5560 var hi = this._countBits(w);
5561 return (this.length - 1) * 26 + hi;
5562 };
5563
5564 function toBitArray (num) {
5565 var w = new Array(num.bitLength());
5566
5567 for (var bit = 0; bit < w.length; bit++) {
5568 var off = (bit / 26) | 0;
5569 var wbit = bit % 26;
5570
5571 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
5572 }
5573
5574 return w;
5575 }
5576
5577 // Number of trailing zero bits
5578 BN.prototype.zeroBits = function zeroBits () {
5579 if (this.isZero()) return 0;
5580
5581 var r = 0;
5582 for (var i = 0; i < this.length; i++) {
5583 var b = this._zeroBits(this.words[i]);
5584 r += b;
5585 if (b !== 26) break;
5586 }
5587 return r;
5588 };
5589
5590 BN.prototype.byteLength = function byteLength () {
5591 return Math.ceil(this.bitLength() / 8);
5592 };
5593
5594 BN.prototype.toTwos = function toTwos (width) {
5595 if (this.negative !== 0) {
5596 return this.abs().inotn(width).iaddn(1);
5597 }
5598 return this.clone();
5599 };
5600
5601 BN.prototype.fromTwos = function fromTwos (width) {
5602 if (this.testn(width - 1)) {
5603 return this.notn(width).iaddn(1).ineg();
5604 }
5605 return this.clone();
5606 };
5607
5608 BN.prototype.isNeg = function isNeg () {
5609 return this.negative !== 0;
5610 };
5611
5612 // Return negative clone of `this`
5613 BN.prototype.neg = function neg () {
5614 return this.clone().ineg();
5615 };
5616
5617 BN.prototype.ineg = function ineg () {
5618 if (!this.isZero()) {
5619 this.negative ^= 1;
5620 }
5621
5622 return this;
5623 };
5624
5625 // Or `num` with `this` in-place
5626 BN.prototype.iuor = function iuor (num) {
5627 while (this.length < num.length) {
5628 this.words[this.length++] = 0;
5629 }
5630
5631 for (var i = 0; i < num.length; i++) {
5632 this.words[i] = this.words[i] | num.words[i];
5633 }
5634
5635 return this.strip();
5636 };
5637
5638 BN.prototype.ior = function ior (num) {
5639 assert((this.negative | num.negative) === 0);
5640 return this.iuor(num);
5641 };
5642
5643 // Or `num` with `this`
5644 BN.prototype.or = function or (num) {
5645 if (this.length > num.length) return this.clone().ior(num);
5646 return num.clone().ior(this);
5647 };
5648
5649 BN.prototype.uor = function uor (num) {
5650 if (this.length > num.length) return this.clone().iuor(num);
5651 return num.clone().iuor(this);
5652 };
5653
5654 // And `num` with `this` in-place
5655 BN.prototype.iuand = function iuand (num) {
5656 // b = min-length(num, this)
5657 var b;
5658 if (this.length > num.length) {
5659 b = num;
5660 } else {
5661 b = this;
5662 }
5663
5664 for (var i = 0; i < b.length; i++) {
5665 this.words[i] = this.words[i] & num.words[i];
5666 }
5667
5668 this.length = b.length;
5669
5670 return this.strip();
5671 };
5672
5673 BN.prototype.iand = function iand (num) {
5674 assert((this.negative | num.negative) === 0);
5675 return this.iuand(num);
5676 };
5677
5678 // And `num` with `this`
5679 BN.prototype.and = function and (num) {
5680 if (this.length > num.length) return this.clone().iand(num);
5681 return num.clone().iand(this);
5682 };
5683
5684 BN.prototype.uand = function uand (num) {
5685 if (this.length > num.length) return this.clone().iuand(num);
5686 return num.clone().iuand(this);
5687 };
5688
5689 // Xor `num` with `this` in-place
5690 BN.prototype.iuxor = function iuxor (num) {
5691 // a.length > b.length
5692 var a;
5693 var b;
5694 if (this.length > num.length) {
5695 a = this;
5696 b = num;
5697 } else {
5698 a = num;
5699 b = this;
5700 }
5701
5702 for (var i = 0; i < b.length; i++) {
5703 this.words[i] = a.words[i] ^ b.words[i];
5704 }
5705
5706 if (this !== a) {
5707 for (; i < a.length; i++) {
5708 this.words[i] = a.words[i];
5709 }
5710 }
5711
5712 this.length = a.length;
5713
5714 return this.strip();
5715 };
5716
5717 BN.prototype.ixor = function ixor (num) {
5718 assert((this.negative | num.negative) === 0);
5719 return this.iuxor(num);
5720 };
5721
5722 // Xor `num` with `this`
5723 BN.prototype.xor = function xor (num) {
5724 if (this.length > num.length) return this.clone().ixor(num);
5725 return num.clone().ixor(this);
5726 };
5727
5728 BN.prototype.uxor = function uxor (num) {
5729 if (this.length > num.length) return this.clone().iuxor(num);
5730 return num.clone().iuxor(this);
5731 };
5732
5733 // Not ``this`` with ``width`` bitwidth
5734 BN.prototype.inotn = function inotn (width) {
5735 assert(typeof width === 'number' && width >= 0);
5736
5737 var bytesNeeded = Math.ceil(width / 26) | 0;
5738 var bitsLeft = width % 26;
5739
5740 // Extend the buffer with leading zeroes
5741 this._expand(bytesNeeded);
5742
5743 if (bitsLeft > 0) {
5744 bytesNeeded--;
5745 }
5746
5747 // Handle complete words
5748 for (var i = 0; i < bytesNeeded; i++) {
5749 this.words[i] = ~this.words[i] & 0x3ffffff;
5750 }
5751
5752 // Handle the residue
5753 if (bitsLeft > 0) {
5754 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
5755 }
5756
5757 // And remove leading zeroes
5758 return this.strip();
5759 };
5760
5761 BN.prototype.notn = function notn (width) {
5762 return this.clone().inotn(width);
5763 };
5764
5765 // Set `bit` of `this`
5766 BN.prototype.setn = function setn (bit, val) {
5767 assert(typeof bit === 'number' && bit >= 0);
5768
5769 var off = (bit / 26) | 0;
5770 var wbit = bit % 26;
5771
5772 this._expand(off + 1);
5773
5774 if (val) {
5775 this.words[off] = this.words[off] | (1 << wbit);
5776 } else {
5777 this.words[off] = this.words[off] & ~(1 << wbit);
5778 }
5779
5780 return this.strip();
5781 };
5782
5783 // Add `num` to `this` in-place
5784 BN.prototype.iadd = function iadd (num) {
5785 var r;
5786
5787 // negative + positive
5788 if (this.negative !== 0 && num.negative === 0) {
5789 this.negative = 0;
5790 r = this.isub(num);
5791 this.negative ^= 1;
5792 return this._normSign();
5793
5794 // positive + negative
5795 } else if (this.negative === 0 && num.negative !== 0) {
5796 num.negative = 0;
5797 r = this.isub(num);
5798 num.negative = 1;
5799 return r._normSign();
5800 }
5801
5802 // a.length > b.length
5803 var a, b;
5804 if (this.length > num.length) {
5805 a = this;
5806 b = num;
5807 } else {
5808 a = num;
5809 b = this;
5810 }
5811
5812 var carry = 0;
5813 for (var i = 0; i < b.length; i++) {
5814 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
5815 this.words[i] = r & 0x3ffffff;
5816 carry = r >>> 26;
5817 }
5818 for (; carry !== 0 && i < a.length; i++) {
5819 r = (a.words[i] | 0) + carry;
5820 this.words[i] = r & 0x3ffffff;
5821 carry = r >>> 26;
5822 }
5823
5824 this.length = a.length;
5825 if (carry !== 0) {
5826 this.words[this.length] = carry;
5827 this.length++;
5828 // Copy the rest of the words
5829 } else if (a !== this) {
5830 for (; i < a.length; i++) {
5831 this.words[i] = a.words[i];
5832 }
5833 }
5834
5835 return this;
5836 };
5837
5838 // Add `num` to `this`
5839 BN.prototype.add = function add (num) {
5840 var res;
5841 if (num.negative !== 0 && this.negative === 0) {
5842 num.negative = 0;
5843 res = this.sub(num);
5844 num.negative ^= 1;
5845 return res;
5846 } else if (num.negative === 0 && this.negative !== 0) {
5847 this.negative = 0;
5848 res = num.sub(this);
5849 this.negative = 1;
5850 return res;
5851 }
5852
5853 if (this.length > num.length) return this.clone().iadd(num);
5854
5855 return num.clone().iadd(this);
5856 };
5857
5858 // Subtract `num` from `this` in-place
5859 BN.prototype.isub = function isub (num) {
5860 // this - (-num) = this + num
5861 if (num.negative !== 0) {
5862 num.negative = 0;
5863 var r = this.iadd(num);
5864 num.negative = 1;
5865 return r._normSign();
5866
5867 // -this - num = -(this + num)
5868 } else if (this.negative !== 0) {
5869 this.negative = 0;
5870 this.iadd(num);
5871 this.negative = 1;
5872 return this._normSign();
5873 }
5874
5875 // At this point both numbers are positive
5876 var cmp = this.cmp(num);
5877
5878 // Optimization - zeroify
5879 if (cmp === 0) {
5880 this.negative = 0;
5881 this.length = 1;
5882 this.words[0] = 0;
5883 return this;
5884 }
5885
5886 // a > b
5887 var a, b;
5888 if (cmp > 0) {
5889 a = this;
5890 b = num;
5891 } else {
5892 a = num;
5893 b = this;
5894 }
5895
5896 var carry = 0;
5897 for (var i = 0; i < b.length; i++) {
5898 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
5899 carry = r >> 26;
5900 this.words[i] = r & 0x3ffffff;
5901 }
5902 for (; carry !== 0 && i < a.length; i++) {
5903 r = (a.words[i] | 0) + carry;
5904 carry = r >> 26;
5905 this.words[i] = r & 0x3ffffff;
5906 }
5907
5908 // Copy rest of the words
5909 if (carry === 0 && i < a.length && a !== this) {
5910 for (; i < a.length; i++) {
5911 this.words[i] = a.words[i];
5912 }
5913 }
5914
5915 this.length = Math.max(this.length, i);
5916
5917 if (a !== this) {
5918 this.negative = 1;
5919 }
5920
5921 return this.strip();
5922 };
5923
5924 // Subtract `num` from `this`
5925 BN.prototype.sub = function sub (num) {
5926 return this.clone().isub(num);
5927 };
5928
5929 function smallMulTo (self, num, out) {
5930 out.negative = num.negative ^ self.negative;
5931 var len = (self.length + num.length) | 0;
5932 out.length = len;
5933 len = (len - 1) | 0;
5934
5935 // Peel one iteration (compiler can't do it, because of code complexity)
5936 var a = self.words[0] | 0;
5937 var b = num.words[0] | 0;
5938 var r = a * b;
5939
5940 var lo = r & 0x3ffffff;
5941 var carry = (r / 0x4000000) | 0;
5942 out.words[0] = lo;
5943
5944 for (var k = 1; k < len; k++) {
5945 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
5946 // note that ncarry could be >= 0x3ffffff
5947 var ncarry = carry >>> 26;
5948 var rword = carry & 0x3ffffff;
5949 var maxJ = Math.min(k, num.length - 1);
5950 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
5951 var i = (k - j) | 0;
5952 a = self.words[i] | 0;
5953 b = num.words[j] | 0;
5954 r = a * b + rword;
5955 ncarry += (r / 0x4000000) | 0;
5956 rword = r & 0x3ffffff;
5957 }
5958 out.words[k] = rword | 0;
5959 carry = ncarry | 0;
5960 }
5961 if (carry !== 0) {
5962 out.words[k] = carry | 0;
5963 } else {
5964 out.length--;
5965 }
5966
5967 return out.strip();
5968 }
5969
5970 // TODO(indutny): it may be reasonable to omit it for users who don't need
5971 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
5972 // multiplication (like elliptic secp256k1).
5973 var comb10MulTo = function comb10MulTo (self, num, out) {
5974 var a = self.words;
5975 var b = num.words;
5976 var o = out.words;
5977 var c = 0;
5978 var lo;
5979 var mid;
5980 var hi;
5981 var a0 = a[0] | 0;
5982 var al0 = a0 & 0x1fff;
5983 var ah0 = a0 >>> 13;
5984 var a1 = a[1] | 0;
5985 var al1 = a1 & 0x1fff;
5986 var ah1 = a1 >>> 13;
5987 var a2 = a[2] | 0;
5988 var al2 = a2 & 0x1fff;
5989 var ah2 = a2 >>> 13;
5990 var a3 = a[3] | 0;
5991 var al3 = a3 & 0x1fff;
5992 var ah3 = a3 >>> 13;
5993 var a4 = a[4] | 0;
5994 var al4 = a4 & 0x1fff;
5995 var ah4 = a4 >>> 13;
5996 var a5 = a[5] | 0;
5997 var al5 = a5 & 0x1fff;
5998 var ah5 = a5 >>> 13;
5999 var a6 = a[6] | 0;
6000 var al6 = a6 & 0x1fff;
6001 var ah6 = a6 >>> 13;
6002 var a7 = a[7] | 0;
6003 var al7 = a7 & 0x1fff;
6004 var ah7 = a7 >>> 13;
6005 var a8 = a[8] | 0;
6006 var al8 = a8 & 0x1fff;
6007 var ah8 = a8 >>> 13;
6008 var a9 = a[9] | 0;
6009 var al9 = a9 & 0x1fff;
6010 var ah9 = a9 >>> 13;
6011 var b0 = b[0] | 0;
6012 var bl0 = b0 & 0x1fff;
6013 var bh0 = b0 >>> 13;
6014 var b1 = b[1] | 0;
6015 var bl1 = b1 & 0x1fff;
6016 var bh1 = b1 >>> 13;
6017 var b2 = b[2] | 0;
6018 var bl2 = b2 & 0x1fff;
6019 var bh2 = b2 >>> 13;
6020 var b3 = b[3] | 0;
6021 var bl3 = b3 & 0x1fff;
6022 var bh3 = b3 >>> 13;
6023 var b4 = b[4] | 0;
6024 var bl4 = b4 & 0x1fff;
6025 var bh4 = b4 >>> 13;
6026 var b5 = b[5] | 0;
6027 var bl5 = b5 & 0x1fff;
6028 var bh5 = b5 >>> 13;
6029 var b6 = b[6] | 0;
6030 var bl6 = b6 & 0x1fff;
6031 var bh6 = b6 >>> 13;
6032 var b7 = b[7] | 0;
6033 var bl7 = b7 & 0x1fff;
6034 var bh7 = b7 >>> 13;
6035 var b8 = b[8] | 0;
6036 var bl8 = b8 & 0x1fff;
6037 var bh8 = b8 >>> 13;
6038 var b9 = b[9] | 0;
6039 var bl9 = b9 & 0x1fff;
6040 var bh9 = b9 >>> 13;
6041
6042 out.negative = self.negative ^ num.negative;
6043 out.length = 19;
6044 /* k = 0 */
6045 lo = Math.imul(al0, bl0);
6046 mid = Math.imul(al0, bh0);
6047 mid = (mid + Math.imul(ah0, bl0)) | 0;
6048 hi = Math.imul(ah0, bh0);
6049 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6050 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
6051 w0 &= 0x3ffffff;
6052 /* k = 1 */
6053 lo = Math.imul(al1, bl0);
6054 mid = Math.imul(al1, bh0);
6055 mid = (mid + Math.imul(ah1, bl0)) | 0;
6056 hi = Math.imul(ah1, bh0);
6057 lo = (lo + Math.imul(al0, bl1)) | 0;
6058 mid = (mid + Math.imul(al0, bh1)) | 0;
6059 mid = (mid + Math.imul(ah0, bl1)) | 0;
6060 hi = (hi + Math.imul(ah0, bh1)) | 0;
6061 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6062 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
6063 w1 &= 0x3ffffff;
6064 /* k = 2 */
6065 lo = Math.imul(al2, bl0);
6066 mid = Math.imul(al2, bh0);
6067 mid = (mid + Math.imul(ah2, bl0)) | 0;
6068 hi = Math.imul(ah2, bh0);
6069 lo = (lo + Math.imul(al1, bl1)) | 0;
6070 mid = (mid + Math.imul(al1, bh1)) | 0;
6071 mid = (mid + Math.imul(ah1, bl1)) | 0;
6072 hi = (hi + Math.imul(ah1, bh1)) | 0;
6073 lo = (lo + Math.imul(al0, bl2)) | 0;
6074 mid = (mid + Math.imul(al0, bh2)) | 0;
6075 mid = (mid + Math.imul(ah0, bl2)) | 0;
6076 hi = (hi + Math.imul(ah0, bh2)) | 0;
6077 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6078 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
6079 w2 &= 0x3ffffff;
6080 /* k = 3 */
6081 lo = Math.imul(al3, bl0);
6082 mid = Math.imul(al3, bh0);
6083 mid = (mid + Math.imul(ah3, bl0)) | 0;
6084 hi = Math.imul(ah3, bh0);
6085 lo = (lo + Math.imul(al2, bl1)) | 0;
6086 mid = (mid + Math.imul(al2, bh1)) | 0;
6087 mid = (mid + Math.imul(ah2, bl1)) | 0;
6088 hi = (hi + Math.imul(ah2, bh1)) | 0;
6089 lo = (lo + Math.imul(al1, bl2)) | 0;
6090 mid = (mid + Math.imul(al1, bh2)) | 0;
6091 mid = (mid + Math.imul(ah1, bl2)) | 0;
6092 hi = (hi + Math.imul(ah1, bh2)) | 0;
6093 lo = (lo + Math.imul(al0, bl3)) | 0;
6094 mid = (mid + Math.imul(al0, bh3)) | 0;
6095 mid = (mid + Math.imul(ah0, bl3)) | 0;
6096 hi = (hi + Math.imul(ah0, bh3)) | 0;
6097 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6098 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
6099 w3 &= 0x3ffffff;
6100 /* k = 4 */
6101 lo = Math.imul(al4, bl0);
6102 mid = Math.imul(al4, bh0);
6103 mid = (mid + Math.imul(ah4, bl0)) | 0;
6104 hi = Math.imul(ah4, bh0);
6105 lo = (lo + Math.imul(al3, bl1)) | 0;
6106 mid = (mid + Math.imul(al3, bh1)) | 0;
6107 mid = (mid + Math.imul(ah3, bl1)) | 0;
6108 hi = (hi + Math.imul(ah3, bh1)) | 0;
6109 lo = (lo + Math.imul(al2, bl2)) | 0;
6110 mid = (mid + Math.imul(al2, bh2)) | 0;
6111 mid = (mid + Math.imul(ah2, bl2)) | 0;
6112 hi = (hi + Math.imul(ah2, bh2)) | 0;
6113 lo = (lo + Math.imul(al1, bl3)) | 0;
6114 mid = (mid + Math.imul(al1, bh3)) | 0;
6115 mid = (mid + Math.imul(ah1, bl3)) | 0;
6116 hi = (hi + Math.imul(ah1, bh3)) | 0;
6117 lo = (lo + Math.imul(al0, bl4)) | 0;
6118 mid = (mid + Math.imul(al0, bh4)) | 0;
6119 mid = (mid + Math.imul(ah0, bl4)) | 0;
6120 hi = (hi + Math.imul(ah0, bh4)) | 0;
6121 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6122 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
6123 w4 &= 0x3ffffff;
6124 /* k = 5 */
6125 lo = Math.imul(al5, bl0);
6126 mid = Math.imul(al5, bh0);
6127 mid = (mid + Math.imul(ah5, bl0)) | 0;
6128 hi = Math.imul(ah5, bh0);
6129 lo = (lo + Math.imul(al4, bl1)) | 0;
6130 mid = (mid + Math.imul(al4, bh1)) | 0;
6131 mid = (mid + Math.imul(ah4, bl1)) | 0;
6132 hi = (hi + Math.imul(ah4, bh1)) | 0;
6133 lo = (lo + Math.imul(al3, bl2)) | 0;
6134 mid = (mid + Math.imul(al3, bh2)) | 0;
6135 mid = (mid + Math.imul(ah3, bl2)) | 0;
6136 hi = (hi + Math.imul(ah3, bh2)) | 0;
6137 lo = (lo + Math.imul(al2, bl3)) | 0;
6138 mid = (mid + Math.imul(al2, bh3)) | 0;
6139 mid = (mid + Math.imul(ah2, bl3)) | 0;
6140 hi = (hi + Math.imul(ah2, bh3)) | 0;
6141 lo = (lo + Math.imul(al1, bl4)) | 0;
6142 mid = (mid + Math.imul(al1, bh4)) | 0;
6143 mid = (mid + Math.imul(ah1, bl4)) | 0;
6144 hi = (hi + Math.imul(ah1, bh4)) | 0;
6145 lo = (lo + Math.imul(al0, bl5)) | 0;
6146 mid = (mid + Math.imul(al0, bh5)) | 0;
6147 mid = (mid + Math.imul(ah0, bl5)) | 0;
6148 hi = (hi + Math.imul(ah0, bh5)) | 0;
6149 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6150 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
6151 w5 &= 0x3ffffff;
6152 /* k = 6 */
6153 lo = Math.imul(al6, bl0);
6154 mid = Math.imul(al6, bh0);
6155 mid = (mid + Math.imul(ah6, bl0)) | 0;
6156 hi = Math.imul(ah6, bh0);
6157 lo = (lo + Math.imul(al5, bl1)) | 0;
6158 mid = (mid + Math.imul(al5, bh1)) | 0;
6159 mid = (mid + Math.imul(ah5, bl1)) | 0;
6160 hi = (hi + Math.imul(ah5, bh1)) | 0;
6161 lo = (lo + Math.imul(al4, bl2)) | 0;
6162 mid = (mid + Math.imul(al4, bh2)) | 0;
6163 mid = (mid + Math.imul(ah4, bl2)) | 0;
6164 hi = (hi + Math.imul(ah4, bh2)) | 0;
6165 lo = (lo + Math.imul(al3, bl3)) | 0;
6166 mid = (mid + Math.imul(al3, bh3)) | 0;
6167 mid = (mid + Math.imul(ah3, bl3)) | 0;
6168 hi = (hi + Math.imul(ah3, bh3)) | 0;
6169 lo = (lo + Math.imul(al2, bl4)) | 0;
6170 mid = (mid + Math.imul(al2, bh4)) | 0;
6171 mid = (mid + Math.imul(ah2, bl4)) | 0;
6172 hi = (hi + Math.imul(ah2, bh4)) | 0;
6173 lo = (lo + Math.imul(al1, bl5)) | 0;
6174 mid = (mid + Math.imul(al1, bh5)) | 0;
6175 mid = (mid + Math.imul(ah1, bl5)) | 0;
6176 hi = (hi + Math.imul(ah1, bh5)) | 0;
6177 lo = (lo + Math.imul(al0, bl6)) | 0;
6178 mid = (mid + Math.imul(al0, bh6)) | 0;
6179 mid = (mid + Math.imul(ah0, bl6)) | 0;
6180 hi = (hi + Math.imul(ah0, bh6)) | 0;
6181 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6182 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
6183 w6 &= 0x3ffffff;
6184 /* k = 7 */
6185 lo = Math.imul(al7, bl0);
6186 mid = Math.imul(al7, bh0);
6187 mid = (mid + Math.imul(ah7, bl0)) | 0;
6188 hi = Math.imul(ah7, bh0);
6189 lo = (lo + Math.imul(al6, bl1)) | 0;
6190 mid = (mid + Math.imul(al6, bh1)) | 0;
6191 mid = (mid + Math.imul(ah6, bl1)) | 0;
6192 hi = (hi + Math.imul(ah6, bh1)) | 0;
6193 lo = (lo + Math.imul(al5, bl2)) | 0;
6194 mid = (mid + Math.imul(al5, bh2)) | 0;
6195 mid = (mid + Math.imul(ah5, bl2)) | 0;
6196 hi = (hi + Math.imul(ah5, bh2)) | 0;
6197 lo = (lo + Math.imul(al4, bl3)) | 0;
6198 mid = (mid + Math.imul(al4, bh3)) | 0;
6199 mid = (mid + Math.imul(ah4, bl3)) | 0;
6200 hi = (hi + Math.imul(ah4, bh3)) | 0;
6201 lo = (lo + Math.imul(al3, bl4)) | 0;
6202 mid = (mid + Math.imul(al3, bh4)) | 0;
6203 mid = (mid + Math.imul(ah3, bl4)) | 0;
6204 hi = (hi + Math.imul(ah3, bh4)) | 0;
6205 lo = (lo + Math.imul(al2, bl5)) | 0;
6206 mid = (mid + Math.imul(al2, bh5)) | 0;
6207 mid = (mid + Math.imul(ah2, bl5)) | 0;
6208 hi = (hi + Math.imul(ah2, bh5)) | 0;
6209 lo = (lo + Math.imul(al1, bl6)) | 0;
6210 mid = (mid + Math.imul(al1, bh6)) | 0;
6211 mid = (mid + Math.imul(ah1, bl6)) | 0;
6212 hi = (hi + Math.imul(ah1, bh6)) | 0;
6213 lo = (lo + Math.imul(al0, bl7)) | 0;
6214 mid = (mid + Math.imul(al0, bh7)) | 0;
6215 mid = (mid + Math.imul(ah0, bl7)) | 0;
6216 hi = (hi + Math.imul(ah0, bh7)) | 0;
6217 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6218 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
6219 w7 &= 0x3ffffff;
6220 /* k = 8 */
6221 lo = Math.imul(al8, bl0);
6222 mid = Math.imul(al8, bh0);
6223 mid = (mid + Math.imul(ah8, bl0)) | 0;
6224 hi = Math.imul(ah8, bh0);
6225 lo = (lo + Math.imul(al7, bl1)) | 0;
6226 mid = (mid + Math.imul(al7, bh1)) | 0;
6227 mid = (mid + Math.imul(ah7, bl1)) | 0;
6228 hi = (hi + Math.imul(ah7, bh1)) | 0;
6229 lo = (lo + Math.imul(al6, bl2)) | 0;
6230 mid = (mid + Math.imul(al6, bh2)) | 0;
6231 mid = (mid + Math.imul(ah6, bl2)) | 0;
6232 hi = (hi + Math.imul(ah6, bh2)) | 0;
6233 lo = (lo + Math.imul(al5, bl3)) | 0;
6234 mid = (mid + Math.imul(al5, bh3)) | 0;
6235 mid = (mid + Math.imul(ah5, bl3)) | 0;
6236 hi = (hi + Math.imul(ah5, bh3)) | 0;
6237 lo = (lo + Math.imul(al4, bl4)) | 0;
6238 mid = (mid + Math.imul(al4, bh4)) | 0;
6239 mid = (mid + Math.imul(ah4, bl4)) | 0;
6240 hi = (hi + Math.imul(ah4, bh4)) | 0;
6241 lo = (lo + Math.imul(al3, bl5)) | 0;
6242 mid = (mid + Math.imul(al3, bh5)) | 0;
6243 mid = (mid + Math.imul(ah3, bl5)) | 0;
6244 hi = (hi + Math.imul(ah3, bh5)) | 0;
6245 lo = (lo + Math.imul(al2, bl6)) | 0;
6246 mid = (mid + Math.imul(al2, bh6)) | 0;
6247 mid = (mid + Math.imul(ah2, bl6)) | 0;
6248 hi = (hi + Math.imul(ah2, bh6)) | 0;
6249 lo = (lo + Math.imul(al1, bl7)) | 0;
6250 mid = (mid + Math.imul(al1, bh7)) | 0;
6251 mid = (mid + Math.imul(ah1, bl7)) | 0;
6252 hi = (hi + Math.imul(ah1, bh7)) | 0;
6253 lo = (lo + Math.imul(al0, bl8)) | 0;
6254 mid = (mid + Math.imul(al0, bh8)) | 0;
6255 mid = (mid + Math.imul(ah0, bl8)) | 0;
6256 hi = (hi + Math.imul(ah0, bh8)) | 0;
6257 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6258 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
6259 w8 &= 0x3ffffff;
6260 /* k = 9 */
6261 lo = Math.imul(al9, bl0);
6262 mid = Math.imul(al9, bh0);
6263 mid = (mid + Math.imul(ah9, bl0)) | 0;
6264 hi = Math.imul(ah9, bh0);
6265 lo = (lo + Math.imul(al8, bl1)) | 0;
6266 mid = (mid + Math.imul(al8, bh1)) | 0;
6267 mid = (mid + Math.imul(ah8, bl1)) | 0;
6268 hi = (hi + Math.imul(ah8, bh1)) | 0;
6269 lo = (lo + Math.imul(al7, bl2)) | 0;
6270 mid = (mid + Math.imul(al7, bh2)) | 0;
6271 mid = (mid + Math.imul(ah7, bl2)) | 0;
6272 hi = (hi + Math.imul(ah7, bh2)) | 0;
6273 lo = (lo + Math.imul(al6, bl3)) | 0;
6274 mid = (mid + Math.imul(al6, bh3)) | 0;
6275 mid = (mid + Math.imul(ah6, bl3)) | 0;
6276 hi = (hi + Math.imul(ah6, bh3)) | 0;
6277 lo = (lo + Math.imul(al5, bl4)) | 0;
6278 mid = (mid + Math.imul(al5, bh4)) | 0;
6279 mid = (mid + Math.imul(ah5, bl4)) | 0;
6280 hi = (hi + Math.imul(ah5, bh4)) | 0;
6281 lo = (lo + Math.imul(al4, bl5)) | 0;
6282 mid = (mid + Math.imul(al4, bh5)) | 0;
6283 mid = (mid + Math.imul(ah4, bl5)) | 0;
6284 hi = (hi + Math.imul(ah4, bh5)) | 0;
6285 lo = (lo + Math.imul(al3, bl6)) | 0;
6286 mid = (mid + Math.imul(al3, bh6)) | 0;
6287 mid = (mid + Math.imul(ah3, bl6)) | 0;
6288 hi = (hi + Math.imul(ah3, bh6)) | 0;
6289 lo = (lo + Math.imul(al2, bl7)) | 0;
6290 mid = (mid + Math.imul(al2, bh7)) | 0;
6291 mid = (mid + Math.imul(ah2, bl7)) | 0;
6292 hi = (hi + Math.imul(ah2, bh7)) | 0;
6293 lo = (lo + Math.imul(al1, bl8)) | 0;
6294 mid = (mid + Math.imul(al1, bh8)) | 0;
6295 mid = (mid + Math.imul(ah1, bl8)) | 0;
6296 hi = (hi + Math.imul(ah1, bh8)) | 0;
6297 lo = (lo + Math.imul(al0, bl9)) | 0;
6298 mid = (mid + Math.imul(al0, bh9)) | 0;
6299 mid = (mid + Math.imul(ah0, bl9)) | 0;
6300 hi = (hi + Math.imul(ah0, bh9)) | 0;
6301 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6302 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
6303 w9 &= 0x3ffffff;
6304 /* k = 10 */
6305 lo = Math.imul(al9, bl1);
6306 mid = Math.imul(al9, bh1);
6307 mid = (mid + Math.imul(ah9, bl1)) | 0;
6308 hi = Math.imul(ah9, bh1);
6309 lo = (lo + Math.imul(al8, bl2)) | 0;
6310 mid = (mid + Math.imul(al8, bh2)) | 0;
6311 mid = (mid + Math.imul(ah8, bl2)) | 0;
6312 hi = (hi + Math.imul(ah8, bh2)) | 0;
6313 lo = (lo + Math.imul(al7, bl3)) | 0;
6314 mid = (mid + Math.imul(al7, bh3)) | 0;
6315 mid = (mid + Math.imul(ah7, bl3)) | 0;
6316 hi = (hi + Math.imul(ah7, bh3)) | 0;
6317 lo = (lo + Math.imul(al6, bl4)) | 0;
6318 mid = (mid + Math.imul(al6, bh4)) | 0;
6319 mid = (mid + Math.imul(ah6, bl4)) | 0;
6320 hi = (hi + Math.imul(ah6, bh4)) | 0;
6321 lo = (lo + Math.imul(al5, bl5)) | 0;
6322 mid = (mid + Math.imul(al5, bh5)) | 0;
6323 mid = (mid + Math.imul(ah5, bl5)) | 0;
6324 hi = (hi + Math.imul(ah5, bh5)) | 0;
6325 lo = (lo + Math.imul(al4, bl6)) | 0;
6326 mid = (mid + Math.imul(al4, bh6)) | 0;
6327 mid = (mid + Math.imul(ah4, bl6)) | 0;
6328 hi = (hi + Math.imul(ah4, bh6)) | 0;
6329 lo = (lo + Math.imul(al3, bl7)) | 0;
6330 mid = (mid + Math.imul(al3, bh7)) | 0;
6331 mid = (mid + Math.imul(ah3, bl7)) | 0;
6332 hi = (hi + Math.imul(ah3, bh7)) | 0;
6333 lo = (lo + Math.imul(al2, bl8)) | 0;
6334 mid = (mid + Math.imul(al2, bh8)) | 0;
6335 mid = (mid + Math.imul(ah2, bl8)) | 0;
6336 hi = (hi + Math.imul(ah2, bh8)) | 0;
6337 lo = (lo + Math.imul(al1, bl9)) | 0;
6338 mid = (mid + Math.imul(al1, bh9)) | 0;
6339 mid = (mid + Math.imul(ah1, bl9)) | 0;
6340 hi = (hi + Math.imul(ah1, bh9)) | 0;
6341 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6342 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
6343 w10 &= 0x3ffffff;
6344 /* k = 11 */
6345 lo = Math.imul(al9, bl2);
6346 mid = Math.imul(al9, bh2);
6347 mid = (mid + Math.imul(ah9, bl2)) | 0;
6348 hi = Math.imul(ah9, bh2);
6349 lo = (lo + Math.imul(al8, bl3)) | 0;
6350 mid = (mid + Math.imul(al8, bh3)) | 0;
6351 mid = (mid + Math.imul(ah8, bl3)) | 0;
6352 hi = (hi + Math.imul(ah8, bh3)) | 0;
6353 lo = (lo + Math.imul(al7, bl4)) | 0;
6354 mid = (mid + Math.imul(al7, bh4)) | 0;
6355 mid = (mid + Math.imul(ah7, bl4)) | 0;
6356 hi = (hi + Math.imul(ah7, bh4)) | 0;
6357 lo = (lo + Math.imul(al6, bl5)) | 0;
6358 mid = (mid + Math.imul(al6, bh5)) | 0;
6359 mid = (mid + Math.imul(ah6, bl5)) | 0;
6360 hi = (hi + Math.imul(ah6, bh5)) | 0;
6361 lo = (lo + Math.imul(al5, bl6)) | 0;
6362 mid = (mid + Math.imul(al5, bh6)) | 0;
6363 mid = (mid + Math.imul(ah5, bl6)) | 0;
6364 hi = (hi + Math.imul(ah5, bh6)) | 0;
6365 lo = (lo + Math.imul(al4, bl7)) | 0;
6366 mid = (mid + Math.imul(al4, bh7)) | 0;
6367 mid = (mid + Math.imul(ah4, bl7)) | 0;
6368 hi = (hi + Math.imul(ah4, bh7)) | 0;
6369 lo = (lo + Math.imul(al3, bl8)) | 0;
6370 mid = (mid + Math.imul(al3, bh8)) | 0;
6371 mid = (mid + Math.imul(ah3, bl8)) | 0;
6372 hi = (hi + Math.imul(ah3, bh8)) | 0;
6373 lo = (lo + Math.imul(al2, bl9)) | 0;
6374 mid = (mid + Math.imul(al2, bh9)) | 0;
6375 mid = (mid + Math.imul(ah2, bl9)) | 0;
6376 hi = (hi + Math.imul(ah2, bh9)) | 0;
6377 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6378 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
6379 w11 &= 0x3ffffff;
6380 /* k = 12 */
6381 lo = Math.imul(al9, bl3);
6382 mid = Math.imul(al9, bh3);
6383 mid = (mid + Math.imul(ah9, bl3)) | 0;
6384 hi = Math.imul(ah9, bh3);
6385 lo = (lo + Math.imul(al8, bl4)) | 0;
6386 mid = (mid + Math.imul(al8, bh4)) | 0;
6387 mid = (mid + Math.imul(ah8, bl4)) | 0;
6388 hi = (hi + Math.imul(ah8, bh4)) | 0;
6389 lo = (lo + Math.imul(al7, bl5)) | 0;
6390 mid = (mid + Math.imul(al7, bh5)) | 0;
6391 mid = (mid + Math.imul(ah7, bl5)) | 0;
6392 hi = (hi + Math.imul(ah7, bh5)) | 0;
6393 lo = (lo + Math.imul(al6, bl6)) | 0;
6394 mid = (mid + Math.imul(al6, bh6)) | 0;
6395 mid = (mid + Math.imul(ah6, bl6)) | 0;
6396 hi = (hi + Math.imul(ah6, bh6)) | 0;
6397 lo = (lo + Math.imul(al5, bl7)) | 0;
6398 mid = (mid + Math.imul(al5, bh7)) | 0;
6399 mid = (mid + Math.imul(ah5, bl7)) | 0;
6400 hi = (hi + Math.imul(ah5, bh7)) | 0;
6401 lo = (lo + Math.imul(al4, bl8)) | 0;
6402 mid = (mid + Math.imul(al4, bh8)) | 0;
6403 mid = (mid + Math.imul(ah4, bl8)) | 0;
6404 hi = (hi + Math.imul(ah4, bh8)) | 0;
6405 lo = (lo + Math.imul(al3, bl9)) | 0;
6406 mid = (mid + Math.imul(al3, bh9)) | 0;
6407 mid = (mid + Math.imul(ah3, bl9)) | 0;
6408 hi = (hi + Math.imul(ah3, bh9)) | 0;
6409 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6410 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
6411 w12 &= 0x3ffffff;
6412 /* k = 13 */
6413 lo = Math.imul(al9, bl4);
6414 mid = Math.imul(al9, bh4);
6415 mid = (mid + Math.imul(ah9, bl4)) | 0;
6416 hi = Math.imul(ah9, bh4);
6417 lo = (lo + Math.imul(al8, bl5)) | 0;
6418 mid = (mid + Math.imul(al8, bh5)) | 0;
6419 mid = (mid + Math.imul(ah8, bl5)) | 0;
6420 hi = (hi + Math.imul(ah8, bh5)) | 0;
6421 lo = (lo + Math.imul(al7, bl6)) | 0;
6422 mid = (mid + Math.imul(al7, bh6)) | 0;
6423 mid = (mid + Math.imul(ah7, bl6)) | 0;
6424 hi = (hi + Math.imul(ah7, bh6)) | 0;
6425 lo = (lo + Math.imul(al6, bl7)) | 0;
6426 mid = (mid + Math.imul(al6, bh7)) | 0;
6427 mid = (mid + Math.imul(ah6, bl7)) | 0;
6428 hi = (hi + Math.imul(ah6, bh7)) | 0;
6429 lo = (lo + Math.imul(al5, bl8)) | 0;
6430 mid = (mid + Math.imul(al5, bh8)) | 0;
6431 mid = (mid + Math.imul(ah5, bl8)) | 0;
6432 hi = (hi + Math.imul(ah5, bh8)) | 0;
6433 lo = (lo + Math.imul(al4, bl9)) | 0;
6434 mid = (mid + Math.imul(al4, bh9)) | 0;
6435 mid = (mid + Math.imul(ah4, bl9)) | 0;
6436 hi = (hi + Math.imul(ah4, bh9)) | 0;
6437 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6438 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
6439 w13 &= 0x3ffffff;
6440 /* k = 14 */
6441 lo = Math.imul(al9, bl5);
6442 mid = Math.imul(al9, bh5);
6443 mid = (mid + Math.imul(ah9, bl5)) | 0;
6444 hi = Math.imul(ah9, bh5);
6445 lo = (lo + Math.imul(al8, bl6)) | 0;
6446 mid = (mid + Math.imul(al8, bh6)) | 0;
6447 mid = (mid + Math.imul(ah8, bl6)) | 0;
6448 hi = (hi + Math.imul(ah8, bh6)) | 0;
6449 lo = (lo + Math.imul(al7, bl7)) | 0;
6450 mid = (mid + Math.imul(al7, bh7)) | 0;
6451 mid = (mid + Math.imul(ah7, bl7)) | 0;
6452 hi = (hi + Math.imul(ah7, bh7)) | 0;
6453 lo = (lo + Math.imul(al6, bl8)) | 0;
6454 mid = (mid + Math.imul(al6, bh8)) | 0;
6455 mid = (mid + Math.imul(ah6, bl8)) | 0;
6456 hi = (hi + Math.imul(ah6, bh8)) | 0;
6457 lo = (lo + Math.imul(al5, bl9)) | 0;
6458 mid = (mid + Math.imul(al5, bh9)) | 0;
6459 mid = (mid + Math.imul(ah5, bl9)) | 0;
6460 hi = (hi + Math.imul(ah5, bh9)) | 0;
6461 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6462 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
6463 w14 &= 0x3ffffff;
6464 /* k = 15 */
6465 lo = Math.imul(al9, bl6);
6466 mid = Math.imul(al9, bh6);
6467 mid = (mid + Math.imul(ah9, bl6)) | 0;
6468 hi = Math.imul(ah9, bh6);
6469 lo = (lo + Math.imul(al8, bl7)) | 0;
6470 mid = (mid + Math.imul(al8, bh7)) | 0;
6471 mid = (mid + Math.imul(ah8, bl7)) | 0;
6472 hi = (hi + Math.imul(ah8, bh7)) | 0;
6473 lo = (lo + Math.imul(al7, bl8)) | 0;
6474 mid = (mid + Math.imul(al7, bh8)) | 0;
6475 mid = (mid + Math.imul(ah7, bl8)) | 0;
6476 hi = (hi + Math.imul(ah7, bh8)) | 0;
6477 lo = (lo + Math.imul(al6, bl9)) | 0;
6478 mid = (mid + Math.imul(al6, bh9)) | 0;
6479 mid = (mid + Math.imul(ah6, bl9)) | 0;
6480 hi = (hi + Math.imul(ah6, bh9)) | 0;
6481 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6482 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
6483 w15 &= 0x3ffffff;
6484 /* k = 16 */
6485 lo = Math.imul(al9, bl7);
6486 mid = Math.imul(al9, bh7);
6487 mid = (mid + Math.imul(ah9, bl7)) | 0;
6488 hi = Math.imul(ah9, bh7);
6489 lo = (lo + Math.imul(al8, bl8)) | 0;
6490 mid = (mid + Math.imul(al8, bh8)) | 0;
6491 mid = (mid + Math.imul(ah8, bl8)) | 0;
6492 hi = (hi + Math.imul(ah8, bh8)) | 0;
6493 lo = (lo + Math.imul(al7, bl9)) | 0;
6494 mid = (mid + Math.imul(al7, bh9)) | 0;
6495 mid = (mid + Math.imul(ah7, bl9)) | 0;
6496 hi = (hi + Math.imul(ah7, bh9)) | 0;
6497 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6498 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
6499 w16 &= 0x3ffffff;
6500 /* k = 17 */
6501 lo = Math.imul(al9, bl8);
6502 mid = Math.imul(al9, bh8);
6503 mid = (mid + Math.imul(ah9, bl8)) | 0;
6504 hi = Math.imul(ah9, bh8);
6505 lo = (lo + Math.imul(al8, bl9)) | 0;
6506 mid = (mid + Math.imul(al8, bh9)) | 0;
6507 mid = (mid + Math.imul(ah8, bl9)) | 0;
6508 hi = (hi + Math.imul(ah8, bh9)) | 0;
6509 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6510 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
6511 w17 &= 0x3ffffff;
6512 /* k = 18 */
6513 lo = Math.imul(al9, bl9);
6514 mid = Math.imul(al9, bh9);
6515 mid = (mid + Math.imul(ah9, bl9)) | 0;
6516 hi = Math.imul(ah9, bh9);
6517 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
6518 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
6519 w18 &= 0x3ffffff;
6520 o[0] = w0;
6521 o[1] = w1;
6522 o[2] = w2;
6523 o[3] = w3;
6524 o[4] = w4;
6525 o[5] = w5;
6526 o[6] = w6;
6527 o[7] = w7;
6528 o[8] = w8;
6529 o[9] = w9;
6530 o[10] = w10;
6531 o[11] = w11;
6532 o[12] = w12;
6533 o[13] = w13;
6534 o[14] = w14;
6535 o[15] = w15;
6536 o[16] = w16;
6537 o[17] = w17;
6538 o[18] = w18;
6539 if (c !== 0) {
6540 o[19] = c;
6541 out.length++;
6542 }
6543 return out;
6544 };
6545
6546 // Polyfill comb
6547 if (!Math.imul) {
6548 comb10MulTo = smallMulTo;
6549 }
6550
6551 function bigMulTo (self, num, out) {
6552 out.negative = num.negative ^ self.negative;
6553 out.length = self.length + num.length;
6554
6555 var carry = 0;
6556 var hncarry = 0;
6557 for (var k = 0; k < out.length - 1; k++) {
6558 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
6559 // note that ncarry could be >= 0x3ffffff
6560 var ncarry = hncarry;
6561 hncarry = 0;
6562 var rword = carry & 0x3ffffff;
6563 var maxJ = Math.min(k, num.length - 1);
6564 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
6565 var i = k - j;
6566 var a = self.words[i] | 0;
6567 var b = num.words[j] | 0;
6568 var r = a * b;
6569
6570 var lo = r & 0x3ffffff;
6571 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
6572 lo = (lo + rword) | 0;
6573 rword = lo & 0x3ffffff;
6574 ncarry = (ncarry + (lo >>> 26)) | 0;
6575
6576 hncarry += ncarry >>> 26;
6577 ncarry &= 0x3ffffff;
6578 }
6579 out.words[k] = rword;
6580 carry = ncarry;
6581 ncarry = hncarry;
6582 }
6583 if (carry !== 0) {
6584 out.words[k] = carry;
6585 } else {
6586 out.length--;
6587 }
6588
6589 return out.strip();
6590 }
6591
6592 function jumboMulTo (self, num, out) {
6593 var fftm = new FFTM();
6594 return fftm.mulp(self, num, out);
6595 }
6596
6597 BN.prototype.mulTo = function mulTo (num, out) {
6598 var res;
6599 var len = this.length + num.length;
6600 if (this.length === 10 && num.length === 10) {
6601 res = comb10MulTo(this, num, out);
6602 } else if (len < 63) {
6603 res = smallMulTo(this, num, out);
6604 } else if (len < 1024) {
6605 res = bigMulTo(this, num, out);
6606 } else {
6607 res = jumboMulTo(this, num, out);
6608 }
6609
6610 return res;
6611 };
6612
6613 // Cooley-Tukey algorithm for FFT
6614 // slightly revisited to rely on looping instead of recursion
6615
6616 function FFTM (x, y) {
6617 this.x = x;
6618 this.y = y;
6619 }
6620
6621 FFTM.prototype.makeRBT = function makeRBT (N) {
6622 var t = new Array(N);
6623 var l = BN.prototype._countBits(N) - 1;
6624 for (var i = 0; i < N; i++) {
6625 t[i] = this.revBin(i, l, N);
6626 }
6627
6628 return t;
6629 };
6630
6631 // Returns binary-reversed representation of `x`
6632 FFTM.prototype.revBin = function revBin (x, l, N) {
6633 if (x === 0 || x === N - 1) return x;
6634
6635 var rb = 0;
6636 for (var i = 0; i < l; i++) {
6637 rb |= (x & 1) << (l - i - 1);
6638 x >>= 1;
6639 }
6640
6641 return rb;
6642 };
6643
6644 // Performs "tweedling" phase, therefore 'emulating'
6645 // behaviour of the recursive algorithm
6646 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
6647 for (var i = 0; i < N; i++) {
6648 rtws[i] = rws[rbt[i]];
6649 itws[i] = iws[rbt[i]];
6650 }
6651 };
6652
6653 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
6654 this.permute(rbt, rws, iws, rtws, itws, N);
6655
6656 for (var s = 1; s < N; s <<= 1) {
6657 var l = s << 1;
6658
6659 var rtwdf = Math.cos(2 * Math.PI / l);
6660 var itwdf = Math.sin(2 * Math.PI / l);
6661
6662 for (var p = 0; p < N; p += l) {
6663 var rtwdf_ = rtwdf;
6664 var itwdf_ = itwdf;
6665
6666 for (var j = 0; j < s; j++) {
6667 var re = rtws[p + j];
6668 var ie = itws[p + j];
6669
6670 var ro = rtws[p + j + s];
6671 var io = itws[p + j + s];
6672
6673 var rx = rtwdf_ * ro - itwdf_ * io;
6674
6675 io = rtwdf_ * io + itwdf_ * ro;
6676 ro = rx;
6677
6678 rtws[p + j] = re + ro;
6679 itws[p + j] = ie + io;
6680
6681 rtws[p + j + s] = re - ro;
6682 itws[p + j + s] = ie - io;
6683
6684 /* jshint maxdepth : false */
6685 if (j !== l) {
6686 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
6687
6688 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
6689 rtwdf_ = rx;
6690 }
6691 }
6692 }
6693 }
6694 };
6695
6696 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
6697 var N = Math.max(m, n) | 1;
6698 var odd = N & 1;
6699 var i = 0;
6700 for (N = N / 2 | 0; N; N = N >>> 1) {
6701 i++;
6702 }
6703
6704 return 1 << i + 1 + odd;
6705 };
6706
6707 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
6708 if (N <= 1) return;
6709
6710 for (var i = 0; i < N / 2; i++) {
6711 var t = rws[i];
6712
6713 rws[i] = rws[N - i - 1];
6714 rws[N - i - 1] = t;
6715
6716 t = iws[i];
6717
6718 iws[i] = -iws[N - i - 1];
6719 iws[N - i - 1] = -t;
6720 }
6721 };
6722
6723 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
6724 var carry = 0;
6725 for (var i = 0; i < N / 2; i++) {
6726 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
6727 Math.round(ws[2 * i] / N) +
6728 carry;
6729
6730 ws[i] = w & 0x3ffffff;
6731
6732 if (w < 0x4000000) {
6733 carry = 0;
6734 } else {
6735 carry = w / 0x4000000 | 0;
6736 }
6737 }
6738
6739 return ws;
6740 };
6741
6742 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
6743 var carry = 0;
6744 for (var i = 0; i < len; i++) {
6745 carry = carry + (ws[i] | 0);
6746
6747 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
6748 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
6749 }
6750
6751 // Pad with zeroes
6752 for (i = 2 * len; i < N; ++i) {
6753 rws[i] = 0;
6754 }
6755
6756 assert(carry === 0);
6757 assert((carry & ~0x1fff) === 0);
6758 };
6759
6760 FFTM.prototype.stub = function stub (N) {
6761 var ph = new Array(N);
6762 for (var i = 0; i < N; i++) {
6763 ph[i] = 0;
6764 }
6765
6766 return ph;
6767 };
6768
6769 FFTM.prototype.mulp = function mulp (x, y, out) {
6770 var N = 2 * this.guessLen13b(x.length, y.length);
6771
6772 var rbt = this.makeRBT(N);
6773
6774 var _ = this.stub(N);
6775
6776 var rws = new Array(N);
6777 var rwst = new Array(N);
6778 var iwst = new Array(N);
6779
6780 var nrws = new Array(N);
6781 var nrwst = new Array(N);
6782 var niwst = new Array(N);
6783
6784 var rmws = out.words;
6785 rmws.length = N;
6786
6787 this.convert13b(x.words, x.length, rws, N);
6788 this.convert13b(y.words, y.length, nrws, N);
6789
6790 this.transform(rws, _, rwst, iwst, N, rbt);
6791 this.transform(nrws, _, nrwst, niwst, N, rbt);
6792
6793 for (var i = 0; i < N; i++) {
6794 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
6795 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
6796 rwst[i] = rx;
6797 }
6798
6799 this.conjugate(rwst, iwst, N);
6800 this.transform(rwst, iwst, rmws, _, N, rbt);
6801 this.conjugate(rmws, _, N);
6802 this.normalize13b(rmws, N);
6803
6804 out.negative = x.negative ^ y.negative;
6805 out.length = x.length + y.length;
6806 return out.strip();
6807 };
6808
6809 // Multiply `this` by `num`
6810 BN.prototype.mul = function mul (num) {
6811 var out = new BN(null);
6812 out.words = new Array(this.length + num.length);
6813 return this.mulTo(num, out);
6814 };
6815
6816 // Multiply employing FFT
6817 BN.prototype.mulf = function mulf (num) {
6818 var out = new BN(null);
6819 out.words = new Array(this.length + num.length);
6820 return jumboMulTo(this, num, out);
6821 };
6822
6823 // In-place Multiplication
6824 BN.prototype.imul = function imul (num) {
6825 return this.clone().mulTo(num, this);
6826 };
6827
6828 BN.prototype.imuln = function imuln (num) {
6829 assert(typeof num === 'number');
6830 assert(num < 0x4000000);
6831
6832 // Carry
6833 var carry = 0;
6834 for (var i = 0; i < this.length; i++) {
6835 var w = (this.words[i] | 0) * num;
6836 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
6837 carry >>= 26;
6838 carry += (w / 0x4000000) | 0;
6839 // NOTE: lo is 27bit maximum
6840 carry += lo >>> 26;
6841 this.words[i] = lo & 0x3ffffff;
6842 }
6843
6844 if (carry !== 0) {
6845 this.words[i] = carry;
6846 this.length++;
6847 }
6848
6849 return this;
6850 };
6851
6852 BN.prototype.muln = function muln (num) {
6853 return this.clone().imuln(num);
6854 };
6855
6856 // `this` * `this`
6857 BN.prototype.sqr = function sqr () {
6858 return this.mul(this);
6859 };
6860
6861 // `this` * `this` in-place
6862 BN.prototype.isqr = function isqr () {
6863 return this.imul(this.clone());
6864 };
6865
6866 // Math.pow(`this`, `num`)
6867 BN.prototype.pow = function pow (num) {
6868 var w = toBitArray(num);
6869 if (w.length === 0) return new BN(1);
6870
6871 // Skip leading zeroes
6872 var res = this;
6873 for (var i = 0; i < w.length; i++, res = res.sqr()) {
6874 if (w[i] !== 0) break;
6875 }
6876
6877 if (++i < w.length) {
6878 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
6879 if (w[i] === 0) continue;
6880
6881 res = res.mul(q);
6882 }
6883 }
6884
6885 return res;
6886 };
6887
6888 // Shift-left in-place
6889 BN.prototype.iushln = function iushln (bits) {
6890 assert(typeof bits === 'number' && bits >= 0);
6891 var r = bits % 26;
6892 var s = (bits - r) / 26;
6893 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
6894 var i;
6895
6896 if (r !== 0) {
6897 var carry = 0;
6898
6899 for (i = 0; i < this.length; i++) {
6900 var newCarry = this.words[i] & carryMask;
6901 var c = ((this.words[i] | 0) - newCarry) << r;
6902 this.words[i] = c | carry;
6903 carry = newCarry >>> (26 - r);
6904 }
6905
6906 if (carry) {
6907 this.words[i] = carry;
6908 this.length++;
6909 }
6910 }
6911
6912 if (s !== 0) {
6913 for (i = this.length - 1; i >= 0; i--) {
6914 this.words[i + s] = this.words[i];
6915 }
6916
6917 for (i = 0; i < s; i++) {
6918 this.words[i] = 0;
6919 }
6920
6921 this.length += s;
6922 }
6923
6924 return this.strip();
6925 };
6926
6927 BN.prototype.ishln = function ishln (bits) {
6928 // TODO(indutny): implement me
6929 assert(this.negative === 0);
6930 return this.iushln(bits);
6931 };
6932
6933 // Shift-right in-place
6934 // NOTE: `hint` is a lowest bit before trailing zeroes
6935 // NOTE: if `extended` is present - it will be filled with destroyed bits
6936 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
6937 assert(typeof bits === 'number' && bits >= 0);
6938 var h;
6939 if (hint) {
6940 h = (hint - (hint % 26)) / 26;
6941 } else {
6942 h = 0;
6943 }
6944
6945 var r = bits % 26;
6946 var s = Math.min((bits - r) / 26, this.length);
6947 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
6948 var maskedWords = extended;
6949
6950 h -= s;
6951 h = Math.max(0, h);
6952
6953 // Extended mode, copy masked part
6954 if (maskedWords) {
6955 for (var i = 0; i < s; i++) {
6956 maskedWords.words[i] = this.words[i];
6957 }
6958 maskedWords.length = s;
6959 }
6960
6961 if (s === 0) {
6962 // No-op, we should not move anything at all
6963 } else if (this.length > s) {
6964 this.length -= s;
6965 for (i = 0; i < this.length; i++) {
6966 this.words[i] = this.words[i + s];
6967 }
6968 } else {
6969 this.words[0] = 0;
6970 this.length = 1;
6971 }
6972
6973 var carry = 0;
6974 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
6975 var word = this.words[i] | 0;
6976 this.words[i] = (carry << (26 - r)) | (word >>> r);
6977 carry = word & mask;
6978 }
6979
6980 // Push carried bits as a mask
6981 if (maskedWords && carry !== 0) {
6982 maskedWords.words[maskedWords.length++] = carry;
6983 }
6984
6985 if (this.length === 0) {
6986 this.words[0] = 0;
6987 this.length = 1;
6988 }
6989
6990 return this.strip();
6991 };
6992
6993 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
6994 // TODO(indutny): implement me
6995 assert(this.negative === 0);
6996 return this.iushrn(bits, hint, extended);
6997 };
6998
6999 // Shift-left
7000 BN.prototype.shln = function shln (bits) {
7001 return this.clone().ishln(bits);
7002 };
7003
7004 BN.prototype.ushln = function ushln (bits) {
7005 return this.clone().iushln(bits);
7006 };
7007
7008 // Shift-right
7009 BN.prototype.shrn = function shrn (bits) {
7010 return this.clone().ishrn(bits);
7011 };
7012
7013 BN.prototype.ushrn = function ushrn (bits) {
7014 return this.clone().iushrn(bits);
7015 };
7016
7017 // Test if n bit is set
7018 BN.prototype.testn = function testn (bit) {
7019 assert(typeof bit === 'number' && bit >= 0);
7020 var r = bit % 26;
7021 var s = (bit - r) / 26;
7022 var q = 1 << r;
7023
7024 // Fast case: bit is much higher than all existing words
7025 if (this.length <= s) return false;
7026
7027 // Check bit and return
7028 var w = this.words[s];
7029
7030 return !!(w & q);
7031 };
7032
7033 // Return only lowers bits of number (in-place)
7034 BN.prototype.imaskn = function imaskn (bits) {
7035 assert(typeof bits === 'number' && bits >= 0);
7036 var r = bits % 26;
7037 var s = (bits - r) / 26;
7038
7039 assert(this.negative === 0, 'imaskn works only with positive numbers');
7040
7041 if (this.length <= s) {
7042 return this;
7043 }
7044
7045 if (r !== 0) {
7046 s++;
7047 }
7048 this.length = Math.min(s, this.length);
7049
7050 if (r !== 0) {
7051 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
7052 this.words[this.length - 1] &= mask;
7053 }
7054
7055 return this.strip();
7056 };
7057
7058 // Return only lowers bits of number
7059 BN.prototype.maskn = function maskn (bits) {
7060 return this.clone().imaskn(bits);
7061 };
7062
7063 // Add plain number `num` to `this`
7064 BN.prototype.iaddn = function iaddn (num) {
7065 assert(typeof num === 'number');
7066 assert(num < 0x4000000);
7067 if (num < 0) return this.isubn(-num);
7068
7069 // Possible sign change
7070 if (this.negative !== 0) {
7071 if (this.length === 1 && (this.words[0] | 0) < num) {
7072 this.words[0] = num - (this.words[0] | 0);
7073 this.negative = 0;
7074 return this;
7075 }
7076
7077 this.negative = 0;
7078 this.isubn(num);
7079 this.negative = 1;
7080 return this;
7081 }
7082
7083 // Add without checks
7084 return this._iaddn(num);
7085 };
7086
7087 BN.prototype._iaddn = function _iaddn (num) {
7088 this.words[0] += num;
7089
7090 // Carry
7091 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
7092 this.words[i] -= 0x4000000;
7093 if (i === this.length - 1) {
7094 this.words[i + 1] = 1;
7095 } else {
7096 this.words[i + 1]++;
7097 }
7098 }
7099 this.length = Math.max(this.length, i + 1);
7100
7101 return this;
7102 };
7103
7104 // Subtract plain number `num` from `this`
7105 BN.prototype.isubn = function isubn (num) {
7106 assert(typeof num === 'number');
7107 assert(num < 0x4000000);
7108 if (num < 0) return this.iaddn(-num);
7109
7110 if (this.negative !== 0) {
7111 this.negative = 0;
7112 this.iaddn(num);
7113 this.negative = 1;
7114 return this;
7115 }
7116
7117 this.words[0] -= num;
7118
7119 if (this.length === 1 && this.words[0] < 0) {
7120 this.words[0] = -this.words[0];
7121 this.negative = 1;
7122 } else {
7123 // Carry
7124 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
7125 this.words[i] += 0x4000000;
7126 this.words[i + 1] -= 1;
7127 }
7128 }
7129
7130 return this.strip();
7131 };
7132
7133 BN.prototype.addn = function addn (num) {
7134 return this.clone().iaddn(num);
7135 };
7136
7137 BN.prototype.subn = function subn (num) {
7138 return this.clone().isubn(num);
7139 };
7140
7141 BN.prototype.iabs = function iabs () {
7142 this.negative = 0;
7143
7144 return this;
7145 };
7146
7147 BN.prototype.abs = function abs () {
7148 return this.clone().iabs();
7149 };
7150
7151 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
7152 var len = num.length + shift;
7153 var i;
7154
7155 this._expand(len);
7156
7157 var w;
7158 var carry = 0;
7159 for (i = 0; i < num.length; i++) {
7160 w = (this.words[i + shift] | 0) + carry;
7161 var right = (num.words[i] | 0) * mul;
7162 w -= right & 0x3ffffff;
7163 carry = (w >> 26) - ((right / 0x4000000) | 0);
7164 this.words[i + shift] = w & 0x3ffffff;
7165 }
7166 for (; i < this.length - shift; i++) {
7167 w = (this.words[i + shift] | 0) + carry;
7168 carry = w >> 26;
7169 this.words[i + shift] = w & 0x3ffffff;
7170 }
7171
7172 if (carry === 0) return this.strip();
7173
7174 // Subtraction overflow
7175 assert(carry === -1);
7176 carry = 0;
7177 for (i = 0; i < this.length; i++) {
7178 w = -(this.words[i] | 0) + carry;
7179 carry = w >> 26;
7180 this.words[i] = w & 0x3ffffff;
7181 }
7182 this.negative = 1;
7183
7184 return this.strip();
7185 };
7186
7187 BN.prototype._wordDiv = function _wordDiv (num, mode) {
7188 var shift = this.length - num.length;
7189
7190 var a = this.clone();
7191 var b = num;
7192
7193 // Normalize
7194 var bhi = b.words[b.length - 1] | 0;
7195 var bhiBits = this._countBits(bhi);
7196 shift = 26 - bhiBits;
7197 if (shift !== 0) {
7198 b = b.ushln(shift);
7199 a.iushln(shift);
7200 bhi = b.words[b.length - 1] | 0;
7201 }
7202
7203 // Initialize quotient
7204 var m = a.length - b.length;
7205 var q;
7206
7207 if (mode !== 'mod') {
7208 q = new BN(null);
7209 q.length = m + 1;
7210 q.words = new Array(q.length);
7211 for (var i = 0; i < q.length; i++) {
7212 q.words[i] = 0;
7213 }
7214 }
7215
7216 var diff = a.clone()._ishlnsubmul(b, 1, m);
7217 if (diff.negative === 0) {
7218 a = diff;
7219 if (q) {
7220 q.words[m] = 1;
7221 }
7222 }
7223
7224 for (var j = m - 1; j >= 0; j--) {
7225 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
7226 (a.words[b.length + j - 1] | 0);
7227
7228 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
7229 // (0x7ffffff)
7230 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
7231
7232 a._ishlnsubmul(b, qj, j);
7233 while (a.negative !== 0) {
7234 qj--;
7235 a.negative = 0;
7236 a._ishlnsubmul(b, 1, j);
7237 if (!a.isZero()) {
7238 a.negative ^= 1;
7239 }
7240 }
7241 if (q) {
7242 q.words[j] = qj;
7243 }
7244 }
7245 if (q) {
7246 q.strip();
7247 }
7248 a.strip();
7249
7250 // Denormalize
7251 if (mode !== 'div' && shift !== 0) {
7252 a.iushrn(shift);
7253 }
7254
7255 return {
7256 div: q || null,
7257 mod: a
7258 };
7259 };
7260
7261 // NOTE: 1) `mode` can be set to `mod` to request mod only,
7262 // to `div` to request div only, or be absent to
7263 // request both div & mod
7264 // 2) `positive` is true if unsigned mod is requested
7265 BN.prototype.divmod = function divmod (num, mode, positive) {
7266 assert(!num.isZero());
7267
7268 if (this.isZero()) {
7269 return {
7270 div: new BN(0),
7271 mod: new BN(0)
7272 };
7273 }
7274
7275 var div, mod, res;
7276 if (this.negative !== 0 && num.negative === 0) {
7277 res = this.neg().divmod(num, mode);
7278
7279 if (mode !== 'mod') {
7280 div = res.div.neg();
7281 }
7282
7283 if (mode !== 'div') {
7284 mod = res.mod.neg();
7285 if (positive && mod.negative !== 0) {
7286 mod.iadd(num);
7287 }
7288 }
7289
7290 return {
7291 div: div,
7292 mod: mod
7293 };
7294 }
7295
7296 if (this.negative === 0 && num.negative !== 0) {
7297 res = this.divmod(num.neg(), mode);
7298
7299 if (mode !== 'mod') {
7300 div = res.div.neg();
7301 }
7302
7303 return {
7304 div: div,
7305 mod: res.mod
7306 };
7307 }
7308
7309 if ((this.negative & num.negative) !== 0) {
7310 res = this.neg().divmod(num.neg(), mode);
7311
7312 if (mode !== 'div') {
7313 mod = res.mod.neg();
7314 if (positive && mod.negative !== 0) {
7315 mod.isub(num);
7316 }
7317 }
7318
7319 return {
7320 div: res.div,
7321 mod: mod
7322 };
7323 }
7324
7325 // Both numbers are positive at this point
7326
7327 // Strip both numbers to approximate shift value
7328 if (num.length > this.length || this.cmp(num) < 0) {
7329 return {
7330 div: new BN(0),
7331 mod: this
7332 };
7333 }
7334
7335 // Very short reduction
7336 if (num.length === 1) {
7337 if (mode === 'div') {
7338 return {
7339 div: this.divn(num.words[0]),
7340 mod: null
7341 };
7342 }
7343
7344 if (mode === 'mod') {
7345 return {
7346 div: null,
7347 mod: new BN(this.modn(num.words[0]))
7348 };
7349 }
7350
7351 return {
7352 div: this.divn(num.words[0]),
7353 mod: new BN(this.modn(num.words[0]))
7354 };
7355 }
7356
7357 return this._wordDiv(num, mode);
7358 };
7359
7360 // Find `this` / `num`
7361 BN.prototype.div = function div (num) {
7362 return this.divmod(num, 'div', false).div;
7363 };
7364
7365 // Find `this` % `num`
7366 BN.prototype.mod = function mod (num) {
7367 return this.divmod(num, 'mod', false).mod;
7368 };
7369
7370 BN.prototype.umod = function umod (num) {
7371 return this.divmod(num, 'mod', true).mod;
7372 };
7373
7374 // Find Round(`this` / `num`)
7375 BN.prototype.divRound = function divRound (num) {
7376 var dm = this.divmod(num);
7377
7378 // Fast case - exact division
7379 if (dm.mod.isZero()) return dm.div;
7380
7381 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
7382
7383 var half = num.ushrn(1);
7384 var r2 = num.andln(1);
7385 var cmp = mod.cmp(half);
7386
7387 // Round down
7388 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
7389
7390 // Round up
7391 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
7392 };
7393
7394 BN.prototype.modn = function modn (num) {
7395 assert(num <= 0x3ffffff);
7396 var p = (1 << 26) % num;
7397
7398 var acc = 0;
7399 for (var i = this.length - 1; i >= 0; i--) {
7400 acc = (p * acc + (this.words[i] | 0)) % num;
7401 }
7402
7403 return acc;
7404 };
7405
7406 // In-place division by number
7407 BN.prototype.idivn = function idivn (num) {
7408 assert(num <= 0x3ffffff);
7409
7410 var carry = 0;
7411 for (var i = this.length - 1; i >= 0; i--) {
7412 var w = (this.words[i] | 0) + carry * 0x4000000;
7413 this.words[i] = (w / num) | 0;
7414 carry = w % num;
7415 }
7416
7417 return this.strip();
7418 };
7419
7420 BN.prototype.divn = function divn (num) {
7421 return this.clone().idivn(num);
7422 };
7423
7424 BN.prototype.egcd = function egcd (p) {
7425 assert(p.negative === 0);
7426 assert(!p.isZero());
7427
7428 var x = this;
7429 var y = p.clone();
7430
7431 if (x.negative !== 0) {
7432 x = x.umod(p);
7433 } else {
7434 x = x.clone();
7435 }
7436
7437 // A * x + B * y = x
7438 var A = new BN(1);
7439 var B = new BN(0);
7440
7441 // C * x + D * y = y
7442 var C = new BN(0);
7443 var D = new BN(1);
7444
7445 var g = 0;
7446
7447 while (x.isEven() && y.isEven()) {
7448 x.iushrn(1);
7449 y.iushrn(1);
7450 ++g;
7451 }
7452
7453 var yp = y.clone();
7454 var xp = x.clone();
7455
7456 while (!x.isZero()) {
7457 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
7458 if (i > 0) {
7459 x.iushrn(i);
7460 while (i-- > 0) {
7461 if (A.isOdd() || B.isOdd()) {
7462 A.iadd(yp);
7463 B.isub(xp);
7464 }
7465
7466 A.iushrn(1);
7467 B.iushrn(1);
7468 }
7469 }
7470
7471 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
7472 if (j > 0) {
7473 y.iushrn(j);
7474 while (j-- > 0) {
7475 if (C.isOdd() || D.isOdd()) {
7476 C.iadd(yp);
7477 D.isub(xp);
7478 }
7479
7480 C.iushrn(1);
7481 D.iushrn(1);
7482 }
7483 }
7484
7485 if (x.cmp(y) >= 0) {
7486 x.isub(y);
7487 A.isub(C);
7488 B.isub(D);
7489 } else {
7490 y.isub(x);
7491 C.isub(A);
7492 D.isub(B);
7493 }
7494 }
7495
7496 return {
7497 a: C,
7498 b: D,
7499 gcd: y.iushln(g)
7500 };
7501 };
7502
7503 // This is reduced incarnation of the binary EEA
7504 // above, designated to invert members of the
7505 // _prime_ fields F(p) at a maximal speed
7506 BN.prototype._invmp = function _invmp (p) {
7507 assert(p.negative === 0);
7508 assert(!p.isZero());
7509
7510 var a = this;
7511 var b = p.clone();
7512
7513 if (a.negative !== 0) {
7514 a = a.umod(p);
7515 } else {
7516 a = a.clone();
7517 }
7518
7519 var x1 = new BN(1);
7520 var x2 = new BN(0);
7521
7522 var delta = b.clone();
7523
7524 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
7525 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
7526 if (i > 0) {
7527 a.iushrn(i);
7528 while (i-- > 0) {
7529 if (x1.isOdd()) {
7530 x1.iadd(delta);
7531 }
7532
7533 x1.iushrn(1);
7534 }
7535 }
7536
7537 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
7538 if (j > 0) {
7539 b.iushrn(j);
7540 while (j-- > 0) {
7541 if (x2.isOdd()) {
7542 x2.iadd(delta);
7543 }
7544
7545 x2.iushrn(1);
7546 }
7547 }
7548
7549 if (a.cmp(b) >= 0) {
7550 a.isub(b);
7551 x1.isub(x2);
7552 } else {
7553 b.isub(a);
7554 x2.isub(x1);
7555 }
7556 }
7557
7558 var res;
7559 if (a.cmpn(1) === 0) {
7560 res = x1;
7561 } else {
7562 res = x2;
7563 }
7564
7565 if (res.cmpn(0) < 0) {
7566 res.iadd(p);
7567 }
7568
7569 return res;
7570 };
7571
7572 BN.prototype.gcd = function gcd (num) {
7573 if (this.isZero()) return num.abs();
7574 if (num.isZero()) return this.abs();
7575
7576 var a = this.clone();
7577 var b = num.clone();
7578 a.negative = 0;
7579 b.negative = 0;
7580
7581 // Remove common factor of two
7582 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
7583 a.iushrn(1);
7584 b.iushrn(1);
7585 }
7586
7587 do {
7588 while (a.isEven()) {
7589 a.iushrn(1);
7590 }
7591 while (b.isEven()) {
7592 b.iushrn(1);
7593 }
7594
7595 var r = a.cmp(b);
7596 if (r < 0) {
7597 // Swap `a` and `b` to make `a` always bigger than `b`
7598 var t = a;
7599 a = b;
7600 b = t;
7601 } else if (r === 0 || b.cmpn(1) === 0) {
7602 break;
7603 }
7604
7605 a.isub(b);
7606 } while (true);
7607
7608 return b.iushln(shift);
7609 };
7610
7611 // Invert number in the field F(num)
7612 BN.prototype.invm = function invm (num) {
7613 return this.egcd(num).a.umod(num);
7614 };
7615
7616 BN.prototype.isEven = function isEven () {
7617 return (this.words[0] & 1) === 0;
7618 };
7619
7620 BN.prototype.isOdd = function isOdd () {
7621 return (this.words[0] & 1) === 1;
7622 };
7623
7624 // And first word and num
7625 BN.prototype.andln = function andln (num) {
7626 return this.words[0] & num;
7627 };
7628
7629 // Increment at the bit position in-line
7630 BN.prototype.bincn = function bincn (bit) {
7631 assert(typeof bit === 'number');
7632 var r = bit % 26;
7633 var s = (bit - r) / 26;
7634 var q = 1 << r;
7635
7636 // Fast case: bit is much higher than all existing words
7637 if (this.length <= s) {
7638 this._expand(s + 1);
7639 this.words[s] |= q;
7640 return this;
7641 }
7642
7643 // Add bit and propagate, if needed
7644 var carry = q;
7645 for (var i = s; carry !== 0 && i < this.length; i++) {
7646 var w = this.words[i] | 0;
7647 w += carry;
7648 carry = w >>> 26;
7649 w &= 0x3ffffff;
7650 this.words[i] = w;
7651 }
7652 if (carry !== 0) {
7653 this.words[i] = carry;
7654 this.length++;
7655 }
7656 return this;
7657 };
7658
7659 BN.prototype.isZero = function isZero () {
7660 return this.length === 1 && this.words[0] === 0;
7661 };
7662
7663 BN.prototype.cmpn = function cmpn (num) {
7664 var negative = num < 0;
7665
7666 if (this.negative !== 0 && !negative) return -1;
7667 if (this.negative === 0 && negative) return 1;
7668
7669 this.strip();
7670
7671 var res;
7672 if (this.length > 1) {
7673 res = 1;
7674 } else {
7675 if (negative) {
7676 num = -num;
7677 }
7678
7679 assert(num <= 0x3ffffff, 'Number is too big');
7680
7681 var w = this.words[0] | 0;
7682 res = w === num ? 0 : w < num ? -1 : 1;
7683 }
7684 if (this.negative !== 0) return -res | 0;
7685 return res;
7686 };
7687
7688 // Compare two numbers and return:
7689 // 1 - if `this` > `num`
7690 // 0 - if `this` == `num`
7691 // -1 - if `this` < `num`
7692 BN.prototype.cmp = function cmp (num) {
7693 if (this.negative !== 0 && num.negative === 0) return -1;
7694 if (this.negative === 0 && num.negative !== 0) return 1;
7695
7696 var res = this.ucmp(num);
7697 if (this.negative !== 0) return -res | 0;
7698 return res;
7699 };
7700
7701 // Unsigned comparison
7702 BN.prototype.ucmp = function ucmp (num) {
7703 // At this point both numbers have the same sign
7704 if (this.length > num.length) return 1;
7705 if (this.length < num.length) return -1;
7706
7707 var res = 0;
7708 for (var i = this.length - 1; i >= 0; i--) {
7709 var a = this.words[i] | 0;
7710 var b = num.words[i] | 0;
7711
7712 if (a === b) continue;
7713 if (a < b) {
7714 res = -1;
7715 } else if (a > b) {
7716 res = 1;
7717 }
7718 break;
7719 }
7720 return res;
7721 };
7722
7723 BN.prototype.gtn = function gtn (num) {
7724 return this.cmpn(num) === 1;
7725 };
7726
7727 BN.prototype.gt = function gt (num) {
7728 return this.cmp(num) === 1;
7729 };
7730
7731 BN.prototype.gten = function gten (num) {
7732 return this.cmpn(num) >= 0;
7733 };
7734
7735 BN.prototype.gte = function gte (num) {
7736 return this.cmp(num) >= 0;
7737 };
7738
7739 BN.prototype.ltn = function ltn (num) {
7740 return this.cmpn(num) === -1;
7741 };
7742
7743 BN.prototype.lt = function lt (num) {
7744 return this.cmp(num) === -1;
7745 };
7746
7747 BN.prototype.lten = function lten (num) {
7748 return this.cmpn(num) <= 0;
7749 };
7750
7751 BN.prototype.lte = function lte (num) {
7752 return this.cmp(num) <= 0;
7753 };
7754
7755 BN.prototype.eqn = function eqn (num) {
7756 return this.cmpn(num) === 0;
7757 };
7758
7759 BN.prototype.eq = function eq (num) {
7760 return this.cmp(num) === 0;
7761 };
7762
7763 //
7764 // A reduce context, could be using montgomery or something better, depending
7765 // on the `m` itself.
7766 //
7767 BN.red = function red (num) {
7768 return new Red(num);
7769 };
7770
7771 BN.prototype.toRed = function toRed (ctx) {
7772 assert(!this.red, 'Already a number in reduction context');
7773 assert(this.negative === 0, 'red works only with positives');
7774 return ctx.convertTo(this)._forceRed(ctx);
7775 };
7776
7777 BN.prototype.fromRed = function fromRed () {
7778 assert(this.red, 'fromRed works only with numbers in reduction context');
7779 return this.red.convertFrom(this);
7780 };
7781
7782 BN.prototype._forceRed = function _forceRed (ctx) {
7783 this.red = ctx;
7784 return this;
7785 };
7786
7787 BN.prototype.forceRed = function forceRed (ctx) {
7788 assert(!this.red, 'Already a number in reduction context');
7789 return this._forceRed(ctx);
7790 };
7791
7792 BN.prototype.redAdd = function redAdd (num) {
7793 assert(this.red, 'redAdd works only with red numbers');
7794 return this.red.add(this, num);
7795 };
7796
7797 BN.prototype.redIAdd = function redIAdd (num) {
7798 assert(this.red, 'redIAdd works only with red numbers');
7799 return this.red.iadd(this, num);
7800 };
7801
7802 BN.prototype.redSub = function redSub (num) {
7803 assert(this.red, 'redSub works only with red numbers');
7804 return this.red.sub(this, num);
7805 };
7806
7807 BN.prototype.redISub = function redISub (num) {
7808 assert(this.red, 'redISub works only with red numbers');
7809 return this.red.isub(this, num);
7810 };
7811
7812 BN.prototype.redShl = function redShl (num) {
7813 assert(this.red, 'redShl works only with red numbers');
7814 return this.red.shl(this, num);
7815 };
7816
7817 BN.prototype.redMul = function redMul (num) {
7818 assert(this.red, 'redMul works only with red numbers');
7819 this.red._verify2(this, num);
7820 return this.red.mul(this, num);
7821 };
7822
7823 BN.prototype.redIMul = function redIMul (num) {
7824 assert(this.red, 'redMul works only with red numbers');
7825 this.red._verify2(this, num);
7826 return this.red.imul(this, num);
7827 };
7828
7829 BN.prototype.redSqr = function redSqr () {
7830 assert(this.red, 'redSqr works only with red numbers');
7831 this.red._verify1(this);
7832 return this.red.sqr(this);
7833 };
7834
7835 BN.prototype.redISqr = function redISqr () {
7836 assert(this.red, 'redISqr works only with red numbers');
7837 this.red._verify1(this);
7838 return this.red.isqr(this);
7839 };
7840
7841 // Square root over p
7842 BN.prototype.redSqrt = function redSqrt () {
7843 assert(this.red, 'redSqrt works only with red numbers');
7844 this.red._verify1(this);
7845 return this.red.sqrt(this);
7846 };
7847
7848 BN.prototype.redInvm = function redInvm () {
7849 assert(this.red, 'redInvm works only with red numbers');
7850 this.red._verify1(this);
7851 return this.red.invm(this);
7852 };
7853
7854 // Return negative clone of `this` % `red modulo`
7855 BN.prototype.redNeg = function redNeg () {
7856 assert(this.red, 'redNeg works only with red numbers');
7857 this.red._verify1(this);
7858 return this.red.neg(this);
7859 };
7860
7861 BN.prototype.redPow = function redPow (num) {
7862 assert(this.red && !num.red, 'redPow(normalNum)');
7863 this.red._verify1(this);
7864 return this.red.pow(this, num);
7865 };
7866
7867 // Prime numbers with efficient reduction
7868 var primes = {
7869 k256: null,
7870 p224: null,
7871 p192: null,
7872 p25519: null
7873 };
7874
7875 // Pseudo-Mersenne prime
7876 function MPrime (name, p) {
7877 // P = 2 ^ N - K
7878 this.name = name;
7879 this.p = new BN(p, 16);
7880 this.n = this.p.bitLength();
7881 this.k = new BN(1).iushln(this.n).isub(this.p);
7882
7883 this.tmp = this._tmp();
7884 }
7885
7886 MPrime.prototype._tmp = function _tmp () {
7887 var tmp = new BN(null);
7888 tmp.words = new Array(Math.ceil(this.n / 13));
7889 return tmp;
7890 };
7891
7892 MPrime.prototype.ireduce = function ireduce (num) {
7893 // Assumes that `num` is less than `P^2`
7894 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
7895 var r = num;
7896 var rlen;
7897
7898 do {
7899 this.split(r, this.tmp);
7900 r = this.imulK(r);
7901 r = r.iadd(this.tmp);
7902 rlen = r.bitLength();
7903 } while (rlen > this.n);
7904
7905 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
7906 if (cmp === 0) {
7907 r.words[0] = 0;
7908 r.length = 1;
7909 } else if (cmp > 0) {
7910 r.isub(this.p);
7911 } else {
7912 r.strip();
7913 }
7914
7915 return r;
7916 };
7917
7918 MPrime.prototype.split = function split (input, out) {
7919 input.iushrn(this.n, 0, out);
7920 };
7921
7922 MPrime.prototype.imulK = function imulK (num) {
7923 return num.imul(this.k);
7924 };
7925
7926 function K256 () {
7927 MPrime.call(
7928 this,
7929 'k256',
7930 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
7931 }
7932 inherits(K256, MPrime);
7933
7934 K256.prototype.split = function split (input, output) {
7935 // 256 = 9 * 26 + 22
7936 var mask = 0x3fffff;
7937
7938 var outLen = Math.min(input.length, 9);
7939 for (var i = 0; i < outLen; i++) {
7940 output.words[i] = input.words[i];
7941 }
7942 output.length = outLen;
7943
7944 if (input.length <= 9) {
7945 input.words[0] = 0;
7946 input.length = 1;
7947 return;
7948 }
7949
7950 // Shift by 9 limbs
7951 var prev = input.words[9];
7952 output.words[output.length++] = prev & mask;
7953
7954 for (i = 10; i < input.length; i++) {
7955 var next = input.words[i] | 0;
7956 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
7957 prev = next;
7958 }
7959 prev >>>= 22;
7960 input.words[i - 10] = prev;
7961 if (prev === 0 && input.length > 10) {
7962 input.length -= 10;
7963 } else {
7964 input.length -= 9;
7965 }
7966 };
7967
7968 K256.prototype.imulK = function imulK (num) {
7969 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
7970 num.words[num.length] = 0;
7971 num.words[num.length + 1] = 0;
7972 num.length += 2;
7973
7974 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
7975 var lo = 0;
7976 for (var i = 0; i < num.length; i++) {
7977 var w = num.words[i] | 0;
7978 lo += w * 0x3d1;
7979 num.words[i] = lo & 0x3ffffff;
7980 lo = w * 0x40 + ((lo / 0x4000000) | 0);
7981 }
7982
7983 // Fast length reduction
7984 if (num.words[num.length - 1] === 0) {
7985 num.length--;
7986 if (num.words[num.length - 1] === 0) {
7987 num.length--;
7988 }
7989 }
7990 return num;
7991 };
7992
7993 function P224 () {
7994 MPrime.call(
7995 this,
7996 'p224',
7997 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
7998 }
7999 inherits(P224, MPrime);
8000
8001 function P192 () {
8002 MPrime.call(
8003 this,
8004 'p192',
8005 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
8006 }
8007 inherits(P192, MPrime);
8008
8009 function P25519 () {
8010 // 2 ^ 255 - 19
8011 MPrime.call(
8012 this,
8013 '25519',
8014 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
8015 }
8016 inherits(P25519, MPrime);
8017
8018 P25519.prototype.imulK = function imulK (num) {
8019 // K = 0x13
8020 var carry = 0;
8021 for (var i = 0; i < num.length; i++) {
8022 var hi = (num.words[i] | 0) * 0x13 + carry;
8023 var lo = hi & 0x3ffffff;
8024 hi >>>= 26;
8025
8026 num.words[i] = lo;
8027 carry = hi;
8028 }
8029 if (carry !== 0) {
8030 num.words[num.length++] = carry;
8031 }
8032 return num;
8033 };
8034
8035 // Exported mostly for testing purposes, use plain name instead
8036 BN._prime = function prime (name) {
8037 // Cached version of prime
8038 if (primes[name]) return primes[name];
8039
8040 var prime;
8041 if (name === 'k256') {
8042 prime = new K256();
8043 } else if (name === 'p224') {
8044 prime = new P224();
8045 } else if (name === 'p192') {
8046 prime = new P192();
8047 } else if (name === 'p25519') {
8048 prime = new P25519();
8049 } else {
8050 throw new Error('Unknown prime ' + name);
8051 }
8052 primes[name] = prime;
8053
8054 return prime;
8055 };
8056
8057 //
8058 // Base reduction engine
8059 //
8060 function Red (m) {
8061 if (typeof m === 'string') {
8062 var prime = BN._prime(m);
8063 this.m = prime.p;
8064 this.prime = prime;
8065 } else {
8066 assert(m.gtn(1), 'modulus must be greater than 1');
8067 this.m = m;
8068 this.prime = null;
8069 }
8070 }
8071
8072 Red.prototype._verify1 = function _verify1 (a) {
8073 assert(a.negative === 0, 'red works only with positives');
8074 assert(a.red, 'red works only with red numbers');
8075 };
8076
8077 Red.prototype._verify2 = function _verify2 (a, b) {
8078 assert((a.negative | b.negative) === 0, 'red works only with positives');
8079 assert(a.red && a.red === b.red,
8080 'red works only with red numbers');
8081 };
8082
8083 Red.prototype.imod = function imod (a) {
8084 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
8085 return a.umod(this.m)._forceRed(this);
8086 };
8087
8088 Red.prototype.neg = function neg (a) {
8089 if (a.isZero()) {
8090 return a.clone();
8091 }
8092
8093 return this.m.sub(a)._forceRed(this);
8094 };
8095
8096 Red.prototype.add = function add (a, b) {
8097 this._verify2(a, b);
8098
8099 var res = a.add(b);
8100 if (res.cmp(this.m) >= 0) {
8101 res.isub(this.m);
8102 }
8103 return res._forceRed(this);
8104 };
8105
8106 Red.prototype.iadd = function iadd (a, b) {
8107 this._verify2(a, b);
8108
8109 var res = a.iadd(b);
8110 if (res.cmp(this.m) >= 0) {
8111 res.isub(this.m);
8112 }
8113 return res;
8114 };
8115
8116 Red.prototype.sub = function sub (a, b) {
8117 this._verify2(a, b);
8118
8119 var res = a.sub(b);
8120 if (res.cmpn(0) < 0) {
8121 res.iadd(this.m);
8122 }
8123 return res._forceRed(this);
8124 };
8125
8126 Red.prototype.isub = function isub (a, b) {
8127 this._verify2(a, b);
8128
8129 var res = a.isub(b);
8130 if (res.cmpn(0) < 0) {
8131 res.iadd(this.m);
8132 }
8133 return res;
8134 };
8135
8136 Red.prototype.shl = function shl (a, num) {
8137 this._verify1(a);
8138 return this.imod(a.ushln(num));
8139 };
8140
8141 Red.prototype.imul = function imul (a, b) {
8142 this._verify2(a, b);
8143 return this.imod(a.imul(b));
8144 };
8145
8146 Red.prototype.mul = function mul (a, b) {
8147 this._verify2(a, b);
8148 return this.imod(a.mul(b));
8149 };
8150
8151 Red.prototype.isqr = function isqr (a) {
8152 return this.imul(a, a.clone());
8153 };
8154
8155 Red.prototype.sqr = function sqr (a) {
8156 return this.mul(a, a);
8157 };
8158
8159 Red.prototype.sqrt = function sqrt (a) {
8160 if (a.isZero()) return a.clone();
8161
8162 var mod3 = this.m.andln(3);
8163 assert(mod3 % 2 === 1);
8164
8165 // Fast case
8166 if (mod3 === 3) {
8167 var pow = this.m.add(new BN(1)).iushrn(2);
8168 return this.pow(a, pow);
8169 }
8170
8171 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
8172 //
8173 // Find Q and S, that Q * 2 ^ S = (P - 1)
8174 var q = this.m.subn(1);
8175 var s = 0;
8176 while (!q.isZero() && q.andln(1) === 0) {
8177 s++;
8178 q.iushrn(1);
8179 }
8180 assert(!q.isZero());
8181
8182 var one = new BN(1).toRed(this);
8183 var nOne = one.redNeg();
8184
8185 // Find quadratic non-residue
8186 // NOTE: Max is such because of generalized Riemann hypothesis.
8187 var lpow = this.m.subn(1).iushrn(1);
8188 var z = this.m.bitLength();
8189 z = new BN(2 * z * z).toRed(this);
8190
8191 while (this.pow(z, lpow).cmp(nOne) !== 0) {
8192 z.redIAdd(nOne);
8193 }
8194
8195 var c = this.pow(z, q);
8196 var r = this.pow(a, q.addn(1).iushrn(1));
8197 var t = this.pow(a, q);
8198 var m = s;
8199 while (t.cmp(one) !== 0) {
8200 var tmp = t;
8201 for (var i = 0; tmp.cmp(one) !== 0; i++) {
8202 tmp = tmp.redSqr();
8203 }
8204 assert(i < m);
8205 var b = this.pow(c, new BN(1).iushln(m - i - 1));
8206
8207 r = r.redMul(b);
8208 c = b.redSqr();
8209 t = t.redMul(c);
8210 m = i;
8211 }
8212
8213 return r;
8214 };
8215
8216 Red.prototype.invm = function invm (a) {
8217 var inv = a._invmp(this.m);
8218 if (inv.negative !== 0) {
8219 inv.negative = 0;
8220 return this.imod(inv).redNeg();
8221 } else {
8222 return this.imod(inv);
8223 }
8224 };
8225
8226 Red.prototype.pow = function pow (a, num) {
8227 if (num.isZero()) return new BN(1).toRed(this);
8228 if (num.cmpn(1) === 0) return a.clone();
8229
8230 var windowSize = 4;
8231 var wnd = new Array(1 << windowSize);
8232 wnd[0] = new BN(1).toRed(this);
8233 wnd[1] = a;
8234 for (var i = 2; i < wnd.length; i++) {
8235 wnd[i] = this.mul(wnd[i - 1], a);
8236 }
8237
8238 var res = wnd[0];
8239 var current = 0;
8240 var currentLen = 0;
8241 var start = num.bitLength() % 26;
8242 if (start === 0) {
8243 start = 26;
8244 }
8245
8246 for (i = num.length - 1; i >= 0; i--) {
8247 var word = num.words[i];
8248 for (var j = start - 1; j >= 0; j--) {
8249 var bit = (word >> j) & 1;
8250 if (res !== wnd[0]) {
8251 res = this.sqr(res);
8252 }
8253
8254 if (bit === 0 && current === 0) {
8255 currentLen = 0;
8256 continue;
8257 }
8258
8259 current <<= 1;
8260 current |= bit;
8261 currentLen++;
8262 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
8263
8264 res = this.mul(res, wnd[current]);
8265 currentLen = 0;
8266 current = 0;
8267 }
8268 start = 26;
8269 }
8270
8271 return res;
8272 };
8273
8274 Red.prototype.convertTo = function convertTo (num) {
8275 var r = num.umod(this.m);
8276
8277 return r === num ? r.clone() : r;
8278 };
8279
8280 Red.prototype.convertFrom = function convertFrom (num) {
8281 var res = num.clone();
8282 res.red = null;
8283 return res;
8284 };
8285
8286 //
8287 // Montgomery method engine
8288 //
8289
8290 BN.mont = function mont (num) {
8291 return new Mont(num);
8292 };
8293
8294 function Mont (m) {
8295 Red.call(this, m);
8296
8297 this.shift = this.m.bitLength();
8298 if (this.shift % 26 !== 0) {
8299 this.shift += 26 - (this.shift % 26);
8300 }
8301
8302 this.r = new BN(1).iushln(this.shift);
8303 this.r2 = this.imod(this.r.sqr());
8304 this.rinv = this.r._invmp(this.m);
8305
8306 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
8307 this.minv = this.minv.umod(this.r);
8308 this.minv = this.r.sub(this.minv);
8309 }
8310 inherits(Mont, Red);
8311
8312 Mont.prototype.convertTo = function convertTo (num) {
8313 return this.imod(num.ushln(this.shift));
8314 };
8315
8316 Mont.prototype.convertFrom = function convertFrom (num) {
8317 var r = this.imod(num.mul(this.rinv));
8318 r.red = null;
8319 return r;
8320 };
8321
8322 Mont.prototype.imul = function imul (a, b) {
8323 if (a.isZero() || b.isZero()) {
8324 a.words[0] = 0;
8325 a.length = 1;
8326 return a;
8327 }
8328
8329 var t = a.imul(b);
8330 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
8331 var u = t.isub(c).iushrn(this.shift);
8332 var res = u;
8333
8334 if (u.cmp(this.m) >= 0) {
8335 res = u.isub(this.m);
8336 } else if (u.cmpn(0) < 0) {
8337 res = u.iadd(this.m);
8338 }
8339
8340 return res._forceRed(this);
8341 };
8342
8343 Mont.prototype.mul = function mul (a, b) {
8344 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
8345
8346 var t = a.mul(b);
8347 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
8348 var u = t.isub(c).iushrn(this.shift);
8349 var res = u;
8350 if (u.cmp(this.m) >= 0) {
8351 res = u.isub(this.m);
8352 } else if (u.cmpn(0) < 0) {
8353 res = u.iadd(this.m);
8354 }
8355
8356 return res._forceRed(this);
8357 };
8358
8359 Mont.prototype.invm = function invm (a) {
8360 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
8361 var res = this.imod(a._invmp(this.m).mul(this.r2));
8362 return res._forceRed(this);
8363 };
8364})(typeof module === 'undefined' || module, this);
8365
8366},{"buffer":20}],19:[function(require,module,exports){
8367var r;
8368
8369module.exports = function rand(len) {
8370 if (!r)
8371 r = new Rand(null);
8372
8373 return r.generate(len);
8374};
8375
8376function Rand(rand) {
8377 this.rand = rand;
8378}
8379module.exports.Rand = Rand;
8380
8381Rand.prototype.generate = function generate(len) {
8382 return this._rand(len);
8383};
8384
8385// Emulate crypto API using randy
8386Rand.prototype._rand = function _rand(n) {
8387 if (this.rand.getBytes)
8388 return this.rand.getBytes(n);
8389
8390 var res = new Uint8Array(n);
8391 for (var i = 0; i < res.length; i++)
8392 res[i] = this.rand.getByte();
8393 return res;
8394};
8395
8396if (typeof self === 'object') {
8397 if (self.crypto && self.crypto.getRandomValues) {
8398 // Modern browsers
8399 Rand.prototype._rand = function _rand(n) {
8400 var arr = new Uint8Array(n);
8401 self.crypto.getRandomValues(arr);
8402 return arr;
8403 };
8404 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
8405 // IE
8406 Rand.prototype._rand = function _rand(n) {
8407 var arr = new Uint8Array(n);
8408 self.msCrypto.getRandomValues(arr);
8409 return arr;
8410 };
8411
8412 // Safari's WebWorkers do not have `crypto`
8413 } else if (typeof window === 'object') {
8414 // Old junk
8415 Rand.prototype._rand = function() {
8416 throw new Error('Not implemented yet');
8417 };
8418 }
8419} else {
8420 // Node.js or Web worker with no crypto support
8421 try {
8422 var crypto = require('crypto');
8423 if (typeof crypto.randomBytes !== 'function')
8424 throw new Error('Not supported');
8425
8426 Rand.prototype._rand = function _rand(n) {
8427 return crypto.randomBytes(n);
8428 };
8429 } catch (e) {
8430 }
8431}
8432
8433},{"crypto":20}],20:[function(require,module,exports){
8434
8435},{}],21:[function(require,module,exports){
8436// based on the aes implimentation in triple sec
8437// https://github.com/keybase/triplesec
8438// which is in turn based on the one from crypto-js
8439// https://code.google.com/p/crypto-js/
8440
8441var Buffer = require('safe-buffer').Buffer
8442
8443function asUInt32Array (buf) {
8444 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
8445
8446 var len = (buf.length / 4) | 0
8447 var out = new Array(len)
8448
8449 for (var i = 0; i < len; i++) {
8450 out[i] = buf.readUInt32BE(i * 4)
8451 }
8452
8453 return out
8454}
8455
8456function scrubVec (v) {
8457 for (var i = 0; i < v.length; v++) {
8458 v[i] = 0
8459 }
8460}
8461
8462function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
8463 var SUB_MIX0 = SUB_MIX[0]
8464 var SUB_MIX1 = SUB_MIX[1]
8465 var SUB_MIX2 = SUB_MIX[2]
8466 var SUB_MIX3 = SUB_MIX[3]
8467
8468 var s0 = M[0] ^ keySchedule[0]
8469 var s1 = M[1] ^ keySchedule[1]
8470 var s2 = M[2] ^ keySchedule[2]
8471 var s3 = M[3] ^ keySchedule[3]
8472 var t0, t1, t2, t3
8473 var ksRow = 4
8474
8475 for (var round = 1; round < nRounds; round++) {
8476 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
8477 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
8478 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
8479 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
8480 s0 = t0
8481 s1 = t1
8482 s2 = t2
8483 s3 = t3
8484 }
8485
8486 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
8487 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
8488 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
8489 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
8490 t0 = t0 >>> 0
8491 t1 = t1 >>> 0
8492 t2 = t2 >>> 0
8493 t3 = t3 >>> 0
8494
8495 return [t0, t1, t2, t3]
8496}
8497
8498// AES constants
8499var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
8500var G = (function () {
8501 // Compute double table
8502 var d = new Array(256)
8503 for (var j = 0; j < 256; j++) {
8504 if (j < 128) {
8505 d[j] = j << 1
8506 } else {
8507 d[j] = (j << 1) ^ 0x11b
8508 }
8509 }
8510
8511 var SBOX = []
8512 var INV_SBOX = []
8513 var SUB_MIX = [[], [], [], []]
8514 var INV_SUB_MIX = [[], [], [], []]
8515
8516 // Walk GF(2^8)
8517 var x = 0
8518 var xi = 0
8519 for (var i = 0; i < 256; ++i) {
8520 // Compute sbox
8521 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
8522 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
8523 SBOX[x] = sx
8524 INV_SBOX[sx] = x
8525
8526 // Compute multiplication
8527 var x2 = d[x]
8528 var x4 = d[x2]
8529 var x8 = d[x4]
8530
8531 // Compute sub bytes, mix columns tables
8532 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
8533 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
8534 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
8535 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
8536 SUB_MIX[3][x] = t
8537
8538 // Compute inv sub bytes, inv mix columns tables
8539 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
8540 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
8541 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
8542 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
8543 INV_SUB_MIX[3][sx] = t
8544
8545 if (x === 0) {
8546 x = xi = 1
8547 } else {
8548 x = x2 ^ d[d[d[x8 ^ x2]]]
8549 xi ^= d[d[xi]]
8550 }
8551 }
8552
8553 return {
8554 SBOX: SBOX,
8555 INV_SBOX: INV_SBOX,
8556 SUB_MIX: SUB_MIX,
8557 INV_SUB_MIX: INV_SUB_MIX
8558 }
8559})()
8560
8561function AES (key) {
8562 this._key = asUInt32Array(key)
8563 this._reset()
8564}
8565
8566AES.blockSize = 4 * 4
8567AES.keySize = 256 / 8
8568AES.prototype.blockSize = AES.blockSize
8569AES.prototype.keySize = AES.keySize
8570AES.prototype._reset = function () {
8571 var keyWords = this._key
8572 var keySize = keyWords.length
8573 var nRounds = keySize + 6
8574 var ksRows = (nRounds + 1) * 4
8575
8576 var keySchedule = []
8577 for (var k = 0; k < keySize; k++) {
8578 keySchedule[k] = keyWords[k]
8579 }
8580
8581 for (k = keySize; k < ksRows; k++) {
8582 var t = keySchedule[k - 1]
8583
8584 if (k % keySize === 0) {
8585 t = (t << 8) | (t >>> 24)
8586 t =
8587 (G.SBOX[t >>> 24] << 24) |
8588 (G.SBOX[(t >>> 16) & 0xff] << 16) |
8589 (G.SBOX[(t >>> 8) & 0xff] << 8) |
8590 (G.SBOX[t & 0xff])
8591
8592 t ^= RCON[(k / keySize) | 0] << 24
8593 } else if (keySize > 6 && k % keySize === 4) {
8594 t =
8595 (G.SBOX[t >>> 24] << 24) |
8596 (G.SBOX[(t >>> 16) & 0xff] << 16) |
8597 (G.SBOX[(t >>> 8) & 0xff] << 8) |
8598 (G.SBOX[t & 0xff])
8599 }
8600
8601 keySchedule[k] = keySchedule[k - keySize] ^ t
8602 }
8603
8604 var invKeySchedule = []
8605 for (var ik = 0; ik < ksRows; ik++) {
8606 var ksR = ksRows - ik
8607 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
8608
8609 if (ik < 4 || ksR <= 4) {
8610 invKeySchedule[ik] = tt
8611 } else {
8612 invKeySchedule[ik] =
8613 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
8614 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
8615 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
8616 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
8617 }
8618 }
8619
8620 this._nRounds = nRounds
8621 this._keySchedule = keySchedule
8622 this._invKeySchedule = invKeySchedule
8623}
8624
8625AES.prototype.encryptBlockRaw = function (M) {
8626 M = asUInt32Array(M)
8627 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
8628}
8629
8630AES.prototype.encryptBlock = function (M) {
8631 var out = this.encryptBlockRaw(M)
8632 var buf = Buffer.allocUnsafe(16)
8633 buf.writeUInt32BE(out[0], 0)
8634 buf.writeUInt32BE(out[1], 4)
8635 buf.writeUInt32BE(out[2], 8)
8636 buf.writeUInt32BE(out[3], 12)
8637 return buf
8638}
8639
8640AES.prototype.decryptBlock = function (M) {
8641 M = asUInt32Array(M)
8642
8643 // swap
8644 var m1 = M[1]
8645 M[1] = M[3]
8646 M[3] = m1
8647
8648 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
8649 var buf = Buffer.allocUnsafe(16)
8650 buf.writeUInt32BE(out[0], 0)
8651 buf.writeUInt32BE(out[3], 4)
8652 buf.writeUInt32BE(out[2], 8)
8653 buf.writeUInt32BE(out[1], 12)
8654 return buf
8655}
8656
8657AES.prototype.scrub = function () {
8658 scrubVec(this._keySchedule)
8659 scrubVec(this._invKeySchedule)
8660 scrubVec(this._key)
8661}
8662
8663module.exports.AES = AES
8664
8665},{"safe-buffer":393}],22:[function(require,module,exports){
8666var aes = require('./aes')
8667var Buffer = require('safe-buffer').Buffer
8668var Transform = require('cipher-base')
8669var inherits = require('inherits')
8670var GHASH = require('./ghash')
8671var xor = require('buffer-xor')
8672var incr32 = require('./incr32')
8673
8674function xorTest (a, b) {
8675 var out = 0
8676 if (a.length !== b.length) out++
8677
8678 var len = Math.min(a.length, b.length)
8679 for (var i = 0; i < len; ++i) {
8680 out += (a[i] ^ b[i])
8681 }
8682
8683 return out
8684}
8685
8686function calcIv (self, iv, ck) {
8687 if (iv.length === 12) {
8688 self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
8689 return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
8690 }
8691 var ghash = new GHASH(ck)
8692 var len = iv.length
8693 var toPad = len % 16
8694 ghash.update(iv)
8695 if (toPad) {
8696 toPad = 16 - toPad
8697 ghash.update(Buffer.alloc(toPad, 0))
8698 }
8699 ghash.update(Buffer.alloc(8, 0))
8700 var ivBits = len * 8
8701 var tail = Buffer.alloc(8)
8702 tail.writeUIntBE(ivBits, 0, 8)
8703 ghash.update(tail)
8704 self._finID = ghash.state
8705 var out = Buffer.from(self._finID)
8706 incr32(out)
8707 return out
8708}
8709function StreamCipher (mode, key, iv, decrypt) {
8710 Transform.call(this)
8711
8712 var h = Buffer.alloc(4, 0)
8713
8714 this._cipher = new aes.AES(key)
8715 var ck = this._cipher.encryptBlock(h)
8716 this._ghash = new GHASH(ck)
8717 iv = calcIv(this, iv, ck)
8718
8719 this._prev = Buffer.from(iv)
8720 this._cache = Buffer.allocUnsafe(0)
8721 this._secCache = Buffer.allocUnsafe(0)
8722 this._decrypt = decrypt
8723 this._alen = 0
8724 this._len = 0
8725 this._mode = mode
8726
8727 this._authTag = null
8728 this._called = false
8729}
8730
8731inherits(StreamCipher, Transform)
8732
8733StreamCipher.prototype._update = function (chunk) {
8734 if (!this._called && this._alen) {
8735 var rump = 16 - (this._alen % 16)
8736 if (rump < 16) {
8737 rump = Buffer.alloc(rump, 0)
8738 this._ghash.update(rump)
8739 }
8740 }
8741
8742 this._called = true
8743 var out = this._mode.encrypt(this, chunk)
8744 if (this._decrypt) {
8745 this._ghash.update(chunk)
8746 } else {
8747 this._ghash.update(out)
8748 }
8749 this._len += chunk.length
8750 return out
8751}
8752
8753StreamCipher.prototype._final = function () {
8754 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
8755
8756 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
8757 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
8758
8759 this._authTag = tag
8760 this._cipher.scrub()
8761}
8762
8763StreamCipher.prototype.getAuthTag = function getAuthTag () {
8764 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
8765
8766 return this._authTag
8767}
8768
8769StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
8770 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
8771
8772 this._authTag = tag
8773}
8774
8775StreamCipher.prototype.setAAD = function setAAD (buf) {
8776 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
8777
8778 this._ghash.update(buf)
8779 this._alen += buf.length
8780}
8781
8782module.exports = StreamCipher
8783
8784},{"./aes":21,"./ghash":26,"./incr32":27,"buffer-xor":48,"cipher-base":50,"inherits":116,"safe-buffer":393}],23:[function(require,module,exports){
8785var ciphers = require('./encrypter')
8786var deciphers = require('./decrypter')
8787var modes = require('./modes/list.json')
8788
8789function getCiphers () {
8790 return Object.keys(modes)
8791}
8792
8793exports.createCipher = exports.Cipher = ciphers.createCipher
8794exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
8795exports.createDecipher = exports.Decipher = deciphers.createDecipher
8796exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
8797exports.listCiphers = exports.getCiphers = getCiphers
8798
8799},{"./decrypter":24,"./encrypter":25,"./modes/list.json":35}],24:[function(require,module,exports){
8800var AuthCipher = require('./authCipher')
8801var Buffer = require('safe-buffer').Buffer
8802var MODES = require('./modes')
8803var StreamCipher = require('./streamCipher')
8804var Transform = require('cipher-base')
8805var aes = require('./aes')
8806var ebtk = require('evp_bytestokey')
8807var inherits = require('inherits')
8808
8809function Decipher (mode, key, iv) {
8810 Transform.call(this)
8811
8812 this._cache = new Splitter()
8813 this._last = void 0
8814 this._cipher = new aes.AES(key)
8815 this._prev = Buffer.from(iv)
8816 this._mode = mode
8817 this._autopadding = true
8818}
8819
8820inherits(Decipher, Transform)
8821
8822Decipher.prototype._update = function (data) {
8823 this._cache.add(data)
8824 var chunk
8825 var thing
8826 var out = []
8827 while ((chunk = this._cache.get(this._autopadding))) {
8828 thing = this._mode.decrypt(this, chunk)
8829 out.push(thing)
8830 }
8831 return Buffer.concat(out)
8832}
8833
8834Decipher.prototype._final = function () {
8835 var chunk = this._cache.flush()
8836 if (this._autopadding) {
8837 return unpad(this._mode.decrypt(this, chunk))
8838 } else if (chunk) {
8839 throw new Error('data not multiple of block length')
8840 }
8841}
8842
8843Decipher.prototype.setAutoPadding = function (setTo) {
8844 this._autopadding = !!setTo
8845 return this
8846}
8847
8848function Splitter () {
8849 this.cache = Buffer.allocUnsafe(0)
8850}
8851
8852Splitter.prototype.add = function (data) {
8853 this.cache = Buffer.concat([this.cache, data])
8854}
8855
8856Splitter.prototype.get = function (autoPadding) {
8857 var out
8858 if (autoPadding) {
8859 if (this.cache.length > 16) {
8860 out = this.cache.slice(0, 16)
8861 this.cache = this.cache.slice(16)
8862 return out
8863 }
8864 } else {
8865 if (this.cache.length >= 16) {
8866 out = this.cache.slice(0, 16)
8867 this.cache = this.cache.slice(16)
8868 return out
8869 }
8870 }
8871
8872 return null
8873}
8874
8875Splitter.prototype.flush = function () {
8876 if (this.cache.length) return this.cache
8877}
8878
8879function unpad (last) {
8880 var padded = last[15]
8881 if (padded < 1 || padded > 16) {
8882 throw new Error('unable to decrypt data')
8883 }
8884 var i = -1
8885 while (++i < padded) {
8886 if (last[(i + (16 - padded))] !== padded) {
8887 throw new Error('unable to decrypt data')
8888 }
8889 }
8890 if (padded === 16) return
8891
8892 return last.slice(0, 16 - padded)
8893}
8894
8895function createDecipheriv (suite, password, iv) {
8896 var config = MODES[suite.toLowerCase()]
8897 if (!config) throw new TypeError('invalid suite type')
8898
8899 if (typeof iv === 'string') iv = Buffer.from(iv)
8900 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
8901
8902 if (typeof password === 'string') password = Buffer.from(password)
8903 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
8904
8905 if (config.type === 'stream') {
8906 return new StreamCipher(config.module, password, iv, true)
8907 } else if (config.type === 'auth') {
8908 return new AuthCipher(config.module, password, iv, true)
8909 }
8910
8911 return new Decipher(config.module, password, iv)
8912}
8913
8914function createDecipher (suite, password) {
8915 var config = MODES[suite.toLowerCase()]
8916 if (!config) throw new TypeError('invalid suite type')
8917
8918 var keys = ebtk(password, false, config.key, config.iv)
8919 return createDecipheriv(suite, keys.key, keys.iv)
8920}
8921
8922exports.createDecipher = createDecipher
8923exports.createDecipheriv = createDecipheriv
8924
8925},{"./aes":21,"./authCipher":22,"./modes":34,"./streamCipher":37,"cipher-base":50,"evp_bytestokey":100,"inherits":116,"safe-buffer":393}],25:[function(require,module,exports){
8926var MODES = require('./modes')
8927var AuthCipher = require('./authCipher')
8928var Buffer = require('safe-buffer').Buffer
8929var StreamCipher = require('./streamCipher')
8930var Transform = require('cipher-base')
8931var aes = require('./aes')
8932var ebtk = require('evp_bytestokey')
8933var inherits = require('inherits')
8934
8935function Cipher (mode, key, iv) {
8936 Transform.call(this)
8937
8938 this._cache = new Splitter()
8939 this._cipher = new aes.AES(key)
8940 this._prev = Buffer.from(iv)
8941 this._mode = mode
8942 this._autopadding = true
8943}
8944
8945inherits(Cipher, Transform)
8946
8947Cipher.prototype._update = function (data) {
8948 this._cache.add(data)
8949 var chunk
8950 var thing
8951 var out = []
8952
8953 while ((chunk = this._cache.get())) {
8954 thing = this._mode.encrypt(this, chunk)
8955 out.push(thing)
8956 }
8957
8958 return Buffer.concat(out)
8959}
8960
8961var PADDING = Buffer.alloc(16, 0x10)
8962
8963Cipher.prototype._final = function () {
8964 var chunk = this._cache.flush()
8965 if (this._autopadding) {
8966 chunk = this._mode.encrypt(this, chunk)
8967 this._cipher.scrub()
8968 return chunk
8969 }
8970
8971 if (!chunk.equals(PADDING)) {
8972 this._cipher.scrub()
8973 throw new Error('data not multiple of block length')
8974 }
8975}
8976
8977Cipher.prototype.setAutoPadding = function (setTo) {
8978 this._autopadding = !!setTo
8979 return this
8980}
8981
8982function Splitter () {
8983 this.cache = Buffer.allocUnsafe(0)
8984}
8985
8986Splitter.prototype.add = function (data) {
8987 this.cache = Buffer.concat([this.cache, data])
8988}
8989
8990Splitter.prototype.get = function () {
8991 if (this.cache.length > 15) {
8992 var out = this.cache.slice(0, 16)
8993 this.cache = this.cache.slice(16)
8994 return out
8995 }
8996 return null
8997}
8998
8999Splitter.prototype.flush = function () {
9000 var len = 16 - this.cache.length
9001 var padBuff = Buffer.allocUnsafe(len)
9002
9003 var i = -1
9004 while (++i < len) {
9005 padBuff.writeUInt8(len, i)
9006 }
9007
9008 return Buffer.concat([this.cache, padBuff])
9009}
9010
9011function createCipheriv (suite, password, iv) {
9012 var config = MODES[suite.toLowerCase()]
9013 if (!config) throw new TypeError('invalid suite type')
9014
9015 if (typeof password === 'string') password = Buffer.from(password)
9016 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
9017
9018 if (typeof iv === 'string') iv = Buffer.from(iv)
9019 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
9020
9021 if (config.type === 'stream') {
9022 return new StreamCipher(config.module, password, iv)
9023 } else if (config.type === 'auth') {
9024 return new AuthCipher(config.module, password, iv)
9025 }
9026
9027 return new Cipher(config.module, password, iv)
9028}
9029
9030function createCipher (suite, password) {
9031 var config = MODES[suite.toLowerCase()]
9032 if (!config) throw new TypeError('invalid suite type')
9033
9034 var keys = ebtk(password, false, config.key, config.iv)
9035 return createCipheriv(suite, keys.key, keys.iv)
9036}
9037
9038exports.createCipheriv = createCipheriv
9039exports.createCipher = createCipher
9040
9041},{"./aes":21,"./authCipher":22,"./modes":34,"./streamCipher":37,"cipher-base":50,"evp_bytestokey":100,"inherits":116,"safe-buffer":393}],26:[function(require,module,exports){
9042var Buffer = require('safe-buffer').Buffer
9043var ZEROES = Buffer.alloc(16, 0)
9044
9045function toArray (buf) {
9046 return [
9047 buf.readUInt32BE(0),
9048 buf.readUInt32BE(4),
9049 buf.readUInt32BE(8),
9050 buf.readUInt32BE(12)
9051 ]
9052}
9053
9054function fromArray (out) {
9055 var buf = Buffer.allocUnsafe(16)
9056 buf.writeUInt32BE(out[0] >>> 0, 0)
9057 buf.writeUInt32BE(out[1] >>> 0, 4)
9058 buf.writeUInt32BE(out[2] >>> 0, 8)
9059 buf.writeUInt32BE(out[3] >>> 0, 12)
9060 return buf
9061}
9062
9063function GHASH (key) {
9064 this.h = key
9065 this.state = Buffer.alloc(16, 0)
9066 this.cache = Buffer.allocUnsafe(0)
9067}
9068
9069// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
9070// by Juho Vähä-Herttua
9071GHASH.prototype.ghash = function (block) {
9072 var i = -1
9073 while (++i < block.length) {
9074 this.state[i] ^= block[i]
9075 }
9076 this._multiply()
9077}
9078
9079GHASH.prototype._multiply = function () {
9080 var Vi = toArray(this.h)
9081 var Zi = [0, 0, 0, 0]
9082 var j, xi, lsbVi
9083 var i = -1
9084 while (++i < 128) {
9085 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
9086 if (xi) {
9087 // Z_i+1 = Z_i ^ V_i
9088 Zi[0] ^= Vi[0]
9089 Zi[1] ^= Vi[1]
9090 Zi[2] ^= Vi[2]
9091 Zi[3] ^= Vi[3]
9092 }
9093
9094 // Store the value of LSB(V_i)
9095 lsbVi = (Vi[3] & 1) !== 0
9096
9097 // V_i+1 = V_i >> 1
9098 for (j = 3; j > 0; j--) {
9099 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
9100 }
9101 Vi[0] = Vi[0] >>> 1
9102
9103 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
9104 if (lsbVi) {
9105 Vi[0] = Vi[0] ^ (0xe1 << 24)
9106 }
9107 }
9108 this.state = fromArray(Zi)
9109}
9110
9111GHASH.prototype.update = function (buf) {
9112 this.cache = Buffer.concat([this.cache, buf])
9113 var chunk
9114 while (this.cache.length >= 16) {
9115 chunk = this.cache.slice(0, 16)
9116 this.cache = this.cache.slice(16)
9117 this.ghash(chunk)
9118 }
9119}
9120
9121GHASH.prototype.final = function (abl, bl) {
9122 if (this.cache.length) {
9123 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
9124 }
9125
9126 this.ghash(fromArray([0, abl, 0, bl]))
9127 return this.state
9128}
9129
9130module.exports = GHASH
9131
9132},{"safe-buffer":393}],27:[function(require,module,exports){
9133function incr32 (iv) {
9134 var len = iv.length
9135 var item
9136 while (len--) {
9137 item = iv.readUInt8(len)
9138 if (item === 255) {
9139 iv.writeUInt8(0, len)
9140 } else {
9141 item++
9142 iv.writeUInt8(item, len)
9143 break
9144 }
9145 }
9146}
9147module.exports = incr32
9148
9149},{}],28:[function(require,module,exports){
9150var xor = require('buffer-xor')
9151
9152exports.encrypt = function (self, block) {
9153 var data = xor(block, self._prev)
9154
9155 self._prev = self._cipher.encryptBlock(data)
9156 return self._prev
9157}
9158
9159exports.decrypt = function (self, block) {
9160 var pad = self._prev
9161
9162 self._prev = block
9163 var out = self._cipher.decryptBlock(block)
9164
9165 return xor(out, pad)
9166}
9167
9168},{"buffer-xor":48}],29:[function(require,module,exports){
9169var Buffer = require('safe-buffer').Buffer
9170var xor = require('buffer-xor')
9171
9172function encryptStart (self, data, decrypt) {
9173 var len = data.length
9174 var out = xor(data, self._cache)
9175 self._cache = self._cache.slice(len)
9176 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
9177 return out
9178}
9179
9180exports.encrypt = function (self, data, decrypt) {
9181 var out = Buffer.allocUnsafe(0)
9182 var len
9183
9184 while (data.length) {
9185 if (self._cache.length === 0) {
9186 self._cache = self._cipher.encryptBlock(self._prev)
9187 self._prev = Buffer.allocUnsafe(0)
9188 }
9189
9190 if (self._cache.length <= data.length) {
9191 len = self._cache.length
9192 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
9193 data = data.slice(len)
9194 } else {
9195 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
9196 break
9197 }
9198 }
9199
9200 return out
9201}
9202
9203},{"buffer-xor":48,"safe-buffer":393}],30:[function(require,module,exports){
9204var Buffer = require('safe-buffer').Buffer
9205
9206function encryptByte (self, byteParam, decrypt) {
9207 var pad
9208 var i = -1
9209 var len = 8
9210 var out = 0
9211 var bit, value
9212 while (++i < len) {
9213 pad = self._cipher.encryptBlock(self._prev)
9214 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
9215 value = pad[0] ^ bit
9216 out += ((value & 0x80) >> (i % 8))
9217 self._prev = shiftIn(self._prev, decrypt ? bit : value)
9218 }
9219 return out
9220}
9221
9222function shiftIn (buffer, value) {
9223 var len = buffer.length
9224 var i = -1
9225 var out = Buffer.allocUnsafe(buffer.length)
9226 buffer = Buffer.concat([buffer, Buffer.from([value])])
9227
9228 while (++i < len) {
9229 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
9230 }
9231
9232 return out
9233}
9234
9235exports.encrypt = function (self, chunk, decrypt) {
9236 var len = chunk.length
9237 var out = Buffer.allocUnsafe(len)
9238 var i = -1
9239
9240 while (++i < len) {
9241 out[i] = encryptByte(self, chunk[i], decrypt)
9242 }
9243
9244 return out
9245}
9246
9247},{"safe-buffer":393}],31:[function(require,module,exports){
9248var Buffer = require('safe-buffer').Buffer
9249
9250function encryptByte (self, byteParam, decrypt) {
9251 var pad = self._cipher.encryptBlock(self._prev)
9252 var out = pad[0] ^ byteParam
9253
9254 self._prev = Buffer.concat([
9255 self._prev.slice(1),
9256 Buffer.from([decrypt ? byteParam : out])
9257 ])
9258
9259 return out
9260}
9261
9262exports.encrypt = function (self, chunk, decrypt) {
9263 var len = chunk.length
9264 var out = Buffer.allocUnsafe(len)
9265 var i = -1
9266
9267 while (++i < len) {
9268 out[i] = encryptByte(self, chunk[i], decrypt)
9269 }
9270
9271 return out
9272}
9273
9274},{"safe-buffer":393}],32:[function(require,module,exports){
9275var xor = require('buffer-xor')
9276var Buffer = require('safe-buffer').Buffer
9277var incr32 = require('../incr32')
9278
9279function getBlock (self) {
9280 var out = self._cipher.encryptBlockRaw(self._prev)
9281 incr32(self._prev)
9282 return out
9283}
9284
9285var blockSize = 16
9286exports.encrypt = function (self, chunk) {
9287 var chunkNum = Math.ceil(chunk.length / blockSize)
9288 var start = self._cache.length
9289 self._cache = Buffer.concat([
9290 self._cache,
9291 Buffer.allocUnsafe(chunkNum * blockSize)
9292 ])
9293 for (var i = 0; i < chunkNum; i++) {
9294 var out = getBlock(self)
9295 var offset = start + i * blockSize
9296 self._cache.writeUInt32BE(out[0], offset + 0)
9297 self._cache.writeUInt32BE(out[1], offset + 4)
9298 self._cache.writeUInt32BE(out[2], offset + 8)
9299 self._cache.writeUInt32BE(out[3], offset + 12)
9300 }
9301 var pad = self._cache.slice(0, chunk.length)
9302 self._cache = self._cache.slice(chunk.length)
9303 return xor(chunk, pad)
9304}
9305
9306},{"../incr32":27,"buffer-xor":48,"safe-buffer":393}],33:[function(require,module,exports){
9307exports.encrypt = function (self, block) {
9308 return self._cipher.encryptBlock(block)
9309}
9310
9311exports.decrypt = function (self, block) {
9312 return self._cipher.decryptBlock(block)
9313}
9314
9315},{}],34:[function(require,module,exports){
9316var modeModules = {
9317 ECB: require('./ecb'),
9318 CBC: require('./cbc'),
9319 CFB: require('./cfb'),
9320 CFB8: require('./cfb8'),
9321 CFB1: require('./cfb1'),
9322 OFB: require('./ofb'),
9323 CTR: require('./ctr'),
9324 GCM: require('./ctr')
9325}
9326
9327var modes = require('./list.json')
9328
9329for (var key in modes) {
9330 modes[key].module = modeModules[modes[key].mode]
9331}
9332
9333module.exports = modes
9334
9335},{"./cbc":28,"./cfb":29,"./cfb1":30,"./cfb8":31,"./ctr":32,"./ecb":33,"./list.json":35,"./ofb":36}],35:[function(require,module,exports){
9336module.exports={
9337 "aes-128-ecb": {
9338 "cipher": "AES",
9339 "key": 128,
9340 "iv": 0,
9341 "mode": "ECB",
9342 "type": "block"
9343 },
9344 "aes-192-ecb": {
9345 "cipher": "AES",
9346 "key": 192,
9347 "iv": 0,
9348 "mode": "ECB",
9349 "type": "block"
9350 },
9351 "aes-256-ecb": {
9352 "cipher": "AES",
9353 "key": 256,
9354 "iv": 0,
9355 "mode": "ECB",
9356 "type": "block"
9357 },
9358 "aes-128-cbc": {
9359 "cipher": "AES",
9360 "key": 128,
9361 "iv": 16,
9362 "mode": "CBC",
9363 "type": "block"
9364 },
9365 "aes-192-cbc": {
9366 "cipher": "AES",
9367 "key": 192,
9368 "iv": 16,
9369 "mode": "CBC",
9370 "type": "block"
9371 },
9372 "aes-256-cbc": {
9373 "cipher": "AES",
9374 "key": 256,
9375 "iv": 16,
9376 "mode": "CBC",
9377 "type": "block"
9378 },
9379 "aes128": {
9380 "cipher": "AES",
9381 "key": 128,
9382 "iv": 16,
9383 "mode": "CBC",
9384 "type": "block"
9385 },
9386 "aes192": {
9387 "cipher": "AES",
9388 "key": 192,
9389 "iv": 16,
9390 "mode": "CBC",
9391 "type": "block"
9392 },
9393 "aes256": {
9394 "cipher": "AES",
9395 "key": 256,
9396 "iv": 16,
9397 "mode": "CBC",
9398 "type": "block"
9399 },
9400 "aes-128-cfb": {
9401 "cipher": "AES",
9402 "key": 128,
9403 "iv": 16,
9404 "mode": "CFB",
9405 "type": "stream"
9406 },
9407 "aes-192-cfb": {
9408 "cipher": "AES",
9409 "key": 192,
9410 "iv": 16,
9411 "mode": "CFB",
9412 "type": "stream"
9413 },
9414 "aes-256-cfb": {
9415 "cipher": "AES",
9416 "key": 256,
9417 "iv": 16,
9418 "mode": "CFB",
9419 "type": "stream"
9420 },
9421 "aes-128-cfb8": {
9422 "cipher": "AES",
9423 "key": 128,
9424 "iv": 16,
9425 "mode": "CFB8",
9426 "type": "stream"
9427 },
9428 "aes-192-cfb8": {
9429 "cipher": "AES",
9430 "key": 192,
9431 "iv": 16,
9432 "mode": "CFB8",
9433 "type": "stream"
9434 },
9435 "aes-256-cfb8": {
9436 "cipher": "AES",
9437 "key": 256,
9438 "iv": 16,
9439 "mode": "CFB8",
9440 "type": "stream"
9441 },
9442 "aes-128-cfb1": {
9443 "cipher": "AES",
9444 "key": 128,
9445 "iv": 16,
9446 "mode": "CFB1",
9447 "type": "stream"
9448 },
9449 "aes-192-cfb1": {
9450 "cipher": "AES",
9451 "key": 192,
9452 "iv": 16,
9453 "mode": "CFB1",
9454 "type": "stream"
9455 },
9456 "aes-256-cfb1": {
9457 "cipher": "AES",
9458 "key": 256,
9459 "iv": 16,
9460 "mode": "CFB1",
9461 "type": "stream"
9462 },
9463 "aes-128-ofb": {
9464 "cipher": "AES",
9465 "key": 128,
9466 "iv": 16,
9467 "mode": "OFB",
9468 "type": "stream"
9469 },
9470 "aes-192-ofb": {
9471 "cipher": "AES",
9472 "key": 192,
9473 "iv": 16,
9474 "mode": "OFB",
9475 "type": "stream"
9476 },
9477 "aes-256-ofb": {
9478 "cipher": "AES",
9479 "key": 256,
9480 "iv": 16,
9481 "mode": "OFB",
9482 "type": "stream"
9483 },
9484 "aes-128-ctr": {
9485 "cipher": "AES",
9486 "key": 128,
9487 "iv": 16,
9488 "mode": "CTR",
9489 "type": "stream"
9490 },
9491 "aes-192-ctr": {
9492 "cipher": "AES",
9493 "key": 192,
9494 "iv": 16,
9495 "mode": "CTR",
9496 "type": "stream"
9497 },
9498 "aes-256-ctr": {
9499 "cipher": "AES",
9500 "key": 256,
9501 "iv": 16,
9502 "mode": "CTR",
9503 "type": "stream"
9504 },
9505 "aes-128-gcm": {
9506 "cipher": "AES",
9507 "key": 128,
9508 "iv": 12,
9509 "mode": "GCM",
9510 "type": "auth"
9511 },
9512 "aes-192-gcm": {
9513 "cipher": "AES",
9514 "key": 192,
9515 "iv": 12,
9516 "mode": "GCM",
9517 "type": "auth"
9518 },
9519 "aes-256-gcm": {
9520 "cipher": "AES",
9521 "key": 256,
9522 "iv": 12,
9523 "mode": "GCM",
9524 "type": "auth"
9525 }
9526}
9527
9528},{}],36:[function(require,module,exports){
9529(function (Buffer){
9530var xor = require('buffer-xor')
9531
9532function getBlock (self) {
9533 self._prev = self._cipher.encryptBlock(self._prev)
9534 return self._prev
9535}
9536
9537exports.encrypt = function (self, chunk) {
9538 while (self._cache.length < chunk.length) {
9539 self._cache = Buffer.concat([self._cache, getBlock(self)])
9540 }
9541
9542 var pad = self._cache.slice(0, chunk.length)
9543 self._cache = self._cache.slice(chunk.length)
9544 return xor(chunk, pad)
9545}
9546
9547}).call(this,require("buffer").Buffer)
9548},{"buffer":49,"buffer-xor":48}],37:[function(require,module,exports){
9549var aes = require('./aes')
9550var Buffer = require('safe-buffer').Buffer
9551var Transform = require('cipher-base')
9552var inherits = require('inherits')
9553
9554function StreamCipher (mode, key, iv, decrypt) {
9555 Transform.call(this)
9556
9557 this._cipher = new aes.AES(key)
9558 this._prev = Buffer.from(iv)
9559 this._cache = Buffer.allocUnsafe(0)
9560 this._secCache = Buffer.allocUnsafe(0)
9561 this._decrypt = decrypt
9562 this._mode = mode
9563}
9564
9565inherits(StreamCipher, Transform)
9566
9567StreamCipher.prototype._update = function (chunk) {
9568 return this._mode.encrypt(this, chunk, this._decrypt)
9569}
9570
9571StreamCipher.prototype._final = function () {
9572 this._cipher.scrub()
9573}
9574
9575module.exports = StreamCipher
9576
9577},{"./aes":21,"cipher-base":50,"inherits":116,"safe-buffer":393}],38:[function(require,module,exports){
9578var DES = require('browserify-des')
9579var aes = require('browserify-aes/browser')
9580var aesModes = require('browserify-aes/modes')
9581var desModes = require('browserify-des/modes')
9582var ebtk = require('evp_bytestokey')
9583
9584function createCipher (suite, password) {
9585 suite = suite.toLowerCase()
9586
9587 var keyLen, ivLen
9588 if (aesModes[suite]) {
9589 keyLen = aesModes[suite].key
9590 ivLen = aesModes[suite].iv
9591 } else if (desModes[suite]) {
9592 keyLen = desModes[suite].key * 8
9593 ivLen = desModes[suite].iv
9594 } else {
9595 throw new TypeError('invalid suite type')
9596 }
9597
9598 var keys = ebtk(password, false, keyLen, ivLen)
9599 return createCipheriv(suite, keys.key, keys.iv)
9600}
9601
9602function createDecipher (suite, password) {
9603 suite = suite.toLowerCase()
9604
9605 var keyLen, ivLen
9606 if (aesModes[suite]) {
9607 keyLen = aesModes[suite].key
9608 ivLen = aesModes[suite].iv
9609 } else if (desModes[suite]) {
9610 keyLen = desModes[suite].key * 8
9611 ivLen = desModes[suite].iv
9612 } else {
9613 throw new TypeError('invalid suite type')
9614 }
9615
9616 var keys = ebtk(password, false, keyLen, ivLen)
9617 return createDecipheriv(suite, keys.key, keys.iv)
9618}
9619
9620function createCipheriv (suite, key, iv) {
9621 suite = suite.toLowerCase()
9622 if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
9623 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })
9624
9625 throw new TypeError('invalid suite type')
9626}
9627
9628function createDecipheriv (suite, key, iv) {
9629 suite = suite.toLowerCase()
9630 if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
9631 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })
9632
9633 throw new TypeError('invalid suite type')
9634}
9635
9636function getCiphers () {
9637 return Object.keys(desModes).concat(aes.getCiphers())
9638}
9639
9640exports.createCipher = exports.Cipher = createCipher
9641exports.createCipheriv = exports.Cipheriv = createCipheriv
9642exports.createDecipher = exports.Decipher = createDecipher
9643exports.createDecipheriv = exports.Decipheriv = createDecipheriv
9644exports.listCiphers = exports.getCiphers = getCiphers
9645
9646},{"browserify-aes/browser":23,"browserify-aes/modes":34,"browserify-des":39,"browserify-des/modes":40,"evp_bytestokey":100}],39:[function(require,module,exports){
9647var CipherBase = require('cipher-base')
9648var des = require('des.js')
9649var inherits = require('inherits')
9650var Buffer = require('safe-buffer').Buffer
9651
9652var modes = {
9653 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
9654 'des-ede3': des.EDE,
9655 'des-ede-cbc': des.CBC.instantiate(des.EDE),
9656 'des-ede': des.EDE,
9657 'des-cbc': des.CBC.instantiate(des.DES),
9658 'des-ecb': des.DES
9659}
9660modes.des = modes['des-cbc']
9661modes.des3 = modes['des-ede3-cbc']
9662module.exports = DES
9663inherits(DES, CipherBase)
9664function DES (opts) {
9665 CipherBase.call(this)
9666 var modeName = opts.mode.toLowerCase()
9667 var mode = modes[modeName]
9668 var type
9669 if (opts.decrypt) {
9670 type = 'decrypt'
9671 } else {
9672 type = 'encrypt'
9673 }
9674 var key = opts.key
9675 if (!Buffer.isBuffer(key)) {
9676 key = Buffer.from(key)
9677 }
9678 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
9679 key = Buffer.concat([key, key.slice(0, 8)])
9680 }
9681 var iv = opts.iv
9682 if (!Buffer.isBuffer(iv)) {
9683 iv = Buffer.from(iv)
9684 }
9685 this._des = mode.create({
9686 key: key,
9687 iv: iv,
9688 type: type
9689 })
9690}
9691DES.prototype._update = function (data) {
9692 return Buffer.from(this._des.update(data))
9693}
9694DES.prototype._final = function () {
9695 return Buffer.from(this._des.final())
9696}
9697
9698},{"cipher-base":50,"des.js":73,"inherits":116,"safe-buffer":393}],40:[function(require,module,exports){
9699exports['des-ecb'] = {
9700 key: 8,
9701 iv: 0
9702}
9703exports['des-cbc'] = exports.des = {
9704 key: 8,
9705 iv: 8
9706}
9707exports['des-ede3-cbc'] = exports.des3 = {
9708 key: 24,
9709 iv: 8
9710}
9711exports['des-ede3'] = {
9712 key: 24,
9713 iv: 0
9714}
9715exports['des-ede-cbc'] = {
9716 key: 16,
9717 iv: 8
9718}
9719exports['des-ede'] = {
9720 key: 16,
9721 iv: 0
9722}
9723
9724},{}],41:[function(require,module,exports){
9725(function (Buffer){
9726var bn = require('bn.js');
9727var randomBytes = require('randombytes');
9728module.exports = crt;
9729function blind(priv) {
9730 var r = getr(priv);
9731 var blinder = r.toRed(bn.mont(priv.modulus))
9732 .redPow(new bn(priv.publicExponent)).fromRed();
9733 return {
9734 blinder: blinder,
9735 unblinder:r.invm(priv.modulus)
9736 };
9737}
9738function crt(msg, priv) {
9739 var blinds = blind(priv);
9740 var len = priv.modulus.byteLength();
9741 var mod = bn.mont(priv.modulus);
9742 var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
9743 var c1 = blinded.toRed(bn.mont(priv.prime1));
9744 var c2 = blinded.toRed(bn.mont(priv.prime2));
9745 var qinv = priv.coefficient;
9746 var p = priv.prime1;
9747 var q = priv.prime2;
9748 var m1 = c1.redPow(priv.exponent1);
9749 var m2 = c2.redPow(priv.exponent2);
9750 m1 = m1.fromRed();
9751 m2 = m2.fromRed();
9752 var h = m1.isub(m2).imul(qinv).umod(p);
9753 h.imul(q);
9754 m2.iadd(h);
9755 return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
9756}
9757crt.getr = getr;
9758function getr(priv) {
9759 var len = priv.modulus.byteLength();
9760 var r = new bn(randomBytes(len));
9761 while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
9762 r = new bn(randomBytes(len));
9763 }
9764 return r;
9765}
9766
9767}).call(this,require("buffer").Buffer)
9768},{"bn.js":18,"buffer":49,"randombytes":376}],42:[function(require,module,exports){
9769module.exports = require('./browser/algorithms.json')
9770
9771},{"./browser/algorithms.json":43}],43:[function(require,module,exports){
9772module.exports={
9773 "sha224WithRSAEncryption": {
9774 "sign": "rsa",
9775 "hash": "sha224",
9776 "id": "302d300d06096086480165030402040500041c"
9777 },
9778 "RSA-SHA224": {
9779 "sign": "ecdsa/rsa",
9780 "hash": "sha224",
9781 "id": "302d300d06096086480165030402040500041c"
9782 },
9783 "sha256WithRSAEncryption": {
9784 "sign": "rsa",
9785 "hash": "sha256",
9786 "id": "3031300d060960864801650304020105000420"
9787 },
9788 "RSA-SHA256": {
9789 "sign": "ecdsa/rsa",
9790 "hash": "sha256",
9791 "id": "3031300d060960864801650304020105000420"
9792 },
9793 "sha384WithRSAEncryption": {
9794 "sign": "rsa",
9795 "hash": "sha384",
9796 "id": "3041300d060960864801650304020205000430"
9797 },
9798 "RSA-SHA384": {
9799 "sign": "ecdsa/rsa",
9800 "hash": "sha384",
9801 "id": "3041300d060960864801650304020205000430"
9802 },
9803 "sha512WithRSAEncryption": {
9804 "sign": "rsa",
9805 "hash": "sha512",
9806 "id": "3051300d060960864801650304020305000440"
9807 },
9808 "RSA-SHA512": {
9809 "sign": "ecdsa/rsa",
9810 "hash": "sha512",
9811 "id": "3051300d060960864801650304020305000440"
9812 },
9813 "RSA-SHA1": {
9814 "sign": "rsa",
9815 "hash": "sha1",
9816 "id": "3021300906052b0e03021a05000414"
9817 },
9818 "ecdsa-with-SHA1": {
9819 "sign": "ecdsa",
9820 "hash": "sha1",
9821 "id": ""
9822 },
9823 "sha256": {
9824 "sign": "ecdsa",
9825 "hash": "sha256",
9826 "id": ""
9827 },
9828 "sha224": {
9829 "sign": "ecdsa",
9830 "hash": "sha224",
9831 "id": ""
9832 },
9833 "sha384": {
9834 "sign": "ecdsa",
9835 "hash": "sha384",
9836 "id": ""
9837 },
9838 "sha512": {
9839 "sign": "ecdsa",
9840 "hash": "sha512",
9841 "id": ""
9842 },
9843 "DSA-SHA": {
9844 "sign": "dsa",
9845 "hash": "sha1",
9846 "id": ""
9847 },
9848 "DSA-SHA1": {
9849 "sign": "dsa",
9850 "hash": "sha1",
9851 "id": ""
9852 },
9853 "DSA": {
9854 "sign": "dsa",
9855 "hash": "sha1",
9856 "id": ""
9857 },
9858 "DSA-WITH-SHA224": {
9859 "sign": "dsa",
9860 "hash": "sha224",
9861 "id": ""
9862 },
9863 "DSA-SHA224": {
9864 "sign": "dsa",
9865 "hash": "sha224",
9866 "id": ""
9867 },
9868 "DSA-WITH-SHA256": {
9869 "sign": "dsa",
9870 "hash": "sha256",
9871 "id": ""
9872 },
9873 "DSA-SHA256": {
9874 "sign": "dsa",
9875 "hash": "sha256",
9876 "id": ""
9877 },
9878 "DSA-WITH-SHA384": {
9879 "sign": "dsa",
9880 "hash": "sha384",
9881 "id": ""
9882 },
9883 "DSA-SHA384": {
9884 "sign": "dsa",
9885 "hash": "sha384",
9886 "id": ""
9887 },
9888 "DSA-WITH-SHA512": {
9889 "sign": "dsa",
9890 "hash": "sha512",
9891 "id": ""
9892 },
9893 "DSA-SHA512": {
9894 "sign": "dsa",
9895 "hash": "sha512",
9896 "id": ""
9897 },
9898 "DSA-RIPEMD160": {
9899 "sign": "dsa",
9900 "hash": "rmd160",
9901 "id": ""
9902 },
9903 "ripemd160WithRSA": {
9904 "sign": "rsa",
9905 "hash": "rmd160",
9906 "id": "3021300906052b2403020105000414"
9907 },
9908 "RSA-RIPEMD160": {
9909 "sign": "rsa",
9910 "hash": "rmd160",
9911 "id": "3021300906052b2403020105000414"
9912 },
9913 "md5WithRSAEncryption": {
9914 "sign": "rsa",
9915 "hash": "md5",
9916 "id": "3020300c06082a864886f70d020505000410"
9917 },
9918 "RSA-MD5": {
9919 "sign": "rsa",
9920 "hash": "md5",
9921 "id": "3020300c06082a864886f70d020505000410"
9922 }
9923}
9924
9925},{}],44:[function(require,module,exports){
9926module.exports={
9927 "1.3.132.0.10": "secp256k1",
9928 "1.3.132.0.33": "p224",
9929 "1.2.840.10045.3.1.1": "p192",
9930 "1.2.840.10045.3.1.7": "p256",
9931 "1.3.132.0.34": "p384",
9932 "1.3.132.0.35": "p521"
9933}
9934
9935},{}],45:[function(require,module,exports){
9936(function (Buffer){
9937var createHash = require('create-hash')
9938var stream = require('stream')
9939var inherits = require('inherits')
9940var sign = require('./sign')
9941var verify = require('./verify')
9942
9943var algorithms = require('./algorithms.json')
9944Object.keys(algorithms).forEach(function (key) {
9945 algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
9946 algorithms[key.toLowerCase()] = algorithms[key]
9947})
9948
9949function Sign (algorithm) {
9950 stream.Writable.call(this)
9951
9952 var data = algorithms[algorithm]
9953 if (!data) throw new Error('Unknown message digest')
9954
9955 this._hashType = data.hash
9956 this._hash = createHash(data.hash)
9957 this._tag = data.id
9958 this._signType = data.sign
9959}
9960inherits(Sign, stream.Writable)
9961
9962Sign.prototype._write = function _write (data, _, done) {
9963 this._hash.update(data)
9964 done()
9965}
9966
9967Sign.prototype.update = function update (data, enc) {
9968 if (typeof data === 'string') data = new Buffer(data, enc)
9969
9970 this._hash.update(data)
9971 return this
9972}
9973
9974Sign.prototype.sign = function signMethod (key, enc) {
9975 this.end()
9976 var hash = this._hash.digest()
9977 var sig = sign(hash, key, this._hashType, this._signType, this._tag)
9978
9979 return enc ? sig.toString(enc) : sig
9980}
9981
9982function Verify (algorithm) {
9983 stream.Writable.call(this)
9984
9985 var data = algorithms[algorithm]
9986 if (!data) throw new Error('Unknown message digest')
9987
9988 this._hash = createHash(data.hash)
9989 this._tag = data.id
9990 this._signType = data.sign
9991}
9992inherits(Verify, stream.Writable)
9993
9994Verify.prototype._write = function _write (data, _, done) {
9995 this._hash.update(data)
9996 done()
9997}
9998
9999Verify.prototype.update = function update (data, enc) {
10000 if (typeof data === 'string') data = new Buffer(data, enc)
10001
10002 this._hash.update(data)
10003 return this
10004}
10005
10006Verify.prototype.verify = function verifyMethod (key, sig, enc) {
10007 if (typeof sig === 'string') sig = new Buffer(sig, enc)
10008
10009 this.end()
10010 var hash = this._hash.digest()
10011 return verify(sig, hash, key, this._signType, this._tag)
10012}
10013
10014function createSign (algorithm) {
10015 return new Sign(algorithm)
10016}
10017
10018function createVerify (algorithm) {
10019 return new Verify(algorithm)
10020}
10021
10022module.exports = {
10023 Sign: createSign,
10024 Verify: createVerify,
10025 createSign: createSign,
10026 createVerify: createVerify
10027}
10028
10029}).call(this,require("buffer").Buffer)
10030},{"./algorithms.json":43,"./sign":46,"./verify":47,"buffer":49,"create-hash":67,"inherits":116,"stream":432}],46:[function(require,module,exports){
10031(function (Buffer){
10032// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
10033var createHmac = require('create-hmac')
10034var crt = require('browserify-rsa')
10035var EC = require('elliptic').ec
10036var BN = require('bn.js')
10037var parseKeys = require('parse-asn1')
10038var curves = require('./curves.json')
10039
10040function sign (hash, key, hashType, signType, tag) {
10041 var priv = parseKeys(key)
10042 if (priv.curve) {
10043 // rsa keys can be interpreted as ecdsa ones in openssl
10044 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
10045 return ecSign(hash, priv)
10046 } else if (priv.type === 'dsa') {
10047 if (signType !== 'dsa') throw new Error('wrong private key type')
10048 return dsaSign(hash, priv, hashType)
10049 } else {
10050 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
10051 }
10052 hash = Buffer.concat([tag, hash])
10053 var len = priv.modulus.byteLength()
10054 var pad = [ 0, 1 ]
10055 while (hash.length + pad.length + 1 < len) pad.push(0xff)
10056 pad.push(0x00)
10057 var i = -1
10058 while (++i < hash.length) pad.push(hash[i])
10059
10060 var out = crt(pad, priv)
10061 return out
10062}
10063
10064function ecSign (hash, priv) {
10065 var curveId = curves[priv.curve.join('.')]
10066 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
10067
10068 var curve = new EC(curveId)
10069 var key = curve.keyFromPrivate(priv.privateKey)
10070 var out = key.sign(hash)
10071
10072 return new Buffer(out.toDER())
10073}
10074
10075function dsaSign (hash, priv, algo) {
10076 var x = priv.params.priv_key
10077 var p = priv.params.p
10078 var q = priv.params.q
10079 var g = priv.params.g
10080 var r = new BN(0)
10081 var k
10082 var H = bits2int(hash, q).mod(q)
10083 var s = false
10084 var kv = getKey(x, q, hash, algo)
10085 while (s === false) {
10086 k = makeKey(q, kv, algo)
10087 r = makeR(g, k, p, q)
10088 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
10089 if (s.cmpn(0) === 0) {
10090 s = false
10091 r = new BN(0)
10092 }
10093 }
10094 return toDER(r, s)
10095}
10096
10097function toDER (r, s) {
10098 r = r.toArray()
10099 s = s.toArray()
10100
10101 // Pad values
10102 if (r[0] & 0x80) r = [ 0 ].concat(r)
10103 if (s[0] & 0x80) s = [ 0 ].concat(s)
10104
10105 var total = r.length + s.length + 4
10106 var res = [ 0x30, total, 0x02, r.length ]
10107 res = res.concat(r, [ 0x02, s.length ], s)
10108 return new Buffer(res)
10109}
10110
10111function getKey (x, q, hash, algo) {
10112 x = new Buffer(x.toArray())
10113 if (x.length < q.byteLength()) {
10114 var zeros = new Buffer(q.byteLength() - x.length)
10115 zeros.fill(0)
10116 x = Buffer.concat([ zeros, x ])
10117 }
10118 var hlen = hash.length
10119 var hbits = bits2octets(hash, q)
10120 var v = new Buffer(hlen)
10121 v.fill(1)
10122 var k = new Buffer(hlen)
10123 k.fill(0)
10124 k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
10125 v = createHmac(algo, k).update(v).digest()
10126 k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
10127 v = createHmac(algo, k).update(v).digest()
10128 return { k: k, v: v }
10129}
10130
10131function bits2int (obits, q) {
10132 var bits = new BN(obits)
10133 var shift = (obits.length << 3) - q.bitLength()
10134 if (shift > 0) bits.ishrn(shift)
10135 return bits
10136}
10137
10138function bits2octets (bits, q) {
10139 bits = bits2int(bits, q)
10140 bits = bits.mod(q)
10141 var out = new Buffer(bits.toArray())
10142 if (out.length < q.byteLength()) {
10143 var zeros = new Buffer(q.byteLength() - out.length)
10144 zeros.fill(0)
10145 out = Buffer.concat([ zeros, out ])
10146 }
10147 return out
10148}
10149
10150function makeKey (q, kv, algo) {
10151 var t
10152 var k
10153
10154 do {
10155 t = new Buffer(0)
10156
10157 while (t.length * 8 < q.bitLength()) {
10158 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
10159 t = Buffer.concat([ t, kv.v ])
10160 }
10161
10162 k = bits2int(t, q)
10163 kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
10164 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
10165 } while (k.cmp(q) !== -1)
10166
10167 return k
10168}
10169
10170function makeR (g, k, p, q) {
10171 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
10172}
10173
10174module.exports = sign
10175module.exports.getKey = getKey
10176module.exports.makeKey = makeKey
10177
10178}).call(this,require("buffer").Buffer)
10179},{"./curves.json":44,"bn.js":18,"browserify-rsa":41,"buffer":49,"create-hmac":69,"elliptic":83,"parse-asn1":362}],47:[function(require,module,exports){
10180(function (Buffer){
10181// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
10182var BN = require('bn.js')
10183var EC = require('elliptic').ec
10184var parseKeys = require('parse-asn1')
10185var curves = require('./curves.json')
10186
10187function verify (sig, hash, key, signType, tag) {
10188 var pub = parseKeys(key)
10189 if (pub.type === 'ec') {
10190 // rsa keys can be interpreted as ecdsa ones in openssl
10191 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
10192 return ecVerify(sig, hash, pub)
10193 } else if (pub.type === 'dsa') {
10194 if (signType !== 'dsa') throw new Error('wrong public key type')
10195 return dsaVerify(sig, hash, pub)
10196 } else {
10197 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
10198 }
10199 hash = Buffer.concat([tag, hash])
10200 var len = pub.modulus.byteLength()
10201 var pad = [ 1 ]
10202 var padNum = 0
10203 while (hash.length + pad.length + 2 < len) {
10204 pad.push(0xff)
10205 padNum++
10206 }
10207 pad.push(0x00)
10208 var i = -1
10209 while (++i < hash.length) {
10210 pad.push(hash[i])
10211 }
10212 pad = new Buffer(pad)
10213 var red = BN.mont(pub.modulus)
10214 sig = new BN(sig).toRed(red)
10215
10216 sig = sig.redPow(new BN(pub.publicExponent))
10217 sig = new Buffer(sig.fromRed().toArray())
10218 var out = padNum < 8 ? 1 : 0
10219 len = Math.min(sig.length, pad.length)
10220 if (sig.length !== pad.length) out = 1
10221
10222 i = -1
10223 while (++i < len) out |= sig[i] ^ pad[i]
10224 return out === 0
10225}
10226
10227function ecVerify (sig, hash, pub) {
10228 var curveId = curves[pub.data.algorithm.curve.join('.')]
10229 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
10230
10231 var curve = new EC(curveId)
10232 var pubkey = pub.data.subjectPrivateKey.data
10233
10234 return curve.verify(hash, sig, pubkey)
10235}
10236
10237function dsaVerify (sig, hash, pub) {
10238 var p = pub.data.p
10239 var q = pub.data.q
10240 var g = pub.data.g
10241 var y = pub.data.pub_key
10242 var unpacked = parseKeys.signature.decode(sig, 'der')
10243 var s = unpacked.s
10244 var r = unpacked.r
10245 checkValue(s, q)
10246 checkValue(r, q)
10247 var montp = BN.mont(p)
10248 var w = s.invm(q)
10249 var v = g.toRed(montp)
10250 .redPow(new BN(hash).mul(w).mod(q))
10251 .fromRed()
10252 .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
10253 .mod(p)
10254 .mod(q)
10255 return v.cmp(r) === 0
10256}
10257
10258function checkValue (b, q) {
10259 if (b.cmpn(0) <= 0) throw new Error('invalid sig')
10260 if (b.cmp(q) >= q) throw new Error('invalid sig')
10261}
10262
10263module.exports = verify
10264
10265}).call(this,require("buffer").Buffer)
10266},{"./curves.json":44,"bn.js":18,"buffer":49,"elliptic":83,"parse-asn1":362}],48:[function(require,module,exports){
10267(function (Buffer){
10268module.exports = function xor (a, b) {
10269 var length = Math.min(a.length, b.length)
10270 var buffer = new Buffer(length)
10271
10272 for (var i = 0; i < length; ++i) {
10273 buffer[i] = a[i] ^ b[i]
10274 }
10275
10276 return buffer
10277}
10278
10279}).call(this,require("buffer").Buffer)
10280},{"buffer":49}],49:[function(require,module,exports){
10281/*!
10282 * The buffer module from node.js, for the browser.
10283 *
10284 * @author Feross Aboukhadijeh <https://feross.org>
10285 * @license MIT
10286 */
10287/* eslint-disable no-proto */
10288
10289'use strict'
10290
10291var base64 = require('base64-js')
10292var ieee754 = require('ieee754')
10293
10294exports.Buffer = Buffer
10295exports.SlowBuffer = SlowBuffer
10296exports.INSPECT_MAX_BYTES = 50
10297
10298var K_MAX_LENGTH = 0x7fffffff
10299exports.kMaxLength = K_MAX_LENGTH
10300
10301/**
10302 * If `Buffer.TYPED_ARRAY_SUPPORT`:
10303 * === true Use Uint8Array implementation (fastest)
10304 * === false Print warning and recommend using `buffer` v4.x which has an Object
10305 * implementation (most compatible, even IE6)
10306 *
10307 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
10308 * Opera 11.6+, iOS 4.2+.
10309 *
10310 * We report that the browser does not support typed arrays if the are not subclassable
10311 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
10312 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
10313 * for __proto__ and has a buggy typed array implementation.
10314 */
10315Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
10316
10317if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
10318 typeof console.error === 'function') {
10319 console.error(
10320 'This browser lacks typed array (Uint8Array) support which is required by ' +
10321 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
10322 )
10323}
10324
10325function typedArraySupport () {
10326 // Can typed array instances can be augmented?
10327 try {
10328 var arr = new Uint8Array(1)
10329 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
10330 return arr.foo() === 42
10331 } catch (e) {
10332 return false
10333 }
10334}
10335
10336Object.defineProperty(Buffer.prototype, 'parent', {
10337 enumerable: true,
10338 get: function () {
10339 if (!Buffer.isBuffer(this)) return undefined
10340 return this.buffer
10341 }
10342})
10343
10344Object.defineProperty(Buffer.prototype, 'offset', {
10345 enumerable: true,
10346 get: function () {
10347 if (!Buffer.isBuffer(this)) return undefined
10348 return this.byteOffset
10349 }
10350})
10351
10352function createBuffer (length) {
10353 if (length > K_MAX_LENGTH) {
10354 throw new RangeError('The value "' + length + '" is invalid for option "size"')
10355 }
10356 // Return an augmented `Uint8Array` instance
10357 var buf = new Uint8Array(length)
10358 buf.__proto__ = Buffer.prototype
10359 return buf
10360}
10361
10362/**
10363 * The Buffer constructor returns instances of `Uint8Array` that have their
10364 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
10365 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
10366 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
10367 * returns a single octet.
10368 *
10369 * The `Uint8Array` prototype remains unmodified.
10370 */
10371
10372function Buffer (arg, encodingOrOffset, length) {
10373 // Common case.
10374 if (typeof arg === 'number') {
10375 if (typeof encodingOrOffset === 'string') {
10376 throw new TypeError(
10377 'The "string" argument must be of type string. Received type number'
10378 )
10379 }
10380 return allocUnsafe(arg)
10381 }
10382 return from(arg, encodingOrOffset, length)
10383}
10384
10385// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
10386if (typeof Symbol !== 'undefined' && Symbol.species != null &&
10387 Buffer[Symbol.species] === Buffer) {
10388 Object.defineProperty(Buffer, Symbol.species, {
10389 value: null,
10390 configurable: true,
10391 enumerable: false,
10392 writable: false
10393 })
10394}
10395
10396Buffer.poolSize = 8192 // not used by this implementation
10397
10398function from (value, encodingOrOffset, length) {
10399 if (typeof value === 'string') {
10400 return fromString(value, encodingOrOffset)
10401 }
10402
10403 if (ArrayBuffer.isView(value)) {
10404 return fromArrayLike(value)
10405 }
10406
10407 if (value == null) {
10408 throw TypeError(
10409 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
10410 'or Array-like Object. Received type ' + (typeof value)
10411 )
10412 }
10413
10414 if (isInstance(value, ArrayBuffer) ||
10415 (value && isInstance(value.buffer, ArrayBuffer))) {
10416 return fromArrayBuffer(value, encodingOrOffset, length)
10417 }
10418
10419 if (typeof value === 'number') {
10420 throw new TypeError(
10421 'The "value" argument must not be of type number. Received type number'
10422 )
10423 }
10424
10425 var valueOf = value.valueOf && value.valueOf()
10426 if (valueOf != null && valueOf !== value) {
10427 return Buffer.from(valueOf, encodingOrOffset, length)
10428 }
10429
10430 var b = fromObject(value)
10431 if (b) return b
10432
10433 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
10434 typeof value[Symbol.toPrimitive] === 'function') {
10435 return Buffer.from(
10436 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
10437 )
10438 }
10439
10440 throw new TypeError(
10441 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
10442 'or Array-like Object. Received type ' + (typeof value)
10443 )
10444}
10445
10446/**
10447 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
10448 * if value is a number.
10449 * Buffer.from(str[, encoding])
10450 * Buffer.from(array)
10451 * Buffer.from(buffer)
10452 * Buffer.from(arrayBuffer[, byteOffset[, length]])
10453 **/
10454Buffer.from = function (value, encodingOrOffset, length) {
10455 return from(value, encodingOrOffset, length)
10456}
10457
10458// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
10459// https://github.com/feross/buffer/pull/148
10460Buffer.prototype.__proto__ = Uint8Array.prototype
10461Buffer.__proto__ = Uint8Array
10462
10463function assertSize (size) {
10464 if (typeof size !== 'number') {
10465 throw new TypeError('"size" argument must be of type number')
10466 } else if (size < 0) {
10467 throw new RangeError('The value "' + size + '" is invalid for option "size"')
10468 }
10469}
10470
10471function alloc (size, fill, encoding) {
10472 assertSize(size)
10473 if (size <= 0) {
10474 return createBuffer(size)
10475 }
10476 if (fill !== undefined) {
10477 // Only pay attention to encoding if it's a string. This
10478 // prevents accidentally sending in a number that would
10479 // be interpretted as a start offset.
10480 return typeof encoding === 'string'
10481 ? createBuffer(size).fill(fill, encoding)
10482 : createBuffer(size).fill(fill)
10483 }
10484 return createBuffer(size)
10485}
10486
10487/**
10488 * Creates a new filled Buffer instance.
10489 * alloc(size[, fill[, encoding]])
10490 **/
10491Buffer.alloc = function (size, fill, encoding) {
10492 return alloc(size, fill, encoding)
10493}
10494
10495function allocUnsafe (size) {
10496 assertSize(size)
10497 return createBuffer(size < 0 ? 0 : checked(size) | 0)
10498}
10499
10500/**
10501 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
10502 * */
10503Buffer.allocUnsafe = function (size) {
10504 return allocUnsafe(size)
10505}
10506/**
10507 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
10508 */
10509Buffer.allocUnsafeSlow = function (size) {
10510 return allocUnsafe(size)
10511}
10512
10513function fromString (string, encoding) {
10514 if (typeof encoding !== 'string' || encoding === '') {
10515 encoding = 'utf8'
10516 }
10517
10518 if (!Buffer.isEncoding(encoding)) {
10519 throw new TypeError('Unknown encoding: ' + encoding)
10520 }
10521
10522 var length = byteLength(string, encoding) | 0
10523 var buf = createBuffer(length)
10524
10525 var actual = buf.write(string, encoding)
10526
10527 if (actual !== length) {
10528 // Writing a hex string, for example, that contains invalid characters will
10529 // cause everything after the first invalid character to be ignored. (e.g.
10530 // 'abxxcd' will be treated as 'ab')
10531 buf = buf.slice(0, actual)
10532 }
10533
10534 return buf
10535}
10536
10537function fromArrayLike (array) {
10538 var length = array.length < 0 ? 0 : checked(array.length) | 0
10539 var buf = createBuffer(length)
10540 for (var i = 0; i < length; i += 1) {
10541 buf[i] = array[i] & 255
10542 }
10543 return buf
10544}
10545
10546function fromArrayBuffer (array, byteOffset, length) {
10547 if (byteOffset < 0 || array.byteLength < byteOffset) {
10548 throw new RangeError('"offset" is outside of buffer bounds')
10549 }
10550
10551 if (array.byteLength < byteOffset + (length || 0)) {
10552 throw new RangeError('"length" is outside of buffer bounds')
10553 }
10554
10555 var buf
10556 if (byteOffset === undefined && length === undefined) {
10557 buf = new Uint8Array(array)
10558 } else if (length === undefined) {
10559 buf = new Uint8Array(array, byteOffset)
10560 } else {
10561 buf = new Uint8Array(array, byteOffset, length)
10562 }
10563
10564 // Return an augmented `Uint8Array` instance
10565 buf.__proto__ = Buffer.prototype
10566 return buf
10567}
10568
10569function fromObject (obj) {
10570 if (Buffer.isBuffer(obj)) {
10571 var len = checked(obj.length) | 0
10572 var buf = createBuffer(len)
10573
10574 if (buf.length === 0) {
10575 return buf
10576 }
10577
10578 obj.copy(buf, 0, 0, len)
10579 return buf
10580 }
10581
10582 if (obj.length !== undefined) {
10583 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
10584 return createBuffer(0)
10585 }
10586 return fromArrayLike(obj)
10587 }
10588
10589 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
10590 return fromArrayLike(obj.data)
10591 }
10592}
10593
10594function checked (length) {
10595 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
10596 // length is NaN (which is otherwise coerced to zero.)
10597 if (length >= K_MAX_LENGTH) {
10598 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
10599 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
10600 }
10601 return length | 0
10602}
10603
10604function SlowBuffer (length) {
10605 if (+length != length) { // eslint-disable-line eqeqeq
10606 length = 0
10607 }
10608 return Buffer.alloc(+length)
10609}
10610
10611Buffer.isBuffer = function isBuffer (b) {
10612 return b != null && b._isBuffer === true &&
10613 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
10614}
10615
10616Buffer.compare = function compare (a, b) {
10617 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
10618 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
10619 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
10620 throw new TypeError(
10621 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
10622 )
10623 }
10624
10625 if (a === b) return 0
10626
10627 var x = a.length
10628 var y = b.length
10629
10630 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
10631 if (a[i] !== b[i]) {
10632 x = a[i]
10633 y = b[i]
10634 break
10635 }
10636 }
10637
10638 if (x < y) return -1
10639 if (y < x) return 1
10640 return 0
10641}
10642
10643Buffer.isEncoding = function isEncoding (encoding) {
10644 switch (String(encoding).toLowerCase()) {
10645 case 'hex':
10646 case 'utf8':
10647 case 'utf-8':
10648 case 'ascii':
10649 case 'latin1':
10650 case 'binary':
10651 case 'base64':
10652 case 'ucs2':
10653 case 'ucs-2':
10654 case 'utf16le':
10655 case 'utf-16le':
10656 return true
10657 default:
10658 return false
10659 }
10660}
10661
10662Buffer.concat = function concat (list, length) {
10663 if (!Array.isArray(list)) {
10664 throw new TypeError('"list" argument must be an Array of Buffers')
10665 }
10666
10667 if (list.length === 0) {
10668 return Buffer.alloc(0)
10669 }
10670
10671 var i
10672 if (length === undefined) {
10673 length = 0
10674 for (i = 0; i < list.length; ++i) {
10675 length += list[i].length
10676 }
10677 }
10678
10679 var buffer = Buffer.allocUnsafe(length)
10680 var pos = 0
10681 for (i = 0; i < list.length; ++i) {
10682 var buf = list[i]
10683 if (isInstance(buf, Uint8Array)) {
10684 buf = Buffer.from(buf)
10685 }
10686 if (!Buffer.isBuffer(buf)) {
10687 throw new TypeError('"list" argument must be an Array of Buffers')
10688 }
10689 buf.copy(buffer, pos)
10690 pos += buf.length
10691 }
10692 return buffer
10693}
10694
10695function byteLength (string, encoding) {
10696 if (Buffer.isBuffer(string)) {
10697 return string.length
10698 }
10699 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
10700 return string.byteLength
10701 }
10702 if (typeof string !== 'string') {
10703 throw new TypeError(
10704 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
10705 'Received type ' + typeof string
10706 )
10707 }
10708
10709 var len = string.length
10710 var mustMatch = (arguments.length > 2 && arguments[2] === true)
10711 if (!mustMatch && len === 0) return 0
10712
10713 // Use a for loop to avoid recursion
10714 var loweredCase = false
10715 for (;;) {
10716 switch (encoding) {
10717 case 'ascii':
10718 case 'latin1':
10719 case 'binary':
10720 return len
10721 case 'utf8':
10722 case 'utf-8':
10723 return utf8ToBytes(string).length
10724 case 'ucs2':
10725 case 'ucs-2':
10726 case 'utf16le':
10727 case 'utf-16le':
10728 return len * 2
10729 case 'hex':
10730 return len >>> 1
10731 case 'base64':
10732 return base64ToBytes(string).length
10733 default:
10734 if (loweredCase) {
10735 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
10736 }
10737 encoding = ('' + encoding).toLowerCase()
10738 loweredCase = true
10739 }
10740 }
10741}
10742Buffer.byteLength = byteLength
10743
10744function slowToString (encoding, start, end) {
10745 var loweredCase = false
10746
10747 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
10748 // property of a typed array.
10749
10750 // This behaves neither like String nor Uint8Array in that we set start/end
10751 // to their upper/lower bounds if the value passed is out of range.
10752 // undefined is handled specially as per ECMA-262 6th Edition,
10753 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
10754 if (start === undefined || start < 0) {
10755 start = 0
10756 }
10757 // Return early if start > this.length. Done here to prevent potential uint32
10758 // coercion fail below.
10759 if (start > this.length) {
10760 return ''
10761 }
10762
10763 if (end === undefined || end > this.length) {
10764 end = this.length
10765 }
10766
10767 if (end <= 0) {
10768 return ''
10769 }
10770
10771 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
10772 end >>>= 0
10773 start >>>= 0
10774
10775 if (end <= start) {
10776 return ''
10777 }
10778
10779 if (!encoding) encoding = 'utf8'
10780
10781 while (true) {
10782 switch (encoding) {
10783 case 'hex':
10784 return hexSlice(this, start, end)
10785
10786 case 'utf8':
10787 case 'utf-8':
10788 return utf8Slice(this, start, end)
10789
10790 case 'ascii':
10791 return asciiSlice(this, start, end)
10792
10793 case 'latin1':
10794 case 'binary':
10795 return latin1Slice(this, start, end)
10796
10797 case 'base64':
10798 return base64Slice(this, start, end)
10799
10800 case 'ucs2':
10801 case 'ucs-2':
10802 case 'utf16le':
10803 case 'utf-16le':
10804 return utf16leSlice(this, start, end)
10805
10806 default:
10807 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
10808 encoding = (encoding + '').toLowerCase()
10809 loweredCase = true
10810 }
10811 }
10812}
10813
10814// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
10815// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
10816// reliably in a browserify context because there could be multiple different
10817// copies of the 'buffer' package in use. This method works even for Buffer
10818// instances that were created from another copy of the `buffer` package.
10819// See: https://github.com/feross/buffer/issues/154
10820Buffer.prototype._isBuffer = true
10821
10822function swap (b, n, m) {
10823 var i = b[n]
10824 b[n] = b[m]
10825 b[m] = i
10826}
10827
10828Buffer.prototype.swap16 = function swap16 () {
10829 var len = this.length
10830 if (len % 2 !== 0) {
10831 throw new RangeError('Buffer size must be a multiple of 16-bits')
10832 }
10833 for (var i = 0; i < len; i += 2) {
10834 swap(this, i, i + 1)
10835 }
10836 return this
10837}
10838
10839Buffer.prototype.swap32 = function swap32 () {
10840 var len = this.length
10841 if (len % 4 !== 0) {
10842 throw new RangeError('Buffer size must be a multiple of 32-bits')
10843 }
10844 for (var i = 0; i < len; i += 4) {
10845 swap(this, i, i + 3)
10846 swap(this, i + 1, i + 2)
10847 }
10848 return this
10849}
10850
10851Buffer.prototype.swap64 = function swap64 () {
10852 var len = this.length
10853 if (len % 8 !== 0) {
10854 throw new RangeError('Buffer size must be a multiple of 64-bits')
10855 }
10856 for (var i = 0; i < len; i += 8) {
10857 swap(this, i, i + 7)
10858 swap(this, i + 1, i + 6)
10859 swap(this, i + 2, i + 5)
10860 swap(this, i + 3, i + 4)
10861 }
10862 return this
10863}
10864
10865Buffer.prototype.toString = function toString () {
10866 var length = this.length
10867 if (length === 0) return ''
10868 if (arguments.length === 0) return utf8Slice(this, 0, length)
10869 return slowToString.apply(this, arguments)
10870}
10871
10872Buffer.prototype.toLocaleString = Buffer.prototype.toString
10873
10874Buffer.prototype.equals = function equals (b) {
10875 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
10876 if (this === b) return true
10877 return Buffer.compare(this, b) === 0
10878}
10879
10880Buffer.prototype.inspect = function inspect () {
10881 var str = ''
10882 var max = exports.INSPECT_MAX_BYTES
10883 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
10884 if (this.length > max) str += ' ... '
10885 return '<Buffer ' + str + '>'
10886}
10887
10888Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
10889 if (isInstance(target, Uint8Array)) {
10890 target = Buffer.from(target, target.offset, target.byteLength)
10891 }
10892 if (!Buffer.isBuffer(target)) {
10893 throw new TypeError(
10894 'The "target" argument must be one of type Buffer or Uint8Array. ' +
10895 'Received type ' + (typeof target)
10896 )
10897 }
10898
10899 if (start === undefined) {
10900 start = 0
10901 }
10902 if (end === undefined) {
10903 end = target ? target.length : 0
10904 }
10905 if (thisStart === undefined) {
10906 thisStart = 0
10907 }
10908 if (thisEnd === undefined) {
10909 thisEnd = this.length
10910 }
10911
10912 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
10913 throw new RangeError('out of range index')
10914 }
10915
10916 if (thisStart >= thisEnd && start >= end) {
10917 return 0
10918 }
10919 if (thisStart >= thisEnd) {
10920 return -1
10921 }
10922 if (start >= end) {
10923 return 1
10924 }
10925
10926 start >>>= 0
10927 end >>>= 0
10928 thisStart >>>= 0
10929 thisEnd >>>= 0
10930
10931 if (this === target) return 0
10932
10933 var x = thisEnd - thisStart
10934 var y = end - start
10935 var len = Math.min(x, y)
10936
10937 var thisCopy = this.slice(thisStart, thisEnd)
10938 var targetCopy = target.slice(start, end)
10939
10940 for (var i = 0; i < len; ++i) {
10941 if (thisCopy[i] !== targetCopy[i]) {
10942 x = thisCopy[i]
10943 y = targetCopy[i]
10944 break
10945 }
10946 }
10947
10948 if (x < y) return -1
10949 if (y < x) return 1
10950 return 0
10951}
10952
10953// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
10954// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
10955//
10956// Arguments:
10957// - buffer - a Buffer to search
10958// - val - a string, Buffer, or number
10959// - byteOffset - an index into `buffer`; will be clamped to an int32
10960// - encoding - an optional encoding, relevant is val is a string
10961// - dir - true for indexOf, false for lastIndexOf
10962function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
10963 // Empty buffer means no match
10964 if (buffer.length === 0) return -1
10965
10966 // Normalize byteOffset
10967 if (typeof byteOffset === 'string') {
10968 encoding = byteOffset
10969 byteOffset = 0
10970 } else if (byteOffset > 0x7fffffff) {
10971 byteOffset = 0x7fffffff
10972 } else if (byteOffset < -0x80000000) {
10973 byteOffset = -0x80000000
10974 }
10975 byteOffset = +byteOffset // Coerce to Number.
10976 if (numberIsNaN(byteOffset)) {
10977 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
10978 byteOffset = dir ? 0 : (buffer.length - 1)
10979 }
10980
10981 // Normalize byteOffset: negative offsets start from the end of the buffer
10982 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
10983 if (byteOffset >= buffer.length) {
10984 if (dir) return -1
10985 else byteOffset = buffer.length - 1
10986 } else if (byteOffset < 0) {
10987 if (dir) byteOffset = 0
10988 else return -1
10989 }
10990
10991 // Normalize val
10992 if (typeof val === 'string') {
10993 val = Buffer.from(val, encoding)
10994 }
10995
10996 // Finally, search either indexOf (if dir is true) or lastIndexOf
10997 if (Buffer.isBuffer(val)) {
10998 // Special case: looking for empty string/buffer always fails
10999 if (val.length === 0) {
11000 return -1
11001 }
11002 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
11003 } else if (typeof val === 'number') {
11004 val = val & 0xFF // Search for a byte value [0-255]
11005 if (typeof Uint8Array.prototype.indexOf === 'function') {
11006 if (dir) {
11007 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
11008 } else {
11009 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
11010 }
11011 }
11012 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
11013 }
11014
11015 throw new TypeError('val must be string, number or Buffer')
11016}
11017
11018function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
11019 var indexSize = 1
11020 var arrLength = arr.length
11021 var valLength = val.length
11022
11023 if (encoding !== undefined) {
11024 encoding = String(encoding).toLowerCase()
11025 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
11026 encoding === 'utf16le' || encoding === 'utf-16le') {
11027 if (arr.length < 2 || val.length < 2) {
11028 return -1
11029 }
11030 indexSize = 2
11031 arrLength /= 2
11032 valLength /= 2
11033 byteOffset /= 2
11034 }
11035 }
11036
11037 function read (buf, i) {
11038 if (indexSize === 1) {
11039 return buf[i]
11040 } else {
11041 return buf.readUInt16BE(i * indexSize)
11042 }
11043 }
11044
11045 var i
11046 if (dir) {
11047 var foundIndex = -1
11048 for (i = byteOffset; i < arrLength; i++) {
11049 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
11050 if (foundIndex === -1) foundIndex = i
11051 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
11052 } else {
11053 if (foundIndex !== -1) i -= i - foundIndex
11054 foundIndex = -1
11055 }
11056 }
11057 } else {
11058 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
11059 for (i = byteOffset; i >= 0; i--) {
11060 var found = true
11061 for (var j = 0; j < valLength; j++) {
11062 if (read(arr, i + j) !== read(val, j)) {
11063 found = false
11064 break
11065 }
11066 }
11067 if (found) return i
11068 }
11069 }
11070
11071 return -1
11072}
11073
11074Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
11075 return this.indexOf(val, byteOffset, encoding) !== -1
11076}
11077
11078Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
11079 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
11080}
11081
11082Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
11083 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
11084}
11085
11086function hexWrite (buf, string, offset, length) {
11087 offset = Number(offset) || 0
11088 var remaining = buf.length - offset
11089 if (!length) {
11090 length = remaining
11091 } else {
11092 length = Number(length)
11093 if (length > remaining) {
11094 length = remaining
11095 }
11096 }
11097
11098 var strLen = string.length
11099
11100 if (length > strLen / 2) {
11101 length = strLen / 2
11102 }
11103 for (var i = 0; i < length; ++i) {
11104 var parsed = parseInt(string.substr(i * 2, 2), 16)
11105 if (numberIsNaN(parsed)) return i
11106 buf[offset + i] = parsed
11107 }
11108 return i
11109}
11110
11111function utf8Write (buf, string, offset, length) {
11112 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
11113}
11114
11115function asciiWrite (buf, string, offset, length) {
11116 return blitBuffer(asciiToBytes(string), buf, offset, length)
11117}
11118
11119function latin1Write (buf, string, offset, length) {
11120 return asciiWrite(buf, string, offset, length)
11121}
11122
11123function base64Write (buf, string, offset, length) {
11124 return blitBuffer(base64ToBytes(string), buf, offset, length)
11125}
11126
11127function ucs2Write (buf, string, offset, length) {
11128 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
11129}
11130
11131Buffer.prototype.write = function write (string, offset, length, encoding) {
11132 // Buffer#write(string)
11133 if (offset === undefined) {
11134 encoding = 'utf8'
11135 length = this.length
11136 offset = 0
11137 // Buffer#write(string, encoding)
11138 } else if (length === undefined && typeof offset === 'string') {
11139 encoding = offset
11140 length = this.length
11141 offset = 0
11142 // Buffer#write(string, offset[, length][, encoding])
11143 } else if (isFinite(offset)) {
11144 offset = offset >>> 0
11145 if (isFinite(length)) {
11146 length = length >>> 0
11147 if (encoding === undefined) encoding = 'utf8'
11148 } else {
11149 encoding = length
11150 length = undefined
11151 }
11152 } else {
11153 throw new Error(
11154 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
11155 )
11156 }
11157
11158 var remaining = this.length - offset
11159 if (length === undefined || length > remaining) length = remaining
11160
11161 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
11162 throw new RangeError('Attempt to write outside buffer bounds')
11163 }
11164
11165 if (!encoding) encoding = 'utf8'
11166
11167 var loweredCase = false
11168 for (;;) {
11169 switch (encoding) {
11170 case 'hex':
11171 return hexWrite(this, string, offset, length)
11172
11173 case 'utf8':
11174 case 'utf-8':
11175 return utf8Write(this, string, offset, length)
11176
11177 case 'ascii':
11178 return asciiWrite(this, string, offset, length)
11179
11180 case 'latin1':
11181 case 'binary':
11182 return latin1Write(this, string, offset, length)
11183
11184 case 'base64':
11185 // Warning: maxLength not taken into account in base64Write
11186 return base64Write(this, string, offset, length)
11187
11188 case 'ucs2':
11189 case 'ucs-2':
11190 case 'utf16le':
11191 case 'utf-16le':
11192 return ucs2Write(this, string, offset, length)
11193
11194 default:
11195 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
11196 encoding = ('' + encoding).toLowerCase()
11197 loweredCase = true
11198 }
11199 }
11200}
11201
11202Buffer.prototype.toJSON = function toJSON () {
11203 return {
11204 type: 'Buffer',
11205 data: Array.prototype.slice.call(this._arr || this, 0)
11206 }
11207}
11208
11209function base64Slice (buf, start, end) {
11210 if (start === 0 && end === buf.length) {
11211 return base64.fromByteArray(buf)
11212 } else {
11213 return base64.fromByteArray(buf.slice(start, end))
11214 }
11215}
11216
11217function utf8Slice (buf, start, end) {
11218 end = Math.min(buf.length, end)
11219 var res = []
11220
11221 var i = start
11222 while (i < end) {
11223 var firstByte = buf[i]
11224 var codePoint = null
11225 var bytesPerSequence = (firstByte > 0xEF) ? 4
11226 : (firstByte > 0xDF) ? 3
11227 : (firstByte > 0xBF) ? 2
11228 : 1
11229
11230 if (i + bytesPerSequence <= end) {
11231 var secondByte, thirdByte, fourthByte, tempCodePoint
11232
11233 switch (bytesPerSequence) {
11234 case 1:
11235 if (firstByte < 0x80) {
11236 codePoint = firstByte
11237 }
11238 break
11239 case 2:
11240 secondByte = buf[i + 1]
11241 if ((secondByte & 0xC0) === 0x80) {
11242 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
11243 if (tempCodePoint > 0x7F) {
11244 codePoint = tempCodePoint
11245 }
11246 }
11247 break
11248 case 3:
11249 secondByte = buf[i + 1]
11250 thirdByte = buf[i + 2]
11251 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
11252 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
11253 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
11254 codePoint = tempCodePoint
11255 }
11256 }
11257 break
11258 case 4:
11259 secondByte = buf[i + 1]
11260 thirdByte = buf[i + 2]
11261 fourthByte = buf[i + 3]
11262 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
11263 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
11264 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
11265 codePoint = tempCodePoint
11266 }
11267 }
11268 }
11269 }
11270
11271 if (codePoint === null) {
11272 // we did not generate a valid codePoint so insert a
11273 // replacement char (U+FFFD) and advance only 1 byte
11274 codePoint = 0xFFFD
11275 bytesPerSequence = 1
11276 } else if (codePoint > 0xFFFF) {
11277 // encode to utf16 (surrogate pair dance)
11278 codePoint -= 0x10000
11279 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
11280 codePoint = 0xDC00 | codePoint & 0x3FF
11281 }
11282
11283 res.push(codePoint)
11284 i += bytesPerSequence
11285 }
11286
11287 return decodeCodePointsArray(res)
11288}
11289
11290// Based on http://stackoverflow.com/a/22747272/680742, the browser with
11291// the lowest limit is Chrome, with 0x10000 args.
11292// We go 1 magnitude less, for safety
11293var MAX_ARGUMENTS_LENGTH = 0x1000
11294
11295function decodeCodePointsArray (codePoints) {
11296 var len = codePoints.length
11297 if (len <= MAX_ARGUMENTS_LENGTH) {
11298 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
11299 }
11300
11301 // Decode in chunks to avoid "call stack size exceeded".
11302 var res = ''
11303 var i = 0
11304 while (i < len) {
11305 res += String.fromCharCode.apply(
11306 String,
11307 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
11308 )
11309 }
11310 return res
11311}
11312
11313function asciiSlice (buf, start, end) {
11314 var ret = ''
11315 end = Math.min(buf.length, end)
11316
11317 for (var i = start; i < end; ++i) {
11318 ret += String.fromCharCode(buf[i] & 0x7F)
11319 }
11320 return ret
11321}
11322
11323function latin1Slice (buf, start, end) {
11324 var ret = ''
11325 end = Math.min(buf.length, end)
11326
11327 for (var i = start; i < end; ++i) {
11328 ret += String.fromCharCode(buf[i])
11329 }
11330 return ret
11331}
11332
11333function hexSlice (buf, start, end) {
11334 var len = buf.length
11335
11336 if (!start || start < 0) start = 0
11337 if (!end || end < 0 || end > len) end = len
11338
11339 var out = ''
11340 for (var i = start; i < end; ++i) {
11341 out += toHex(buf[i])
11342 }
11343 return out
11344}
11345
11346function utf16leSlice (buf, start, end) {
11347 var bytes = buf.slice(start, end)
11348 var res = ''
11349 for (var i = 0; i < bytes.length; i += 2) {
11350 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
11351 }
11352 return res
11353}
11354
11355Buffer.prototype.slice = function slice (start, end) {
11356 var len = this.length
11357 start = ~~start
11358 end = end === undefined ? len : ~~end
11359
11360 if (start < 0) {
11361 start += len
11362 if (start < 0) start = 0
11363 } else if (start > len) {
11364 start = len
11365 }
11366
11367 if (end < 0) {
11368 end += len
11369 if (end < 0) end = 0
11370 } else if (end > len) {
11371 end = len
11372 }
11373
11374 if (end < start) end = start
11375
11376 var newBuf = this.subarray(start, end)
11377 // Return an augmented `Uint8Array` instance
11378 newBuf.__proto__ = Buffer.prototype
11379 return newBuf
11380}
11381
11382/*
11383 * Need to make sure that buffer isn't trying to write out of bounds.
11384 */
11385function checkOffset (offset, ext, length) {
11386 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
11387 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
11388}
11389
11390Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
11391 offset = offset >>> 0
11392 byteLength = byteLength >>> 0
11393 if (!noAssert) checkOffset(offset, byteLength, this.length)
11394
11395 var val = this[offset]
11396 var mul = 1
11397 var i = 0
11398 while (++i < byteLength && (mul *= 0x100)) {
11399 val += this[offset + i] * mul
11400 }
11401
11402 return val
11403}
11404
11405Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
11406 offset = offset >>> 0
11407 byteLength = byteLength >>> 0
11408 if (!noAssert) {
11409 checkOffset(offset, byteLength, this.length)
11410 }
11411
11412 var val = this[offset + --byteLength]
11413 var mul = 1
11414 while (byteLength > 0 && (mul *= 0x100)) {
11415 val += this[offset + --byteLength] * mul
11416 }
11417
11418 return val
11419}
11420
11421Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
11422 offset = offset >>> 0
11423 if (!noAssert) checkOffset(offset, 1, this.length)
11424 return this[offset]
11425}
11426
11427Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
11428 offset = offset >>> 0
11429 if (!noAssert) checkOffset(offset, 2, this.length)
11430 return this[offset] | (this[offset + 1] << 8)
11431}
11432
11433Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
11434 offset = offset >>> 0
11435 if (!noAssert) checkOffset(offset, 2, this.length)
11436 return (this[offset] << 8) | this[offset + 1]
11437}
11438
11439Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
11440 offset = offset >>> 0
11441 if (!noAssert) checkOffset(offset, 4, this.length)
11442
11443 return ((this[offset]) |
11444 (this[offset + 1] << 8) |
11445 (this[offset + 2] << 16)) +
11446 (this[offset + 3] * 0x1000000)
11447}
11448
11449Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
11450 offset = offset >>> 0
11451 if (!noAssert) checkOffset(offset, 4, this.length)
11452
11453 return (this[offset] * 0x1000000) +
11454 ((this[offset + 1] << 16) |
11455 (this[offset + 2] << 8) |
11456 this[offset + 3])
11457}
11458
11459Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
11460 offset = offset >>> 0
11461 byteLength = byteLength >>> 0
11462 if (!noAssert) checkOffset(offset, byteLength, this.length)
11463
11464 var val = this[offset]
11465 var mul = 1
11466 var i = 0
11467 while (++i < byteLength && (mul *= 0x100)) {
11468 val += this[offset + i] * mul
11469 }
11470 mul *= 0x80
11471
11472 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
11473
11474 return val
11475}
11476
11477Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
11478 offset = offset >>> 0
11479 byteLength = byteLength >>> 0
11480 if (!noAssert) checkOffset(offset, byteLength, this.length)
11481
11482 var i = byteLength
11483 var mul = 1
11484 var val = this[offset + --i]
11485 while (i > 0 && (mul *= 0x100)) {
11486 val += this[offset + --i] * mul
11487 }
11488 mul *= 0x80
11489
11490 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
11491
11492 return val
11493}
11494
11495Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
11496 offset = offset >>> 0
11497 if (!noAssert) checkOffset(offset, 1, this.length)
11498 if (!(this[offset] & 0x80)) return (this[offset])
11499 return ((0xff - this[offset] + 1) * -1)
11500}
11501
11502Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
11503 offset = offset >>> 0
11504 if (!noAssert) checkOffset(offset, 2, this.length)
11505 var val = this[offset] | (this[offset + 1] << 8)
11506 return (val & 0x8000) ? val | 0xFFFF0000 : val
11507}
11508
11509Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
11510 offset = offset >>> 0
11511 if (!noAssert) checkOffset(offset, 2, this.length)
11512 var val = this[offset + 1] | (this[offset] << 8)
11513 return (val & 0x8000) ? val | 0xFFFF0000 : val
11514}
11515
11516Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
11517 offset = offset >>> 0
11518 if (!noAssert) checkOffset(offset, 4, this.length)
11519
11520 return (this[offset]) |
11521 (this[offset + 1] << 8) |
11522 (this[offset + 2] << 16) |
11523 (this[offset + 3] << 24)
11524}
11525
11526Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
11527 offset = offset >>> 0
11528 if (!noAssert) checkOffset(offset, 4, this.length)
11529
11530 return (this[offset] << 24) |
11531 (this[offset + 1] << 16) |
11532 (this[offset + 2] << 8) |
11533 (this[offset + 3])
11534}
11535
11536Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
11537 offset = offset >>> 0
11538 if (!noAssert) checkOffset(offset, 4, this.length)
11539 return ieee754.read(this, offset, true, 23, 4)
11540}
11541
11542Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
11543 offset = offset >>> 0
11544 if (!noAssert) checkOffset(offset, 4, this.length)
11545 return ieee754.read(this, offset, false, 23, 4)
11546}
11547
11548Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
11549 offset = offset >>> 0
11550 if (!noAssert) checkOffset(offset, 8, this.length)
11551 return ieee754.read(this, offset, true, 52, 8)
11552}
11553
11554Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
11555 offset = offset >>> 0
11556 if (!noAssert) checkOffset(offset, 8, this.length)
11557 return ieee754.read(this, offset, false, 52, 8)
11558}
11559
11560function checkInt (buf, value, offset, ext, max, min) {
11561 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
11562 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
11563 if (offset + ext > buf.length) throw new RangeError('Index out of range')
11564}
11565
11566Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
11567 value = +value
11568 offset = offset >>> 0
11569 byteLength = byteLength >>> 0
11570 if (!noAssert) {
11571 var maxBytes = Math.pow(2, 8 * byteLength) - 1
11572 checkInt(this, value, offset, byteLength, maxBytes, 0)
11573 }
11574
11575 var mul = 1
11576 var i = 0
11577 this[offset] = value & 0xFF
11578 while (++i < byteLength && (mul *= 0x100)) {
11579 this[offset + i] = (value / mul) & 0xFF
11580 }
11581
11582 return offset + byteLength
11583}
11584
11585Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
11586 value = +value
11587 offset = offset >>> 0
11588 byteLength = byteLength >>> 0
11589 if (!noAssert) {
11590 var maxBytes = Math.pow(2, 8 * byteLength) - 1
11591 checkInt(this, value, offset, byteLength, maxBytes, 0)
11592 }
11593
11594 var i = byteLength - 1
11595 var mul = 1
11596 this[offset + i] = value & 0xFF
11597 while (--i >= 0 && (mul *= 0x100)) {
11598 this[offset + i] = (value / mul) & 0xFF
11599 }
11600
11601 return offset + byteLength
11602}
11603
11604Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
11605 value = +value
11606 offset = offset >>> 0
11607 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
11608 this[offset] = (value & 0xff)
11609 return offset + 1
11610}
11611
11612Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
11613 value = +value
11614 offset = offset >>> 0
11615 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
11616 this[offset] = (value & 0xff)
11617 this[offset + 1] = (value >>> 8)
11618 return offset + 2
11619}
11620
11621Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
11622 value = +value
11623 offset = offset >>> 0
11624 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
11625 this[offset] = (value >>> 8)
11626 this[offset + 1] = (value & 0xff)
11627 return offset + 2
11628}
11629
11630Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
11631 value = +value
11632 offset = offset >>> 0
11633 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
11634 this[offset + 3] = (value >>> 24)
11635 this[offset + 2] = (value >>> 16)
11636 this[offset + 1] = (value >>> 8)
11637 this[offset] = (value & 0xff)
11638 return offset + 4
11639}
11640
11641Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
11642 value = +value
11643 offset = offset >>> 0
11644 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
11645 this[offset] = (value >>> 24)
11646 this[offset + 1] = (value >>> 16)
11647 this[offset + 2] = (value >>> 8)
11648 this[offset + 3] = (value & 0xff)
11649 return offset + 4
11650}
11651
11652Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
11653 value = +value
11654 offset = offset >>> 0
11655 if (!noAssert) {
11656 var limit = Math.pow(2, (8 * byteLength) - 1)
11657
11658 checkInt(this, value, offset, byteLength, limit - 1, -limit)
11659 }
11660
11661 var i = 0
11662 var mul = 1
11663 var sub = 0
11664 this[offset] = value & 0xFF
11665 while (++i < byteLength && (mul *= 0x100)) {
11666 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
11667 sub = 1
11668 }
11669 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
11670 }
11671
11672 return offset + byteLength
11673}
11674
11675Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
11676 value = +value
11677 offset = offset >>> 0
11678 if (!noAssert) {
11679 var limit = Math.pow(2, (8 * byteLength) - 1)
11680
11681 checkInt(this, value, offset, byteLength, limit - 1, -limit)
11682 }
11683
11684 var i = byteLength - 1
11685 var mul = 1
11686 var sub = 0
11687 this[offset + i] = value & 0xFF
11688 while (--i >= 0 && (mul *= 0x100)) {
11689 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
11690 sub = 1
11691 }
11692 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
11693 }
11694
11695 return offset + byteLength
11696}
11697
11698Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
11699 value = +value
11700 offset = offset >>> 0
11701 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
11702 if (value < 0) value = 0xff + value + 1
11703 this[offset] = (value & 0xff)
11704 return offset + 1
11705}
11706
11707Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
11708 value = +value
11709 offset = offset >>> 0
11710 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
11711 this[offset] = (value & 0xff)
11712 this[offset + 1] = (value >>> 8)
11713 return offset + 2
11714}
11715
11716Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
11717 value = +value
11718 offset = offset >>> 0
11719 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
11720 this[offset] = (value >>> 8)
11721 this[offset + 1] = (value & 0xff)
11722 return offset + 2
11723}
11724
11725Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
11726 value = +value
11727 offset = offset >>> 0
11728 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
11729 this[offset] = (value & 0xff)
11730 this[offset + 1] = (value >>> 8)
11731 this[offset + 2] = (value >>> 16)
11732 this[offset + 3] = (value >>> 24)
11733 return offset + 4
11734}
11735
11736Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
11737 value = +value
11738 offset = offset >>> 0
11739 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
11740 if (value < 0) value = 0xffffffff + value + 1
11741 this[offset] = (value >>> 24)
11742 this[offset + 1] = (value >>> 16)
11743 this[offset + 2] = (value >>> 8)
11744 this[offset + 3] = (value & 0xff)
11745 return offset + 4
11746}
11747
11748function checkIEEE754 (buf, value, offset, ext, max, min) {
11749 if (offset + ext > buf.length) throw new RangeError('Index out of range')
11750 if (offset < 0) throw new RangeError('Index out of range')
11751}
11752
11753function writeFloat (buf, value, offset, littleEndian, noAssert) {
11754 value = +value
11755 offset = offset >>> 0
11756 if (!noAssert) {
11757 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
11758 }
11759 ieee754.write(buf, value, offset, littleEndian, 23, 4)
11760 return offset + 4
11761}
11762
11763Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
11764 return writeFloat(this, value, offset, true, noAssert)
11765}
11766
11767Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
11768 return writeFloat(this, value, offset, false, noAssert)
11769}
11770
11771function writeDouble (buf, value, offset, littleEndian, noAssert) {
11772 value = +value
11773 offset = offset >>> 0
11774 if (!noAssert) {
11775 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
11776 }
11777 ieee754.write(buf, value, offset, littleEndian, 52, 8)
11778 return offset + 8
11779}
11780
11781Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
11782 return writeDouble(this, value, offset, true, noAssert)
11783}
11784
11785Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
11786 return writeDouble(this, value, offset, false, noAssert)
11787}
11788
11789// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
11790Buffer.prototype.copy = function copy (target, targetStart, start, end) {
11791 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
11792 if (!start) start = 0
11793 if (!end && end !== 0) end = this.length
11794 if (targetStart >= target.length) targetStart = target.length
11795 if (!targetStart) targetStart = 0
11796 if (end > 0 && end < start) end = start
11797
11798 // Copy 0 bytes; we're done
11799 if (end === start) return 0
11800 if (target.length === 0 || this.length === 0) return 0
11801
11802 // Fatal error conditions
11803 if (targetStart < 0) {
11804 throw new RangeError('targetStart out of bounds')
11805 }
11806 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
11807 if (end < 0) throw new RangeError('sourceEnd out of bounds')
11808
11809 // Are we oob?
11810 if (end > this.length) end = this.length
11811 if (target.length - targetStart < end - start) {
11812 end = target.length - targetStart + start
11813 }
11814
11815 var len = end - start
11816
11817 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
11818 // Use built-in when available, missing from IE11
11819 this.copyWithin(targetStart, start, end)
11820 } else if (this === target && start < targetStart && targetStart < end) {
11821 // descending copy from end
11822 for (var i = len - 1; i >= 0; --i) {
11823 target[i + targetStart] = this[i + start]
11824 }
11825 } else {
11826 Uint8Array.prototype.set.call(
11827 target,
11828 this.subarray(start, end),
11829 targetStart
11830 )
11831 }
11832
11833 return len
11834}
11835
11836// Usage:
11837// buffer.fill(number[, offset[, end]])
11838// buffer.fill(buffer[, offset[, end]])
11839// buffer.fill(string[, offset[, end]][, encoding])
11840Buffer.prototype.fill = function fill (val, start, end, encoding) {
11841 // Handle string cases:
11842 if (typeof val === 'string') {
11843 if (typeof start === 'string') {
11844 encoding = start
11845 start = 0
11846 end = this.length
11847 } else if (typeof end === 'string') {
11848 encoding = end
11849 end = this.length
11850 }
11851 if (encoding !== undefined && typeof encoding !== 'string') {
11852 throw new TypeError('encoding must be a string')
11853 }
11854 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
11855 throw new TypeError('Unknown encoding: ' + encoding)
11856 }
11857 if (val.length === 1) {
11858 var code = val.charCodeAt(0)
11859 if ((encoding === 'utf8' && code < 128) ||
11860 encoding === 'latin1') {
11861 // Fast path: If `val` fits into a single byte, use that numeric value.
11862 val = code
11863 }
11864 }
11865 } else if (typeof val === 'number') {
11866 val = val & 255
11867 }
11868
11869 // Invalid ranges are not set to a default, so can range check early.
11870 if (start < 0 || this.length < start || this.length < end) {
11871 throw new RangeError('Out of range index')
11872 }
11873
11874 if (end <= start) {
11875 return this
11876 }
11877
11878 start = start >>> 0
11879 end = end === undefined ? this.length : end >>> 0
11880
11881 if (!val) val = 0
11882
11883 var i
11884 if (typeof val === 'number') {
11885 for (i = start; i < end; ++i) {
11886 this[i] = val
11887 }
11888 } else {
11889 var bytes = Buffer.isBuffer(val)
11890 ? val
11891 : Buffer.from(val, encoding)
11892 var len = bytes.length
11893 if (len === 0) {
11894 throw new TypeError('The value "' + val +
11895 '" is invalid for argument "value"')
11896 }
11897 for (i = 0; i < end - start; ++i) {
11898 this[i + start] = bytes[i % len]
11899 }
11900 }
11901
11902 return this
11903}
11904
11905// HELPER FUNCTIONS
11906// ================
11907
11908var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
11909
11910function base64clean (str) {
11911 // Node takes equal signs as end of the Base64 encoding
11912 str = str.split('=')[0]
11913 // Node strips out invalid characters like \n and \t from the string, base64-js does not
11914 str = str.trim().replace(INVALID_BASE64_RE, '')
11915 // Node converts strings with length < 2 to ''
11916 if (str.length < 2) return ''
11917 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
11918 while (str.length % 4 !== 0) {
11919 str = str + '='
11920 }
11921 return str
11922}
11923
11924function toHex (n) {
11925 if (n < 16) return '0' + n.toString(16)
11926 return n.toString(16)
11927}
11928
11929function utf8ToBytes (string, units) {
11930 units = units || Infinity
11931 var codePoint
11932 var length = string.length
11933 var leadSurrogate = null
11934 var bytes = []
11935
11936 for (var i = 0; i < length; ++i) {
11937 codePoint = string.charCodeAt(i)
11938
11939 // is surrogate component
11940 if (codePoint > 0xD7FF && codePoint < 0xE000) {
11941 // last char was a lead
11942 if (!leadSurrogate) {
11943 // no lead yet
11944 if (codePoint > 0xDBFF) {
11945 // unexpected trail
11946 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
11947 continue
11948 } else if (i + 1 === length) {
11949 // unpaired lead
11950 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
11951 continue
11952 }
11953
11954 // valid lead
11955 leadSurrogate = codePoint
11956
11957 continue
11958 }
11959
11960 // 2 leads in a row
11961 if (codePoint < 0xDC00) {
11962 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
11963 leadSurrogate = codePoint
11964 continue
11965 }
11966
11967 // valid surrogate pair
11968 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
11969 } else if (leadSurrogate) {
11970 // valid bmp char, but last char was a lead
11971 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
11972 }
11973
11974 leadSurrogate = null
11975
11976 // encode utf8
11977 if (codePoint < 0x80) {
11978 if ((units -= 1) < 0) break
11979 bytes.push(codePoint)
11980 } else if (codePoint < 0x800) {
11981 if ((units -= 2) < 0) break
11982 bytes.push(
11983 codePoint >> 0x6 | 0xC0,
11984 codePoint & 0x3F | 0x80
11985 )
11986 } else if (codePoint < 0x10000) {
11987 if ((units -= 3) < 0) break
11988 bytes.push(
11989 codePoint >> 0xC | 0xE0,
11990 codePoint >> 0x6 & 0x3F | 0x80,
11991 codePoint & 0x3F | 0x80
11992 )
11993 } else if (codePoint < 0x110000) {
11994 if ((units -= 4) < 0) break
11995 bytes.push(
11996 codePoint >> 0x12 | 0xF0,
11997 codePoint >> 0xC & 0x3F | 0x80,
11998 codePoint >> 0x6 & 0x3F | 0x80,
11999 codePoint & 0x3F | 0x80
12000 )
12001 } else {
12002 throw new Error('Invalid code point')
12003 }
12004 }
12005
12006 return bytes
12007}
12008
12009function asciiToBytes (str) {
12010 var byteArray = []
12011 for (var i = 0; i < str.length; ++i) {
12012 // Node's code seems to be doing this and not & 0x7F..
12013 byteArray.push(str.charCodeAt(i) & 0xFF)
12014 }
12015 return byteArray
12016}
12017
12018function utf16leToBytes (str, units) {
12019 var c, hi, lo
12020 var byteArray = []
12021 for (var i = 0; i < str.length; ++i) {
12022 if ((units -= 2) < 0) break
12023
12024 c = str.charCodeAt(i)
12025 hi = c >> 8
12026 lo = c % 256
12027 byteArray.push(lo)
12028 byteArray.push(hi)
12029 }
12030
12031 return byteArray
12032}
12033
12034function base64ToBytes (str) {
12035 return base64.toByteArray(base64clean(str))
12036}
12037
12038function blitBuffer (src, dst, offset, length) {
12039 for (var i = 0; i < length; ++i) {
12040 if ((i + offset >= dst.length) || (i >= src.length)) break
12041 dst[i + offset] = src[i]
12042 }
12043 return i
12044}
12045
12046// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
12047// the `instanceof` check but they should be treated as of that type.
12048// See: https://github.com/feross/buffer/issues/166
12049function isInstance (obj, type) {
12050 return obj instanceof type ||
12051 (obj != null && obj.constructor != null && obj.constructor.name != null &&
12052 obj.constructor.name === type.name)
12053}
12054function numberIsNaN (obj) {
12055 // For IE11 support
12056 return obj !== obj // eslint-disable-line no-self-compare
12057}
12058
12059},{"base64-js":16,"ieee754":115}],50:[function(require,module,exports){
12060var Buffer = require('safe-buffer').Buffer
12061var Transform = require('stream').Transform
12062var StringDecoder = require('string_decoder').StringDecoder
12063var inherits = require('inherits')
12064
12065function CipherBase (hashMode) {
12066 Transform.call(this)
12067 this.hashMode = typeof hashMode === 'string'
12068 if (this.hashMode) {
12069 this[hashMode] = this._finalOrDigest
12070 } else {
12071 this.final = this._finalOrDigest
12072 }
12073 if (this._final) {
12074 this.__final = this._final
12075 this._final = null
12076 }
12077 this._decoder = null
12078 this._encoding = null
12079}
12080inherits(CipherBase, Transform)
12081
12082CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
12083 if (typeof data === 'string') {
12084 data = Buffer.from(data, inputEnc)
12085 }
12086
12087 var outData = this._update(data)
12088 if (this.hashMode) return this
12089
12090 if (outputEnc) {
12091 outData = this._toString(outData, outputEnc)
12092 }
12093
12094 return outData
12095}
12096
12097CipherBase.prototype.setAutoPadding = function () {}
12098CipherBase.prototype.getAuthTag = function () {
12099 throw new Error('trying to get auth tag in unsupported state')
12100}
12101
12102CipherBase.prototype.setAuthTag = function () {
12103 throw new Error('trying to set auth tag in unsupported state')
12104}
12105
12106CipherBase.prototype.setAAD = function () {
12107 throw new Error('trying to set aad in unsupported state')
12108}
12109
12110CipherBase.prototype._transform = function (data, _, next) {
12111 var err
12112 try {
12113 if (this.hashMode) {
12114 this._update(data)
12115 } else {
12116 this.push(this._update(data))
12117 }
12118 } catch (e) {
12119 err = e
12120 } finally {
12121 next(err)
12122 }
12123}
12124CipherBase.prototype._flush = function (done) {
12125 var err
12126 try {
12127 this.push(this.__final())
12128 } catch (e) {
12129 err = e
12130 }
12131
12132 done(err)
12133}
12134CipherBase.prototype._finalOrDigest = function (outputEnc) {
12135 var outData = this.__final() || Buffer.alloc(0)
12136 if (outputEnc) {
12137 outData = this._toString(outData, outputEnc, true)
12138 }
12139 return outData
12140}
12141
12142CipherBase.prototype._toString = function (value, enc, fin) {
12143 if (!this._decoder) {
12144 this._decoder = new StringDecoder(enc)
12145 this._encoding = enc
12146 }
12147
12148 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
12149
12150 var out = this._decoder.write(value)
12151 if (fin) {
12152 out += this._decoder.end()
12153 }
12154
12155 return out
12156}
12157
12158module.exports = CipherBase
12159
12160},{"inherits":116,"safe-buffer":393,"stream":432,"string_decoder":433}],51:[function(require,module,exports){
12161(function (Buffer){
12162// Copyright Joyent, Inc. and other Node contributors.
12163//
12164// Permission is hereby granted, free of charge, to any person obtaining a
12165// copy of this software and associated documentation files (the
12166// "Software"), to deal in the Software without restriction, including
12167// without limitation the rights to use, copy, modify, merge, publish,
12168// distribute, sublicense, and/or sell copies of the Software, and to permit
12169// persons to whom the Software is furnished to do so, subject to the
12170// following conditions:
12171//
12172// The above copyright notice and this permission notice shall be included
12173// in all copies or substantial portions of the Software.
12174//
12175// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12176// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12177// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12178// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12179// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12180// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12181// USE OR OTHER DEALINGS IN THE SOFTWARE.
12182
12183// NOTE: These type checking functions intentionally don't use `instanceof`
12184// because it is fragile and can be easily faked with `Object.create()`.
12185
12186function isArray(arg) {
12187 if (Array.isArray) {
12188 return Array.isArray(arg);
12189 }
12190 return objectToString(arg) === '[object Array]';
12191}
12192exports.isArray = isArray;
12193
12194function isBoolean(arg) {
12195 return typeof arg === 'boolean';
12196}
12197exports.isBoolean = isBoolean;
12198
12199function isNull(arg) {
12200 return arg === null;
12201}
12202exports.isNull = isNull;
12203
12204function isNullOrUndefined(arg) {
12205 return arg == null;
12206}
12207exports.isNullOrUndefined = isNullOrUndefined;
12208
12209function isNumber(arg) {
12210 return typeof arg === 'number';
12211}
12212exports.isNumber = isNumber;
12213
12214function isString(arg) {
12215 return typeof arg === 'string';
12216}
12217exports.isString = isString;
12218
12219function isSymbol(arg) {
12220 return typeof arg === 'symbol';
12221}
12222exports.isSymbol = isSymbol;
12223
12224function isUndefined(arg) {
12225 return arg === void 0;
12226}
12227exports.isUndefined = isUndefined;
12228
12229function isRegExp(re) {
12230 return objectToString(re) === '[object RegExp]';
12231}
12232exports.isRegExp = isRegExp;
12233
12234function isObject(arg) {
12235 return typeof arg === 'object' && arg !== null;
12236}
12237exports.isObject = isObject;
12238
12239function isDate(d) {
12240 return objectToString(d) === '[object Date]';
12241}
12242exports.isDate = isDate;
12243
12244function isError(e) {
12245 return (objectToString(e) === '[object Error]' || e instanceof Error);
12246}
12247exports.isError = isError;
12248
12249function isFunction(arg) {
12250 return typeof arg === 'function';
12251}
12252exports.isFunction = isFunction;
12253
12254function isPrimitive(arg) {
12255 return arg === null ||
12256 typeof arg === 'boolean' ||
12257 typeof arg === 'number' ||
12258 typeof arg === 'string' ||
12259 typeof arg === 'symbol' || // ES6 symbol
12260 typeof arg === 'undefined';
12261}
12262exports.isPrimitive = isPrimitive;
12263
12264exports.isBuffer = Buffer.isBuffer;
12265
12266function objectToString(o) {
12267 return Object.prototype.toString.call(o);
12268}
12269
12270}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
12271},{"../../is-buffer/index.js":117}],52:[function(require,module,exports){
12272'use strict';
12273
12274var _buffer = require('buffer');
12275
12276var _create_buffer = require('./create_buffer');
12277
12278var _create_buffer2 = _interopRequireDefault(_create_buffer);
12279
12280var _define_crc = require('./define_crc');
12281
12282var _define_crc2 = _interopRequireDefault(_define_crc);
12283
12284function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12285
12286module.exports = (0, _define_crc2.default)('crc1', function (buf, previous) {
12287 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12288
12289 var crc = ~~previous;
12290 var accum = 0;
12291
12292 for (var index = 0; index < buf.length; index++) {
12293 var byte = buf[index];
12294 accum += byte;
12295 }
12296
12297 crc += accum % 256;
12298 return crc % 256;
12299});
12300},{"./create_buffer":63,"./define_crc":64,"buffer":49}],53:[function(require,module,exports){
12301'use strict';
12302
12303var _buffer = require('buffer');
12304
12305var _create_buffer = require('./create_buffer');
12306
12307var _create_buffer2 = _interopRequireDefault(_create_buffer);
12308
12309var _define_crc = require('./define_crc');
12310
12311var _define_crc2 = _interopRequireDefault(_define_crc);
12312
12313function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12314
12315// Generated by `./pycrc.py --algorithm=table-driven --model=crc-16 --generate=c`
12316var TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
12317
12318if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12319
12320module.exports = (0, _define_crc2.default)('crc-16', function (buf, previous) {
12321 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12322
12323 var crc = ~~previous;
12324
12325 for (var index = 0; index < buf.length; index++) {
12326 var byte = buf[index];
12327 crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
12328 }
12329
12330 return crc;
12331});
12332},{"./create_buffer":63,"./define_crc":64,"buffer":49}],54:[function(require,module,exports){
12333'use strict';
12334
12335var _buffer = require('buffer');
12336
12337var _create_buffer = require('./create_buffer');
12338
12339var _create_buffer2 = _interopRequireDefault(_create_buffer);
12340
12341var _define_crc = require('./define_crc');
12342
12343var _define_crc2 = _interopRequireDefault(_define_crc);
12344
12345function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12346
12347// Generated by `./pycrc.py --algorithm=table-driven --model=ccitt --generate=c`
12348var TABLE = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0];
12349
12350if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12351
12352module.exports = (0, _define_crc2.default)('ccitt', function (buf, previous) {
12353 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12354
12355 var crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;
12356
12357 for (var index = 0; index < buf.length; index++) {
12358 var byte = buf[index];
12359 crc = (TABLE[(crc >> 8 ^ byte) & 0xff] ^ crc << 8) & 0xffff;
12360 }
12361
12362 return crc;
12363});
12364},{"./create_buffer":63,"./define_crc":64,"buffer":49}],55:[function(require,module,exports){
12365'use strict';
12366
12367var _buffer = require('buffer');
12368
12369var _create_buffer = require('./create_buffer');
12370
12371var _create_buffer2 = _interopRequireDefault(_create_buffer);
12372
12373var _define_crc = require('./define_crc');
12374
12375var _define_crc2 = _interopRequireDefault(_define_crc);
12376
12377function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12378
12379// Generated by `./pycrc.py --algorithm=table-driven --model=kermit --generate=c`
12380var TABLE = [0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78];
12381
12382if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12383
12384module.exports = (0, _define_crc2.default)('kermit', function (buf, previous) {
12385 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12386
12387 var crc = typeof previous !== 'undefined' ? ~~previous : 0x0000;
12388
12389 for (var index = 0; index < buf.length; index++) {
12390 var byte = buf[index];
12391 crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
12392 }
12393
12394 return crc;
12395});
12396},{"./create_buffer":63,"./define_crc":64,"buffer":49}],56:[function(require,module,exports){
12397'use strict';
12398
12399var _buffer = require('buffer');
12400
12401var _create_buffer = require('./create_buffer');
12402
12403var _create_buffer2 = _interopRequireDefault(_create_buffer);
12404
12405var _define_crc = require('./define_crc');
12406
12407var _define_crc2 = _interopRequireDefault(_define_crc);
12408
12409function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12410
12411// Generated by `./pycrc.py --algorithm=table-driven --model=crc-16-modbus --generate=c`
12412var TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
12413
12414if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12415
12416module.exports = (0, _define_crc2.default)('crc-16-modbus', function (buf, previous) {
12417 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12418
12419 var crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;
12420
12421 for (var index = 0; index < buf.length; index++) {
12422 var byte = buf[index];
12423 crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
12424 }
12425
12426 return crc;
12427});
12428},{"./create_buffer":63,"./define_crc":64,"buffer":49}],57:[function(require,module,exports){
12429'use strict';
12430
12431var _buffer = require('buffer');
12432
12433var _create_buffer = require('./create_buffer');
12434
12435var _create_buffer2 = _interopRequireDefault(_create_buffer);
12436
12437var _define_crc = require('./define_crc');
12438
12439var _define_crc2 = _interopRequireDefault(_define_crc);
12440
12441function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12442
12443module.exports = (0, _define_crc2.default)('xmodem', function (buf, previous) {
12444 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12445
12446 var crc = typeof previous !== 'undefined' ? ~~previous : 0x0;
12447
12448 for (var index = 0; index < buf.length; index++) {
12449 var byte = buf[index];
12450 var code = crc >>> 8 & 0xFF;
12451
12452 code ^= byte & 0xFF;
12453 code ^= code >>> 4;
12454 crc = crc << 8 & 0xFFFF;
12455 crc ^= code;
12456 code = code << 5 & 0xFFFF;
12457 crc ^= code;
12458 code = code << 7 & 0xFFFF;
12459 crc ^= code;
12460 }
12461
12462 return crc;
12463});
12464},{"./create_buffer":63,"./define_crc":64,"buffer":49}],58:[function(require,module,exports){
12465'use strict';
12466
12467var _buffer = require('buffer');
12468
12469var _create_buffer = require('./create_buffer');
12470
12471var _create_buffer2 = _interopRequireDefault(_create_buffer);
12472
12473var _define_crc = require('./define_crc');
12474
12475var _define_crc2 = _interopRequireDefault(_define_crc);
12476
12477function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12478
12479// Generated by `./pycrc.py --algorithm=table-drive --model=crc-24 --generate=c`
12480var TABLE = [0x000000, 0x864cfb, 0x8ad50d, 0x0c99f6, 0x93e6e1, 0x15aa1a, 0x1933ec, 0x9f7f17, 0xa18139, 0x27cdc2, 0x2b5434, 0xad18cf, 0x3267d8, 0xb42b23, 0xb8b2d5, 0x3efe2e, 0xc54e89, 0x430272, 0x4f9b84, 0xc9d77f, 0x56a868, 0xd0e493, 0xdc7d65, 0x5a319e, 0x64cfb0, 0xe2834b, 0xee1abd, 0x685646, 0xf72951, 0x7165aa, 0x7dfc5c, 0xfbb0a7, 0x0cd1e9, 0x8a9d12, 0x8604e4, 0x00481f, 0x9f3708, 0x197bf3, 0x15e205, 0x93aefe, 0xad50d0, 0x2b1c2b, 0x2785dd, 0xa1c926, 0x3eb631, 0xb8faca, 0xb4633c, 0x322fc7, 0xc99f60, 0x4fd39b, 0x434a6d, 0xc50696, 0x5a7981, 0xdc357a, 0xd0ac8c, 0x56e077, 0x681e59, 0xee52a2, 0xe2cb54, 0x6487af, 0xfbf8b8, 0x7db443, 0x712db5, 0xf7614e, 0x19a3d2, 0x9fef29, 0x9376df, 0x153a24, 0x8a4533, 0x0c09c8, 0x00903e, 0x86dcc5, 0xb822eb, 0x3e6e10, 0x32f7e6, 0xb4bb1d, 0x2bc40a, 0xad88f1, 0xa11107, 0x275dfc, 0xdced5b, 0x5aa1a0, 0x563856, 0xd074ad, 0x4f0bba, 0xc94741, 0xc5deb7, 0x43924c, 0x7d6c62, 0xfb2099, 0xf7b96f, 0x71f594, 0xee8a83, 0x68c678, 0x645f8e, 0xe21375, 0x15723b, 0x933ec0, 0x9fa736, 0x19ebcd, 0x8694da, 0x00d821, 0x0c41d7, 0x8a0d2c, 0xb4f302, 0x32bff9, 0x3e260f, 0xb86af4, 0x2715e3, 0xa15918, 0xadc0ee, 0x2b8c15, 0xd03cb2, 0x567049, 0x5ae9bf, 0xdca544, 0x43da53, 0xc596a8, 0xc90f5e, 0x4f43a5, 0x71bd8b, 0xf7f170, 0xfb6886, 0x7d247d, 0xe25b6a, 0x641791, 0x688e67, 0xeec29c, 0x3347a4, 0xb50b5f, 0xb992a9, 0x3fde52, 0xa0a145, 0x26edbe, 0x2a7448, 0xac38b3, 0x92c69d, 0x148a66, 0x181390, 0x9e5f6b, 0x01207c, 0x876c87, 0x8bf571, 0x0db98a, 0xf6092d, 0x7045d6, 0x7cdc20, 0xfa90db, 0x65efcc, 0xe3a337, 0xef3ac1, 0x69763a, 0x578814, 0xd1c4ef, 0xdd5d19, 0x5b11e2, 0xc46ef5, 0x42220e, 0x4ebbf8, 0xc8f703, 0x3f964d, 0xb9dab6, 0xb54340, 0x330fbb, 0xac70ac, 0x2a3c57, 0x26a5a1, 0xa0e95a, 0x9e1774, 0x185b8f, 0x14c279, 0x928e82, 0x0df195, 0x8bbd6e, 0x872498, 0x016863, 0xfad8c4, 0x7c943f, 0x700dc9, 0xf64132, 0x693e25, 0xef72de, 0xe3eb28, 0x65a7d3, 0x5b59fd, 0xdd1506, 0xd18cf0, 0x57c00b, 0xc8bf1c, 0x4ef3e7, 0x426a11, 0xc426ea, 0x2ae476, 0xaca88d, 0xa0317b, 0x267d80, 0xb90297, 0x3f4e6c, 0x33d79a, 0xb59b61, 0x8b654f, 0x0d29b4, 0x01b042, 0x87fcb9, 0x1883ae, 0x9ecf55, 0x9256a3, 0x141a58, 0xefaaff, 0x69e604, 0x657ff2, 0xe33309, 0x7c4c1e, 0xfa00e5, 0xf69913, 0x70d5e8, 0x4e2bc6, 0xc8673d, 0xc4fecb, 0x42b230, 0xddcd27, 0x5b81dc, 0x57182a, 0xd154d1, 0x26359f, 0xa07964, 0xace092, 0x2aac69, 0xb5d37e, 0x339f85, 0x3f0673, 0xb94a88, 0x87b4a6, 0x01f85d, 0x0d61ab, 0x8b2d50, 0x145247, 0x921ebc, 0x9e874a, 0x18cbb1, 0xe37b16, 0x6537ed, 0x69ae1b, 0xefe2e0, 0x709df7, 0xf6d10c, 0xfa48fa, 0x7c0401, 0x42fa2f, 0xc4b6d4, 0xc82f22, 0x4e63d9, 0xd11cce, 0x575035, 0x5bc9c3, 0xdd8538];
12481
12482if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12483
12484module.exports = (0, _define_crc2.default)('crc-24', function (buf, previous) {
12485 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12486
12487 var crc = typeof previous !== 'undefined' ? ~~previous : 0xb704ce;
12488
12489 for (var index = 0; index < buf.length; index++) {
12490 var byte = buf[index];
12491 crc = (TABLE[(crc >> 16 ^ byte) & 0xff] ^ crc << 8) & 0xffffff;
12492 }
12493
12494 return crc;
12495});
12496},{"./create_buffer":63,"./define_crc":64,"buffer":49}],59:[function(require,module,exports){
12497'use strict';
12498
12499var _buffer = require('buffer');
12500
12501var _create_buffer = require('./create_buffer');
12502
12503var _create_buffer2 = _interopRequireDefault(_create_buffer);
12504
12505var _define_crc = require('./define_crc');
12506
12507var _define_crc2 = _interopRequireDefault(_define_crc);
12508
12509function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12510
12511// Generated by `./pycrc.py --algorithm=table-driven --model=crc-32 --generate=c`
12512var TABLE = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d];
12513
12514if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12515
12516module.exports = (0, _define_crc2.default)('crc-32', function (buf, previous) {
12517 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12518
12519 var crc = previous === 0 ? 0 : ~~previous ^ -1;
12520
12521 for (var index = 0; index < buf.length; index++) {
12522 var byte = buf[index];
12523 crc = TABLE[(crc ^ byte) & 0xff] ^ crc >>> 8;
12524 }
12525
12526 return crc ^ -1;
12527});
12528},{"./create_buffer":63,"./define_crc":64,"buffer":49}],60:[function(require,module,exports){
12529'use strict';
12530
12531var _buffer = require('buffer');
12532
12533var _create_buffer = require('./create_buffer');
12534
12535var _create_buffer2 = _interopRequireDefault(_create_buffer);
12536
12537var _define_crc = require('./define_crc');
12538
12539var _define_crc2 = _interopRequireDefault(_define_crc);
12540
12541function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12542
12543// Generated by `./pycrc.py --algorithm=table-driven --model=crc-8 --generate=c`
12544var TABLE = [0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3];
12545
12546if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12547
12548module.exports = (0, _define_crc2.default)('crc-8', function (buf, previous) {
12549 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12550
12551 var crc = ~~previous;
12552
12553 for (var index = 0; index < buf.length; index++) {
12554 var byte = buf[index];
12555 crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
12556 }
12557
12558 return crc;
12559});
12560},{"./create_buffer":63,"./define_crc":64,"buffer":49}],61:[function(require,module,exports){
12561'use strict';
12562
12563var _buffer = require('buffer');
12564
12565var _create_buffer = require('./create_buffer');
12566
12567var _create_buffer2 = _interopRequireDefault(_create_buffer);
12568
12569var _define_crc = require('./define_crc');
12570
12571var _define_crc2 = _interopRequireDefault(_define_crc);
12572
12573function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12574
12575// Generated by `./pycrc.py --algorithm=table-driven --model=dallas-1-wire --generate=c`
12576var TABLE = [0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc, 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35];
12577
12578if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12579
12580module.exports = (0, _define_crc2.default)('dallas-1-wire', function (buf, previous) {
12581 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12582
12583 var crc = ~~previous;
12584
12585 for (var index = 0; index < buf.length; index++) {
12586 var byte = buf[index];
12587 crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
12588 }
12589
12590 return crc;
12591});
12592},{"./create_buffer":63,"./define_crc":64,"buffer":49}],62:[function(require,module,exports){
12593'use strict';
12594
12595var _buffer = require('buffer');
12596
12597var _create_buffer = require('./create_buffer');
12598
12599var _create_buffer2 = _interopRequireDefault(_create_buffer);
12600
12601var _define_crc = require('./define_crc');
12602
12603var _define_crc2 = _interopRequireDefault(_define_crc);
12604
12605function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12606
12607// Generated by `./pycrc.py --algorithm=table-driven --model=jam --generate=c`
12608var TABLE = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d];
12609
12610if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
12611
12612module.exports = (0, _define_crc2.default)('jam', function (buf) {
12613 var previous = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;
12614
12615 if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
12616
12617 var crc = previous === 0 ? 0 : ~~previous;
12618
12619 for (var index = 0; index < buf.length; index++) {
12620 var byte = buf[index];
12621 crc = TABLE[(crc ^ byte) & 0xff] ^ crc >>> 8;
12622 }
12623
12624 return crc;
12625});
12626},{"./create_buffer":63,"./define_crc":64,"buffer":49}],63:[function(require,module,exports){
12627'use strict';
12628
12629Object.defineProperty(exports, "__esModule", {
12630 value: true
12631});
12632
12633var _buffer = require('buffer');
12634
12635var createBuffer = _buffer.Buffer.from && _buffer.Buffer.alloc && _buffer.Buffer.allocUnsafe && _buffer.Buffer.allocUnsafeSlow ? _buffer.Buffer.from
12636
12637// support for Node < 5.10
12638: function (val) {
12639 return new _buffer.Buffer(val);
12640};
12641
12642exports.default = createBuffer;
12643},{"buffer":49}],64:[function(require,module,exports){
12644"use strict";
12645
12646Object.defineProperty(exports, "__esModule", {
12647 value: true
12648});
12649
12650exports.default = function (model, calc) {
12651 var fn = function fn(buf, previous) {
12652 return calc(buf, previous) >>> 0;
12653 };
12654 fn.signed = calc;
12655 fn.unsigned = fn;
12656 fn.model = model;
12657
12658 return fn;
12659};
12660},{}],65:[function(require,module,exports){
12661'use strict';
12662
12663module.exports = {
12664 crc1: require('./crc1'),
12665 crc8: require('./crc8'),
12666 crc81wire: require('./crc8_1wire'),
12667 crc16: require('./crc16'),
12668 crc16ccitt: require('./crc16_ccitt'),
12669 crc16modbus: require('./crc16_modbus'),
12670 crc16xmodem: require('./crc16_xmodem'),
12671 crc16kermit: require('./crc16_kermit'),
12672 crc24: require('./crc24'),
12673 crc32: require('./crc32'),
12674 crcjam: require('./crcjam')
12675};
12676},{"./crc1":52,"./crc16":53,"./crc16_ccitt":54,"./crc16_kermit":55,"./crc16_modbus":56,"./crc16_xmodem":57,"./crc24":58,"./crc32":59,"./crc8":60,"./crc8_1wire":61,"./crcjam":62}],66:[function(require,module,exports){
12677(function (Buffer){
12678var elliptic = require('elliptic')
12679var BN = require('bn.js')
12680
12681module.exports = function createECDH (curve) {
12682 return new ECDH(curve)
12683}
12684
12685var aliases = {
12686 secp256k1: {
12687 name: 'secp256k1',
12688 byteLength: 32
12689 },
12690 secp224r1: {
12691 name: 'p224',
12692 byteLength: 28
12693 },
12694 prime256v1: {
12695 name: 'p256',
12696 byteLength: 32
12697 },
12698 prime192v1: {
12699 name: 'p192',
12700 byteLength: 24
12701 },
12702 ed25519: {
12703 name: 'ed25519',
12704 byteLength: 32
12705 },
12706 secp384r1: {
12707 name: 'p384',
12708 byteLength: 48
12709 },
12710 secp521r1: {
12711 name: 'p521',
12712 byteLength: 66
12713 }
12714}
12715
12716aliases.p224 = aliases.secp224r1
12717aliases.p256 = aliases.secp256r1 = aliases.prime256v1
12718aliases.p192 = aliases.secp192r1 = aliases.prime192v1
12719aliases.p384 = aliases.secp384r1
12720aliases.p521 = aliases.secp521r1
12721
12722function ECDH (curve) {
12723 this.curveType = aliases[curve]
12724 if (!this.curveType) {
12725 this.curveType = {
12726 name: curve
12727 }
12728 }
12729 this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
12730 this.keys = void 0
12731}
12732
12733ECDH.prototype.generateKeys = function (enc, format) {
12734 this.keys = this.curve.genKeyPair()
12735 return this.getPublicKey(enc, format)
12736}
12737
12738ECDH.prototype.computeSecret = function (other, inenc, enc) {
12739 inenc = inenc || 'utf8'
12740 if (!Buffer.isBuffer(other)) {
12741 other = new Buffer(other, inenc)
12742 }
12743 var otherPub = this.curve.keyFromPublic(other).getPublic()
12744 var out = otherPub.mul(this.keys.getPrivate()).getX()
12745 return formatReturnValue(out, enc, this.curveType.byteLength)
12746}
12747
12748ECDH.prototype.getPublicKey = function (enc, format) {
12749 var key = this.keys.getPublic(format === 'compressed', true)
12750 if (format === 'hybrid') {
12751 if (key[key.length - 1] % 2) {
12752 key[0] = 7
12753 } else {
12754 key[0] = 6
12755 }
12756 }
12757 return formatReturnValue(key, enc)
12758}
12759
12760ECDH.prototype.getPrivateKey = function (enc) {
12761 return formatReturnValue(this.keys.getPrivate(), enc)
12762}
12763
12764ECDH.prototype.setPublicKey = function (pub, enc) {
12765 enc = enc || 'utf8'
12766 if (!Buffer.isBuffer(pub)) {
12767 pub = new Buffer(pub, enc)
12768 }
12769 this.keys._importPublic(pub)
12770 return this
12771}
12772
12773ECDH.prototype.setPrivateKey = function (priv, enc) {
12774 enc = enc || 'utf8'
12775 if (!Buffer.isBuffer(priv)) {
12776 priv = new Buffer(priv, enc)
12777 }
12778
12779 var _priv = new BN(priv)
12780 _priv = _priv.toString(16)
12781 this.keys = this.curve.genKeyPair()
12782 this.keys._importPrivate(_priv)
12783 return this
12784}
12785
12786function formatReturnValue (bn, enc, len) {
12787 if (!Array.isArray(bn)) {
12788 bn = bn.toArray()
12789 }
12790 var buf = new Buffer(bn)
12791 if (len && buf.length < len) {
12792 var zeros = new Buffer(len - buf.length)
12793 zeros.fill(0)
12794 buf = Buffer.concat([zeros, buf])
12795 }
12796 if (!enc) {
12797 return buf
12798 } else {
12799 return buf.toString(enc)
12800 }
12801}
12802
12803}).call(this,require("buffer").Buffer)
12804},{"bn.js":18,"buffer":49,"elliptic":83}],67:[function(require,module,exports){
12805'use strict'
12806var inherits = require('inherits')
12807var MD5 = require('md5.js')
12808var RIPEMD160 = require('ripemd160')
12809var sha = require('sha.js')
12810var Base = require('cipher-base')
12811
12812function Hash (hash) {
12813 Base.call(this, 'digest')
12814
12815 this._hash = hash
12816}
12817
12818inherits(Hash, Base)
12819
12820Hash.prototype._update = function (data) {
12821 this._hash.update(data)
12822}
12823
12824Hash.prototype._final = function () {
12825 return this._hash.digest()
12826}
12827
12828module.exports = function createHash (alg) {
12829 alg = alg.toLowerCase()
12830 if (alg === 'md5') return new MD5()
12831 if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()
12832
12833 return new Hash(sha(alg))
12834}
12835
12836},{"cipher-base":50,"inherits":116,"md5.js":354,"ripemd160":392,"sha.js":395}],68:[function(require,module,exports){
12837var MD5 = require('md5.js')
12838
12839module.exports = function (buffer) {
12840 return new MD5().update(buffer).digest()
12841}
12842
12843},{"md5.js":354}],69:[function(require,module,exports){
12844'use strict'
12845var inherits = require('inherits')
12846var Legacy = require('./legacy')
12847var Base = require('cipher-base')
12848var Buffer = require('safe-buffer').Buffer
12849var md5 = require('create-hash/md5')
12850var RIPEMD160 = require('ripemd160')
12851
12852var sha = require('sha.js')
12853
12854var ZEROS = Buffer.alloc(128)
12855
12856function Hmac (alg, key) {
12857 Base.call(this, 'digest')
12858 if (typeof key === 'string') {
12859 key = Buffer.from(key)
12860 }
12861
12862 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
12863
12864 this._alg = alg
12865 this._key = key
12866 if (key.length > blocksize) {
12867 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12868 key = hash.update(key).digest()
12869 } else if (key.length < blocksize) {
12870 key = Buffer.concat([key, ZEROS], blocksize)
12871 }
12872
12873 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12874 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12875
12876 for (var i = 0; i < blocksize; i++) {
12877 ipad[i] = key[i] ^ 0x36
12878 opad[i] = key[i] ^ 0x5C
12879 }
12880 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12881 this._hash.update(ipad)
12882}
12883
12884inherits(Hmac, Base)
12885
12886Hmac.prototype._update = function (data) {
12887 this._hash.update(data)
12888}
12889
12890Hmac.prototype._final = function () {
12891 var h = this._hash.digest()
12892 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
12893 return hash.update(this._opad).update(h).digest()
12894}
12895
12896module.exports = function createHmac (alg, key) {
12897 alg = alg.toLowerCase()
12898 if (alg === 'rmd160' || alg === 'ripemd160') {
12899 return new Hmac('rmd160', key)
12900 }
12901 if (alg === 'md5') {
12902 return new Legacy(md5, key)
12903 }
12904 return new Hmac(alg, key)
12905}
12906
12907},{"./legacy":70,"cipher-base":50,"create-hash/md5":68,"inherits":116,"ripemd160":392,"safe-buffer":393,"sha.js":395}],70:[function(require,module,exports){
12908'use strict'
12909var inherits = require('inherits')
12910var Buffer = require('safe-buffer').Buffer
12911
12912var Base = require('cipher-base')
12913
12914var ZEROS = Buffer.alloc(128)
12915var blocksize = 64
12916
12917function Hmac (alg, key) {
12918 Base.call(this, 'digest')
12919 if (typeof key === 'string') {
12920 key = Buffer.from(key)
12921 }
12922
12923 this._alg = alg
12924 this._key = key
12925
12926 if (key.length > blocksize) {
12927 key = alg(key)
12928 } else if (key.length < blocksize) {
12929 key = Buffer.concat([key, ZEROS], blocksize)
12930 }
12931
12932 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12933 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12934
12935 for (var i = 0; i < blocksize; i++) {
12936 ipad[i] = key[i] ^ 0x36
12937 opad[i] = key[i] ^ 0x5C
12938 }
12939
12940 this._hash = [ipad]
12941}
12942
12943inherits(Hmac, Base)
12944
12945Hmac.prototype._update = function (data) {
12946 this._hash.push(data)
12947}
12948
12949Hmac.prototype._final = function () {
12950 var h = this._alg(Buffer.concat(this._hash))
12951 return this._alg(Buffer.concat([this._opad, h]))
12952}
12953module.exports = Hmac
12954
12955},{"cipher-base":50,"inherits":116,"safe-buffer":393}],71:[function(require,module,exports){
12956'use strict'
12957
12958exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
12959exports.createHash = exports.Hash = require('create-hash')
12960exports.createHmac = exports.Hmac = require('create-hmac')
12961
12962var algos = require('browserify-sign/algos')
12963var algoKeys = Object.keys(algos)
12964var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
12965exports.getHashes = function () {
12966 return hashes
12967}
12968
12969var p = require('pbkdf2')
12970exports.pbkdf2 = p.pbkdf2
12971exports.pbkdf2Sync = p.pbkdf2Sync
12972
12973var aes = require('browserify-cipher')
12974
12975exports.Cipher = aes.Cipher
12976exports.createCipher = aes.createCipher
12977exports.Cipheriv = aes.Cipheriv
12978exports.createCipheriv = aes.createCipheriv
12979exports.Decipher = aes.Decipher
12980exports.createDecipher = aes.createDecipher
12981exports.Decipheriv = aes.Decipheriv
12982exports.createDecipheriv = aes.createDecipheriv
12983exports.getCiphers = aes.getCiphers
12984exports.listCiphers = aes.listCiphers
12985
12986var dh = require('diffie-hellman')
12987
12988exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
12989exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
12990exports.getDiffieHellman = dh.getDiffieHellman
12991exports.createDiffieHellman = dh.createDiffieHellman
12992exports.DiffieHellman = dh.DiffieHellman
12993
12994var sign = require('browserify-sign')
12995
12996exports.createSign = sign.createSign
12997exports.Sign = sign.Sign
12998exports.createVerify = sign.createVerify
12999exports.Verify = sign.Verify
13000
13001exports.createECDH = require('create-ecdh')
13002
13003var publicEncrypt = require('public-encrypt')
13004
13005exports.publicEncrypt = publicEncrypt.publicEncrypt
13006exports.privateEncrypt = publicEncrypt.privateEncrypt
13007exports.publicDecrypt = publicEncrypt.publicDecrypt
13008exports.privateDecrypt = publicEncrypt.privateDecrypt
13009
13010// the least I can do is make error messages for the rest of the node.js/crypto api.
13011// ;[
13012// 'createCredentials'
13013// ].forEach(function (name) {
13014// exports[name] = function () {
13015// throw new Error([
13016// 'sorry, ' + name + ' is not implemented yet',
13017// 'we accept pull requests',
13018// 'https://github.com/crypto-browserify/crypto-browserify'
13019// ].join('\n'))
13020// }
13021// })
13022
13023var rf = require('randomfill')
13024
13025exports.randomFill = rf.randomFill
13026exports.randomFillSync = rf.randomFillSync
13027
13028exports.createCredentials = function () {
13029 throw new Error([
13030 'sorry, createCredentials is not implemented yet',
13031 'we accept pull requests',
13032 'https://github.com/crypto-browserify/crypto-browserify'
13033 ].join('\n'))
13034}
13035
13036exports.constants = {
13037 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
13038 'DH_CHECK_P_NOT_PRIME': 1,
13039 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
13040 'DH_NOT_SUITABLE_GENERATOR': 8,
13041 'NPN_ENABLED': 1,
13042 'ALPN_ENABLED': 1,
13043 'RSA_PKCS1_PADDING': 1,
13044 'RSA_SSLV23_PADDING': 2,
13045 'RSA_NO_PADDING': 3,
13046 'RSA_PKCS1_OAEP_PADDING': 4,
13047 'RSA_X931_PADDING': 5,
13048 'RSA_PKCS1_PSS_PADDING': 6,
13049 'POINT_CONVERSION_COMPRESSED': 2,
13050 'POINT_CONVERSION_UNCOMPRESSED': 4,
13051 'POINT_CONVERSION_HYBRID': 6
13052}
13053
13054},{"browserify-cipher":38,"browserify-sign":45,"browserify-sign/algos":42,"create-ecdh":66,"create-hash":67,"create-hmac":69,"diffie-hellman":79,"pbkdf2":363,"public-encrypt":370,"randombytes":376,"randomfill":377}],72:[function(require,module,exports){
13055(function (Buffer){
13056var Cursor = function(buffer)
13057{
13058 if (!(this instanceof Cursor))
13059 {
13060 return new Cursor(buffer);
13061 }
13062
13063 if (!(buffer instanceof Buffer))
13064 {
13065 buffer = new Buffer(buffer);
13066 }
13067
13068 this._setBuffer(buffer);
13069 this.rewind();
13070};
13071
13072Cursor.prototype._setBuffer = function(buffer)
13073{
13074 this._buffer = buffer;
13075 this.length = buffer.length;
13076};
13077
13078Cursor.prototype.buffer = function()
13079{
13080 return this._buffer;
13081};
13082
13083Cursor.prototype.tap = function(cb)
13084{
13085 cb(this);
13086 return this;
13087};
13088
13089Cursor.prototype.clone = function(newIndex)
13090{
13091 var c = new this.constructor(this.buffer());
13092 c.seek(arguments.length === 0 ? this.tell() : newIndex);
13093
13094 return c;
13095};
13096
13097Cursor.prototype.tell = function()
13098{
13099 return this._index;
13100};
13101
13102Cursor.prototype.seek = function(op, index)
13103{
13104 if (arguments.length == 1)
13105 {
13106 index = op;
13107 op = '=';
13108 }
13109
13110 if (op == '+')
13111 {
13112 this._index += index;
13113 }
13114 else if (op == '-')
13115 {
13116 this._index -= index;
13117 }
13118 else
13119 {
13120 this._index = index;
13121 }
13122
13123 return this;
13124};
13125
13126Cursor.prototype.rewind = function()
13127{
13128 return this.seek(0);
13129};
13130
13131Cursor.prototype.eof = function()
13132{
13133 return this.tell() == this.buffer().length;
13134};
13135
13136Cursor.prototype.write = function(string, length, encoding)
13137{
13138 return this.seek('+', this.buffer().write(string, this.tell(), length, encoding));
13139};
13140
13141Cursor.prototype.fill = function(value, length)
13142{
13143 if (arguments.length == 1)
13144 {
13145 length = this.buffer().length - this.tell();
13146 }
13147
13148 this.buffer().fill(value, this.tell(), this.tell() + length);
13149 this.seek('+', length);
13150
13151 return this;
13152};
13153
13154Cursor.prototype.slice = function(length)
13155{
13156 if (arguments.length === 0)
13157 {
13158 length = this.length - this.tell();
13159 }
13160
13161 var c = new this.constructor(this.buffer().slice(this.tell(), this.tell() + length));
13162 this.seek('+', length);
13163
13164 return c;
13165};
13166
13167Cursor.prototype.copyFrom = function(source)
13168{
13169 var buf = source instanceof Buffer ? source: source.buffer();
13170 buf.copy(this.buffer(), this.tell(), 0, buf.length);
13171 this.seek('+', buf.length);
13172
13173 return this;
13174};
13175
13176Cursor.prototype.concat = function(list)
13177{
13178 for (var i in list)
13179 {
13180 if (list[i] instanceof Cursor)
13181 {
13182 list[i] = list[i].buffer();
13183 }
13184 }
13185
13186 list.unshift(this.buffer());
13187
13188 var b = Buffer.concat(list);
13189 this._setBuffer(b);
13190
13191 return this;
13192};
13193
13194Cursor.prototype.toString = function(encoding, length)
13195{
13196 if (arguments.length === 0)
13197 {
13198 encoding = 'utf8';
13199 length = this.buffer().length - this.tell();
13200 }
13201 else if (arguments.length === 1)
13202 {
13203 length = this.buffer().length - this.tell();
13204 }
13205
13206 var val = this.buffer().toString(encoding, this.tell(), this.tell() + length);
13207 this.seek('+', length);
13208
13209 return val;
13210};
13211
13212[
13213 [1, ['readInt8', 'readUInt8']],
13214 [2, ['readInt16BE', 'readInt16LE', 'readUInt16BE', 'readUInt16LE']],
13215 [4, ['readInt32BE', 'readInt32LE', 'readUInt32BE', 'readUInt32LE', 'readFloatBE', 'readFloatLE']],
13216 [8, ['readDoubleBE', 'readDoubleLE']]
13217].forEach(function(arr)
13218{
13219 arr[1].forEach(function(method)
13220 {
13221 Cursor.prototype[method] = function()
13222 {
13223 var val = this.buffer()[method](this.tell());
13224 this.seek('+', arr[0]);
13225
13226 return val;
13227 };
13228 });
13229});
13230
13231[
13232 [1, ['writeInt8', 'writeUInt8']],
13233 [2, ['writeInt16BE', 'writeInt16LE', 'writeUInt16BE', 'writeUInt16LE']],
13234 [4, ['writeInt32BE', 'writeInt32LE', 'writeUInt32BE', 'writeUInt32LE', 'writeFloatBE', 'writeFloatLE']],
13235 [8, ['writeDoubleBE', 'writeDoubleLE']]
13236].forEach(function(arr)
13237{
13238 arr[1].forEach(function(method)
13239 {
13240 Cursor.prototype[method] = function(val)
13241 {
13242 val = this.buffer()[method](val, this.tell());
13243 this.seek('+', arr[0]);
13244
13245 return this;
13246 };
13247 });
13248});
13249
13250//basic extend functionality to facilitate
13251//writing your own cursor while still providing
13252//access to low level r/w functionality
13253Cursor.extend = function(C, proto)
13254{
13255 var parent = this;
13256
13257 if (arguments.length === 1)
13258 {
13259 proto = C;
13260 C = null;
13261 }
13262
13263 proto = proto || {};
13264
13265 C = C || function ctor(buffer)
13266 {
13267 if (!(this instanceof C))
13268 {
13269 return new C(buffer);
13270 }
13271
13272 parent.call(this, buffer);
13273 };
13274
13275 require('util').inherits(C, parent);
13276
13277 C.extend = parent.extend;
13278 C.define = parent.define;
13279
13280 for (var i in proto)
13281 {
13282 C.define(i, proto[i]);
13283 }
13284
13285 return C;
13286};
13287
13288Cursor.define = function(name, fn)
13289{
13290 var proto = this.prototype[name];
13291
13292 this.prototype[name] = proto && function()
13293 {
13294 this.__super = proto;
13295 return fn.apply(this, arguments);
13296 } || fn;
13297};
13298
13299module.exports = Cursor;
13300
13301}).call(this,require("buffer").Buffer)
13302},{"buffer":49,"util":438}],73:[function(require,module,exports){
13303'use strict';
13304
13305exports.utils = require('./des/utils');
13306exports.Cipher = require('./des/cipher');
13307exports.DES = require('./des/des');
13308exports.CBC = require('./des/cbc');
13309exports.EDE = require('./des/ede');
13310
13311},{"./des/cbc":74,"./des/cipher":75,"./des/des":76,"./des/ede":77,"./des/utils":78}],74:[function(require,module,exports){
13312'use strict';
13313
13314var assert = require('minimalistic-assert');
13315var inherits = require('inherits');
13316
13317var proto = {};
13318
13319function CBCState(iv) {
13320 assert.equal(iv.length, 8, 'Invalid IV length');
13321
13322 this.iv = new Array(8);
13323 for (var i = 0; i < this.iv.length; i++)
13324 this.iv[i] = iv[i];
13325}
13326
13327function instantiate(Base) {
13328 function CBC(options) {
13329 Base.call(this, options);
13330 this._cbcInit();
13331 }
13332 inherits(CBC, Base);
13333
13334 var keys = Object.keys(proto);
13335 for (var i = 0; i < keys.length; i++) {
13336 var key = keys[i];
13337 CBC.prototype[key] = proto[key];
13338 }
13339
13340 CBC.create = function create(options) {
13341 return new CBC(options);
13342 };
13343
13344 return CBC;
13345}
13346
13347exports.instantiate = instantiate;
13348
13349proto._cbcInit = function _cbcInit() {
13350 var state = new CBCState(this.options.iv);
13351 this._cbcState = state;
13352};
13353
13354proto._update = function _update(inp, inOff, out, outOff) {
13355 var state = this._cbcState;
13356 var superProto = this.constructor.super_.prototype;
13357
13358 var iv = state.iv;
13359 if (this.type === 'encrypt') {
13360 for (var i = 0; i < this.blockSize; i++)
13361 iv[i] ^= inp[inOff + i];
13362
13363 superProto._update.call(this, iv, 0, out, outOff);
13364
13365 for (var i = 0; i < this.blockSize; i++)
13366 iv[i] = out[outOff + i];
13367 } else {
13368 superProto._update.call(this, inp, inOff, out, outOff);
13369
13370 for (var i = 0; i < this.blockSize; i++)
13371 out[outOff + i] ^= iv[i];
13372
13373 for (var i = 0; i < this.blockSize; i++)
13374 iv[i] = inp[inOff + i];
13375 }
13376};
13377
13378},{"inherits":116,"minimalistic-assert":356}],75:[function(require,module,exports){
13379'use strict';
13380
13381var assert = require('minimalistic-assert');
13382
13383function Cipher(options) {
13384 this.options = options;
13385
13386 this.type = this.options.type;
13387 this.blockSize = 8;
13388 this._init();
13389
13390 this.buffer = new Array(this.blockSize);
13391 this.bufferOff = 0;
13392}
13393module.exports = Cipher;
13394
13395Cipher.prototype._init = function _init() {
13396 // Might be overrided
13397};
13398
13399Cipher.prototype.update = function update(data) {
13400 if (data.length === 0)
13401 return [];
13402
13403 if (this.type === 'decrypt')
13404 return this._updateDecrypt(data);
13405 else
13406 return this._updateEncrypt(data);
13407};
13408
13409Cipher.prototype._buffer = function _buffer(data, off) {
13410 // Append data to buffer
13411 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
13412 for (var i = 0; i < min; i++)
13413 this.buffer[this.bufferOff + i] = data[off + i];
13414 this.bufferOff += min;
13415
13416 // Shift next
13417 return min;
13418};
13419
13420Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
13421 this._update(this.buffer, 0, out, off);
13422 this.bufferOff = 0;
13423 return this.blockSize;
13424};
13425
13426Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
13427 var inputOff = 0;
13428 var outputOff = 0;
13429
13430 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
13431 var out = new Array(count * this.blockSize);
13432
13433 if (this.bufferOff !== 0) {
13434 inputOff += this._buffer(data, inputOff);
13435
13436 if (this.bufferOff === this.buffer.length)
13437 outputOff += this._flushBuffer(out, outputOff);
13438 }
13439
13440 // Write blocks
13441 var max = data.length - ((data.length - inputOff) % this.blockSize);
13442 for (; inputOff < max; inputOff += this.blockSize) {
13443 this._update(data, inputOff, out, outputOff);
13444 outputOff += this.blockSize;
13445 }
13446
13447 // Queue rest
13448 for (; inputOff < data.length; inputOff++, this.bufferOff++)
13449 this.buffer[this.bufferOff] = data[inputOff];
13450
13451 return out;
13452};
13453
13454Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
13455 var inputOff = 0;
13456 var outputOff = 0;
13457
13458 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
13459 var out = new Array(count * this.blockSize);
13460
13461 // TODO(indutny): optimize it, this is far from optimal
13462 for (; count > 0; count--) {
13463 inputOff += this._buffer(data, inputOff);
13464 outputOff += this._flushBuffer(out, outputOff);
13465 }
13466
13467 // Buffer rest of the input
13468 inputOff += this._buffer(data, inputOff);
13469
13470 return out;
13471};
13472
13473Cipher.prototype.final = function final(buffer) {
13474 var first;
13475 if (buffer)
13476 first = this.update(buffer);
13477
13478 var last;
13479 if (this.type === 'encrypt')
13480 last = this._finalEncrypt();
13481 else
13482 last = this._finalDecrypt();
13483
13484 if (first)
13485 return first.concat(last);
13486 else
13487 return last;
13488};
13489
13490Cipher.prototype._pad = function _pad(buffer, off) {
13491 if (off === 0)
13492 return false;
13493
13494 while (off < buffer.length)
13495 buffer[off++] = 0;
13496
13497 return true;
13498};
13499
13500Cipher.prototype._finalEncrypt = function _finalEncrypt() {
13501 if (!this._pad(this.buffer, this.bufferOff))
13502 return [];
13503
13504 var out = new Array(this.blockSize);
13505 this._update(this.buffer, 0, out, 0);
13506 return out;
13507};
13508
13509Cipher.prototype._unpad = function _unpad(buffer) {
13510 return buffer;
13511};
13512
13513Cipher.prototype._finalDecrypt = function _finalDecrypt() {
13514 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
13515 var out = new Array(this.blockSize);
13516 this._flushBuffer(out, 0);
13517
13518 return this._unpad(out);
13519};
13520
13521},{"minimalistic-assert":356}],76:[function(require,module,exports){
13522'use strict';
13523
13524var assert = require('minimalistic-assert');
13525var inherits = require('inherits');
13526
13527var des = require('../des');
13528var utils = des.utils;
13529var Cipher = des.Cipher;
13530
13531function DESState() {
13532 this.tmp = new Array(2);
13533 this.keys = null;
13534}
13535
13536function DES(options) {
13537 Cipher.call(this, options);
13538
13539 var state = new DESState();
13540 this._desState = state;
13541
13542 this.deriveKeys(state, options.key);
13543}
13544inherits(DES, Cipher);
13545module.exports = DES;
13546
13547DES.create = function create(options) {
13548 return new DES(options);
13549};
13550
13551var shiftTable = [
13552 1, 1, 2, 2, 2, 2, 2, 2,
13553 1, 2, 2, 2, 2, 2, 2, 1
13554];
13555
13556DES.prototype.deriveKeys = function deriveKeys(state, key) {
13557 state.keys = new Array(16 * 2);
13558
13559 assert.equal(key.length, this.blockSize, 'Invalid key length');
13560
13561 var kL = utils.readUInt32BE(key, 0);
13562 var kR = utils.readUInt32BE(key, 4);
13563
13564 utils.pc1(kL, kR, state.tmp, 0);
13565 kL = state.tmp[0];
13566 kR = state.tmp[1];
13567 for (var i = 0; i < state.keys.length; i += 2) {
13568 var shift = shiftTable[i >>> 1];
13569 kL = utils.r28shl(kL, shift);
13570 kR = utils.r28shl(kR, shift);
13571 utils.pc2(kL, kR, state.keys, i);
13572 }
13573};
13574
13575DES.prototype._update = function _update(inp, inOff, out, outOff) {
13576 var state = this._desState;
13577
13578 var l = utils.readUInt32BE(inp, inOff);
13579 var r = utils.readUInt32BE(inp, inOff + 4);
13580
13581 // Initial Permutation
13582 utils.ip(l, r, state.tmp, 0);
13583 l = state.tmp[0];
13584 r = state.tmp[1];
13585
13586 if (this.type === 'encrypt')
13587 this._encrypt(state, l, r, state.tmp, 0);
13588 else
13589 this._decrypt(state, l, r, state.tmp, 0);
13590
13591 l = state.tmp[0];
13592 r = state.tmp[1];
13593
13594 utils.writeUInt32BE(out, l, outOff);
13595 utils.writeUInt32BE(out, r, outOff + 4);
13596};
13597
13598DES.prototype._pad = function _pad(buffer, off) {
13599 var value = buffer.length - off;
13600 for (var i = off; i < buffer.length; i++)
13601 buffer[i] = value;
13602
13603 return true;
13604};
13605
13606DES.prototype._unpad = function _unpad(buffer) {
13607 var pad = buffer[buffer.length - 1];
13608 for (var i = buffer.length - pad; i < buffer.length; i++)
13609 assert.equal(buffer[i], pad);
13610
13611 return buffer.slice(0, buffer.length - pad);
13612};
13613
13614DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
13615 var l = lStart;
13616 var r = rStart;
13617
13618 // Apply f() x16 times
13619 for (var i = 0; i < state.keys.length; i += 2) {
13620 var keyL = state.keys[i];
13621 var keyR = state.keys[i + 1];
13622
13623 // f(r, k)
13624 utils.expand(r, state.tmp, 0);
13625
13626 keyL ^= state.tmp[0];
13627 keyR ^= state.tmp[1];
13628 var s = utils.substitute(keyL, keyR);
13629 var f = utils.permute(s);
13630
13631 var t = r;
13632 r = (l ^ f) >>> 0;
13633 l = t;
13634 }
13635
13636 // Reverse Initial Permutation
13637 utils.rip(r, l, out, off);
13638};
13639
13640DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
13641 var l = rStart;
13642 var r = lStart;
13643
13644 // Apply f() x16 times
13645 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
13646 var keyL = state.keys[i];
13647 var keyR = state.keys[i + 1];
13648
13649 // f(r, k)
13650 utils.expand(l, state.tmp, 0);
13651
13652 keyL ^= state.tmp[0];
13653 keyR ^= state.tmp[1];
13654 var s = utils.substitute(keyL, keyR);
13655 var f = utils.permute(s);
13656
13657 var t = l;
13658 l = (r ^ f) >>> 0;
13659 r = t;
13660 }
13661
13662 // Reverse Initial Permutation
13663 utils.rip(l, r, out, off);
13664};
13665
13666},{"../des":73,"inherits":116,"minimalistic-assert":356}],77:[function(require,module,exports){
13667'use strict';
13668
13669var assert = require('minimalistic-assert');
13670var inherits = require('inherits');
13671
13672var des = require('../des');
13673var Cipher = des.Cipher;
13674var DES = des.DES;
13675
13676function EDEState(type, key) {
13677 assert.equal(key.length, 24, 'Invalid key length');
13678
13679 var k1 = key.slice(0, 8);
13680 var k2 = key.slice(8, 16);
13681 var k3 = key.slice(16, 24);
13682
13683 if (type === 'encrypt') {
13684 this.ciphers = [
13685 DES.create({ type: 'encrypt', key: k1 }),
13686 DES.create({ type: 'decrypt', key: k2 }),
13687 DES.create({ type: 'encrypt', key: k3 })
13688 ];
13689 } else {
13690 this.ciphers = [
13691 DES.create({ type: 'decrypt', key: k3 }),
13692 DES.create({ type: 'encrypt', key: k2 }),
13693 DES.create({ type: 'decrypt', key: k1 })
13694 ];
13695 }
13696}
13697
13698function EDE(options) {
13699 Cipher.call(this, options);
13700
13701 var state = new EDEState(this.type, this.options.key);
13702 this._edeState = state;
13703}
13704inherits(EDE, Cipher);
13705
13706module.exports = EDE;
13707
13708EDE.create = function create(options) {
13709 return new EDE(options);
13710};
13711
13712EDE.prototype._update = function _update(inp, inOff, out, outOff) {
13713 var state = this._edeState;
13714
13715 state.ciphers[0]._update(inp, inOff, out, outOff);
13716 state.ciphers[1]._update(out, outOff, out, outOff);
13717 state.ciphers[2]._update(out, outOff, out, outOff);
13718};
13719
13720EDE.prototype._pad = DES.prototype._pad;
13721EDE.prototype._unpad = DES.prototype._unpad;
13722
13723},{"../des":73,"inherits":116,"minimalistic-assert":356}],78:[function(require,module,exports){
13724'use strict';
13725
13726exports.readUInt32BE = function readUInt32BE(bytes, off) {
13727 var res = (bytes[0 + off] << 24) |
13728 (bytes[1 + off] << 16) |
13729 (bytes[2 + off] << 8) |
13730 bytes[3 + off];
13731 return res >>> 0;
13732};
13733
13734exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
13735 bytes[0 + off] = value >>> 24;
13736 bytes[1 + off] = (value >>> 16) & 0xff;
13737 bytes[2 + off] = (value >>> 8) & 0xff;
13738 bytes[3 + off] = value & 0xff;
13739};
13740
13741exports.ip = function ip(inL, inR, out, off) {
13742 var outL = 0;
13743 var outR = 0;
13744
13745 for (var i = 6; i >= 0; i -= 2) {
13746 for (var j = 0; j <= 24; j += 8) {
13747 outL <<= 1;
13748 outL |= (inR >>> (j + i)) & 1;
13749 }
13750 for (var j = 0; j <= 24; j += 8) {
13751 outL <<= 1;
13752 outL |= (inL >>> (j + i)) & 1;
13753 }
13754 }
13755
13756 for (var i = 6; i >= 0; i -= 2) {
13757 for (var j = 1; j <= 25; j += 8) {
13758 outR <<= 1;
13759 outR |= (inR >>> (j + i)) & 1;
13760 }
13761 for (var j = 1; j <= 25; j += 8) {
13762 outR <<= 1;
13763 outR |= (inL >>> (j + i)) & 1;
13764 }
13765 }
13766
13767 out[off + 0] = outL >>> 0;
13768 out[off + 1] = outR >>> 0;
13769};
13770
13771exports.rip = function rip(inL, inR, out, off) {
13772 var outL = 0;
13773 var outR = 0;
13774
13775 for (var i = 0; i < 4; i++) {
13776 for (var j = 24; j >= 0; j -= 8) {
13777 outL <<= 1;
13778 outL |= (inR >>> (j + i)) & 1;
13779 outL <<= 1;
13780 outL |= (inL >>> (j + i)) & 1;
13781 }
13782 }
13783 for (var i = 4; i < 8; i++) {
13784 for (var j = 24; j >= 0; j -= 8) {
13785 outR <<= 1;
13786 outR |= (inR >>> (j + i)) & 1;
13787 outR <<= 1;
13788 outR |= (inL >>> (j + i)) & 1;
13789 }
13790 }
13791
13792 out[off + 0] = outL >>> 0;
13793 out[off + 1] = outR >>> 0;
13794};
13795
13796exports.pc1 = function pc1(inL, inR, out, off) {
13797 var outL = 0;
13798 var outR = 0;
13799
13800 // 7, 15, 23, 31, 39, 47, 55, 63
13801 // 6, 14, 22, 30, 39, 47, 55, 63
13802 // 5, 13, 21, 29, 39, 47, 55, 63
13803 // 4, 12, 20, 28
13804 for (var i = 7; i >= 5; i--) {
13805 for (var j = 0; j <= 24; j += 8) {
13806 outL <<= 1;
13807 outL |= (inR >> (j + i)) & 1;
13808 }
13809 for (var j = 0; j <= 24; j += 8) {
13810 outL <<= 1;
13811 outL |= (inL >> (j + i)) & 1;
13812 }
13813 }
13814 for (var j = 0; j <= 24; j += 8) {
13815 outL <<= 1;
13816 outL |= (inR >> (j + i)) & 1;
13817 }
13818
13819 // 1, 9, 17, 25, 33, 41, 49, 57
13820 // 2, 10, 18, 26, 34, 42, 50, 58
13821 // 3, 11, 19, 27, 35, 43, 51, 59
13822 // 36, 44, 52, 60
13823 for (var i = 1; i <= 3; i++) {
13824 for (var j = 0; j <= 24; j += 8) {
13825 outR <<= 1;
13826 outR |= (inR >> (j + i)) & 1;
13827 }
13828 for (var j = 0; j <= 24; j += 8) {
13829 outR <<= 1;
13830 outR |= (inL >> (j + i)) & 1;
13831 }
13832 }
13833 for (var j = 0; j <= 24; j += 8) {
13834 outR <<= 1;
13835 outR |= (inL >> (j + i)) & 1;
13836 }
13837
13838 out[off + 0] = outL >>> 0;
13839 out[off + 1] = outR >>> 0;
13840};
13841
13842exports.r28shl = function r28shl(num, shift) {
13843 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
13844};
13845
13846var pc2table = [
13847 // inL => outL
13848 14, 11, 17, 4, 27, 23, 25, 0,
13849 13, 22, 7, 18, 5, 9, 16, 24,
13850 2, 20, 12, 21, 1, 8, 15, 26,
13851
13852 // inR => outR
13853 15, 4, 25, 19, 9, 1, 26, 16,
13854 5, 11, 23, 8, 12, 7, 17, 0,
13855 22, 3, 10, 14, 6, 20, 27, 24
13856];
13857
13858exports.pc2 = function pc2(inL, inR, out, off) {
13859 var outL = 0;
13860 var outR = 0;
13861
13862 var len = pc2table.length >>> 1;
13863 for (var i = 0; i < len; i++) {
13864 outL <<= 1;
13865 outL |= (inL >>> pc2table[i]) & 0x1;
13866 }
13867 for (var i = len; i < pc2table.length; i++) {
13868 outR <<= 1;
13869 outR |= (inR >>> pc2table[i]) & 0x1;
13870 }
13871
13872 out[off + 0] = outL >>> 0;
13873 out[off + 1] = outR >>> 0;
13874};
13875
13876exports.expand = function expand(r, out, off) {
13877 var outL = 0;
13878 var outR = 0;
13879
13880 outL = ((r & 1) << 5) | (r >>> 27);
13881 for (var i = 23; i >= 15; i -= 4) {
13882 outL <<= 6;
13883 outL |= (r >>> i) & 0x3f;
13884 }
13885 for (var i = 11; i >= 3; i -= 4) {
13886 outR |= (r >>> i) & 0x3f;
13887 outR <<= 6;
13888 }
13889 outR |= ((r & 0x1f) << 1) | (r >>> 31);
13890
13891 out[off + 0] = outL >>> 0;
13892 out[off + 1] = outR >>> 0;
13893};
13894
13895var sTable = [
13896 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
13897 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
13898 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
13899 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
13900
13901 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
13902 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
13903 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
13904 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
13905
13906 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
13907 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
13908 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
13909 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
13910
13911 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
13912 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
13913 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
13914 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
13915
13916 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
13917 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
13918 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
13919 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
13920
13921 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
13922 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
13923 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
13924 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
13925
13926 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
13927 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
13928 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
13929 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
13930
13931 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
13932 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
13933 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
13934 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
13935];
13936
13937exports.substitute = function substitute(inL, inR) {
13938 var out = 0;
13939 for (var i = 0; i < 4; i++) {
13940 var b = (inL >>> (18 - i * 6)) & 0x3f;
13941 var sb = sTable[i * 0x40 + b];
13942
13943 out <<= 4;
13944 out |= sb;
13945 }
13946 for (var i = 0; i < 4; i++) {
13947 var b = (inR >>> (18 - i * 6)) & 0x3f;
13948 var sb = sTable[4 * 0x40 + i * 0x40 + b];
13949
13950 out <<= 4;
13951 out |= sb;
13952 }
13953 return out >>> 0;
13954};
13955
13956var permuteTable = [
13957 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
13958 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
13959];
13960
13961exports.permute = function permute(num) {
13962 var out = 0;
13963 for (var i = 0; i < permuteTable.length; i++) {
13964 out <<= 1;
13965 out |= (num >>> permuteTable[i]) & 0x1;
13966 }
13967 return out >>> 0;
13968};
13969
13970exports.padSplit = function padSplit(num, size, group) {
13971 var str = num.toString(2);
13972 while (str.length < size)
13973 str = '0' + str;
13974
13975 var out = [];
13976 for (var i = 0; i < size; i += group)
13977 out.push(str.slice(i, i + group));
13978 return out.join(' ');
13979};
13980
13981},{}],79:[function(require,module,exports){
13982(function (Buffer){
13983var generatePrime = require('./lib/generatePrime')
13984var primes = require('./lib/primes.json')
13985
13986var DH = require('./lib/dh')
13987
13988function getDiffieHellman (mod) {
13989 var prime = new Buffer(primes[mod].prime, 'hex')
13990 var gen = new Buffer(primes[mod].gen, 'hex')
13991
13992 return new DH(prime, gen)
13993}
13994
13995var ENCODINGS = {
13996 'binary': true, 'hex': true, 'base64': true
13997}
13998
13999function createDiffieHellman (prime, enc, generator, genc) {
14000 if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
14001 return createDiffieHellman(prime, 'binary', enc, generator)
14002 }
14003
14004 enc = enc || 'binary'
14005 genc = genc || 'binary'
14006 generator = generator || new Buffer([2])
14007
14008 if (!Buffer.isBuffer(generator)) {
14009 generator = new Buffer(generator, genc)
14010 }
14011
14012 if (typeof prime === 'number') {
14013 return new DH(generatePrime(prime, generator), generator, true)
14014 }
14015
14016 if (!Buffer.isBuffer(prime)) {
14017 prime = new Buffer(prime, enc)
14018 }
14019
14020 return new DH(prime, generator, true)
14021}
14022
14023exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
14024exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
14025
14026}).call(this,require("buffer").Buffer)
14027},{"./lib/dh":80,"./lib/generatePrime":81,"./lib/primes.json":82,"buffer":49}],80:[function(require,module,exports){
14028(function (Buffer){
14029var BN = require('bn.js');
14030var MillerRabin = require('miller-rabin');
14031var millerRabin = new MillerRabin();
14032var TWENTYFOUR = new BN(24);
14033var ELEVEN = new BN(11);
14034var TEN = new BN(10);
14035var THREE = new BN(3);
14036var SEVEN = new BN(7);
14037var primes = require('./generatePrime');
14038var randomBytes = require('randombytes');
14039module.exports = DH;
14040
14041function setPublicKey(pub, enc) {
14042 enc = enc || 'utf8';
14043 if (!Buffer.isBuffer(pub)) {
14044 pub = new Buffer(pub, enc);
14045 }
14046 this._pub = new BN(pub);
14047 return this;
14048}
14049
14050function setPrivateKey(priv, enc) {
14051 enc = enc || 'utf8';
14052 if (!Buffer.isBuffer(priv)) {
14053 priv = new Buffer(priv, enc);
14054 }
14055 this._priv = new BN(priv);
14056 return this;
14057}
14058
14059var primeCache = {};
14060function checkPrime(prime, generator) {
14061 var gen = generator.toString('hex');
14062 var hex = [gen, prime.toString(16)].join('_');
14063 if (hex in primeCache) {
14064 return primeCache[hex];
14065 }
14066 var error = 0;
14067
14068 if (prime.isEven() ||
14069 !primes.simpleSieve ||
14070 !primes.fermatTest(prime) ||
14071 !millerRabin.test(prime)) {
14072 //not a prime so +1
14073 error += 1;
14074
14075 if (gen === '02' || gen === '05') {
14076 // we'd be able to check the generator
14077 // it would fail so +8
14078 error += 8;
14079 } else {
14080 //we wouldn't be able to test the generator
14081 // so +4
14082 error += 4;
14083 }
14084 primeCache[hex] = error;
14085 return error;
14086 }
14087 if (!millerRabin.test(prime.shrn(1))) {
14088 //not a safe prime
14089 error += 2;
14090 }
14091 var rem;
14092 switch (gen) {
14093 case '02':
14094 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
14095 // unsuidable generator
14096 error += 8;
14097 }
14098 break;
14099 case '05':
14100 rem = prime.mod(TEN);
14101 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
14102 // prime mod 10 needs to equal 3 or 7
14103 error += 8;
14104 }
14105 break;
14106 default:
14107 error += 4;
14108 }
14109 primeCache[hex] = error;
14110 return error;
14111}
14112
14113function DH(prime, generator, malleable) {
14114 this.setGenerator(generator);
14115 this.__prime = new BN(prime);
14116 this._prime = BN.mont(this.__prime);
14117 this._primeLen = prime.length;
14118 this._pub = undefined;
14119 this._priv = undefined;
14120 this._primeCode = undefined;
14121 if (malleable) {
14122 this.setPublicKey = setPublicKey;
14123 this.setPrivateKey = setPrivateKey;
14124 } else {
14125 this._primeCode = 8;
14126 }
14127}
14128Object.defineProperty(DH.prototype, 'verifyError', {
14129 enumerable: true,
14130 get: function () {
14131 if (typeof this._primeCode !== 'number') {
14132 this._primeCode = checkPrime(this.__prime, this.__gen);
14133 }
14134 return this._primeCode;
14135 }
14136});
14137DH.prototype.generateKeys = function () {
14138 if (!this._priv) {
14139 this._priv = new BN(randomBytes(this._primeLen));
14140 }
14141 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
14142 return this.getPublicKey();
14143};
14144
14145DH.prototype.computeSecret = function (other) {
14146 other = new BN(other);
14147 other = other.toRed(this._prime);
14148 var secret = other.redPow(this._priv).fromRed();
14149 var out = new Buffer(secret.toArray());
14150 var prime = this.getPrime();
14151 if (out.length < prime.length) {
14152 var front = new Buffer(prime.length - out.length);
14153 front.fill(0);
14154 out = Buffer.concat([front, out]);
14155 }
14156 return out;
14157};
14158
14159DH.prototype.getPublicKey = function getPublicKey(enc) {
14160 return formatReturnValue(this._pub, enc);
14161};
14162
14163DH.prototype.getPrivateKey = function getPrivateKey(enc) {
14164 return formatReturnValue(this._priv, enc);
14165};
14166
14167DH.prototype.getPrime = function (enc) {
14168 return formatReturnValue(this.__prime, enc);
14169};
14170
14171DH.prototype.getGenerator = function (enc) {
14172 return formatReturnValue(this._gen, enc);
14173};
14174
14175DH.prototype.setGenerator = function (gen, enc) {
14176 enc = enc || 'utf8';
14177 if (!Buffer.isBuffer(gen)) {
14178 gen = new Buffer(gen, enc);
14179 }
14180 this.__gen = gen;
14181 this._gen = new BN(gen);
14182 return this;
14183};
14184
14185function formatReturnValue(bn, enc) {
14186 var buf = new Buffer(bn.toArray());
14187 if (!enc) {
14188 return buf;
14189 } else {
14190 return buf.toString(enc);
14191 }
14192}
14193
14194}).call(this,require("buffer").Buffer)
14195},{"./generatePrime":81,"bn.js":18,"buffer":49,"miller-rabin":355,"randombytes":376}],81:[function(require,module,exports){
14196var randomBytes = require('randombytes');
14197module.exports = findPrime;
14198findPrime.simpleSieve = simpleSieve;
14199findPrime.fermatTest = fermatTest;
14200var BN = require('bn.js');
14201var TWENTYFOUR = new BN(24);
14202var MillerRabin = require('miller-rabin');
14203var millerRabin = new MillerRabin();
14204var ONE = new BN(1);
14205var TWO = new BN(2);
14206var FIVE = new BN(5);
14207var SIXTEEN = new BN(16);
14208var EIGHT = new BN(8);
14209var TEN = new BN(10);
14210var THREE = new BN(3);
14211var SEVEN = new BN(7);
14212var ELEVEN = new BN(11);
14213var FOUR = new BN(4);
14214var TWELVE = new BN(12);
14215var primes = null;
14216
14217function _getPrimes() {
14218 if (primes !== null)
14219 return primes;
14220
14221 var limit = 0x100000;
14222 var res = [];
14223 res[0] = 2;
14224 for (var i = 1, k = 3; k < limit; k += 2) {
14225 var sqrt = Math.ceil(Math.sqrt(k));
14226 for (var j = 0; j < i && res[j] <= sqrt; j++)
14227 if (k % res[j] === 0)
14228 break;
14229
14230 if (i !== j && res[j] <= sqrt)
14231 continue;
14232
14233 res[i++] = k;
14234 }
14235 primes = res;
14236 return res;
14237}
14238
14239function simpleSieve(p) {
14240 var primes = _getPrimes();
14241
14242 for (var i = 0; i < primes.length; i++)
14243 if (p.modn(primes[i]) === 0) {
14244 if (p.cmpn(primes[i]) === 0) {
14245 return true;
14246 } else {
14247 return false;
14248 }
14249 }
14250
14251 return true;
14252}
14253
14254function fermatTest(p) {
14255 var red = BN.mont(p);
14256 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
14257}
14258
14259function findPrime(bits, gen) {
14260 if (bits < 16) {
14261 // this is what openssl does
14262 if (gen === 2 || gen === 5) {
14263 return new BN([0x8c, 0x7b]);
14264 } else {
14265 return new BN([0x8c, 0x27]);
14266 }
14267 }
14268 gen = new BN(gen);
14269
14270 var num, n2;
14271
14272 while (true) {
14273 num = new BN(randomBytes(Math.ceil(bits / 8)));
14274 while (num.bitLength() > bits) {
14275 num.ishrn(1);
14276 }
14277 if (num.isEven()) {
14278 num.iadd(ONE);
14279 }
14280 if (!num.testn(1)) {
14281 num.iadd(TWO);
14282 }
14283 if (!gen.cmp(TWO)) {
14284 while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
14285 num.iadd(FOUR);
14286 }
14287 } else if (!gen.cmp(FIVE)) {
14288 while (num.mod(TEN).cmp(THREE)) {
14289 num.iadd(FOUR);
14290 }
14291 }
14292 n2 = num.shrn(1);
14293 if (simpleSieve(n2) && simpleSieve(num) &&
14294 fermatTest(n2) && fermatTest(num) &&
14295 millerRabin.test(n2) && millerRabin.test(num)) {
14296 return num;
14297 }
14298 }
14299
14300}
14301
14302},{"bn.js":18,"miller-rabin":355,"randombytes":376}],82:[function(require,module,exports){
14303module.exports={
14304 "modp1": {
14305 "gen": "02",
14306 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
14307 },
14308 "modp2": {
14309 "gen": "02",
14310 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
14311 },
14312 "modp5": {
14313 "gen": "02",
14314 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
14315 },
14316 "modp14": {
14317 "gen": "02",
14318 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
14319 },
14320 "modp15": {
14321 "gen": "02",
14322 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
14323 },
14324 "modp16": {
14325 "gen": "02",
14326 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
14327 },
14328 "modp17": {
14329 "gen": "02",
14330 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
14331 },
14332 "modp18": {
14333 "gen": "02",
14334 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
14335 }
14336}
14337},{}],83:[function(require,module,exports){
14338'use strict';
14339
14340var elliptic = exports;
14341
14342elliptic.version = require('../package.json').version;
14343elliptic.utils = require('./elliptic/utils');
14344elliptic.rand = require('brorand');
14345elliptic.curve = require('./elliptic/curve');
14346elliptic.curves = require('./elliptic/curves');
14347
14348// Protocols
14349elliptic.ec = require('./elliptic/ec');
14350elliptic.eddsa = require('./elliptic/eddsa');
14351
14352},{"../package.json":98,"./elliptic/curve":86,"./elliptic/curves":89,"./elliptic/ec":90,"./elliptic/eddsa":93,"./elliptic/utils":97,"brorand":19}],84:[function(require,module,exports){
14353'use strict';
14354
14355var BN = require('bn.js');
14356var elliptic = require('../../elliptic');
14357var utils = elliptic.utils;
14358var getNAF = utils.getNAF;
14359var getJSF = utils.getJSF;
14360var assert = utils.assert;
14361
14362function BaseCurve(type, conf) {
14363 this.type = type;
14364 this.p = new BN(conf.p, 16);
14365
14366 // Use Montgomery, when there is no fast reduction for the prime
14367 this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
14368
14369 // Useful for many curves
14370 this.zero = new BN(0).toRed(this.red);
14371 this.one = new BN(1).toRed(this.red);
14372 this.two = new BN(2).toRed(this.red);
14373
14374 // Curve configuration, optional
14375 this.n = conf.n && new BN(conf.n, 16);
14376 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
14377
14378 // Temporary arrays
14379 this._wnafT1 = new Array(4);
14380 this._wnafT2 = new Array(4);
14381 this._wnafT3 = new Array(4);
14382 this._wnafT4 = new Array(4);
14383
14384 // Generalized Greg Maxwell's trick
14385 var adjustCount = this.n && this.p.div(this.n);
14386 if (!adjustCount || adjustCount.cmpn(100) > 0) {
14387 this.redN = null;
14388 } else {
14389 this._maxwellTrick = true;
14390 this.redN = this.n.toRed(this.red);
14391 }
14392}
14393module.exports = BaseCurve;
14394
14395BaseCurve.prototype.point = function point() {
14396 throw new Error('Not implemented');
14397};
14398
14399BaseCurve.prototype.validate = function validate() {
14400 throw new Error('Not implemented');
14401};
14402
14403BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
14404 assert(p.precomputed);
14405 var doubles = p._getDoubles();
14406
14407 var naf = getNAF(k, 1);
14408 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
14409 I /= 3;
14410
14411 // Translate into more windowed form
14412 var repr = [];
14413 for (var j = 0; j < naf.length; j += doubles.step) {
14414 var nafW = 0;
14415 for (var k = j + doubles.step - 1; k >= j; k--)
14416 nafW = (nafW << 1) + naf[k];
14417 repr.push(nafW);
14418 }
14419
14420 var a = this.jpoint(null, null, null);
14421 var b = this.jpoint(null, null, null);
14422 for (var i = I; i > 0; i--) {
14423 for (var j = 0; j < repr.length; j++) {
14424 var nafW = repr[j];
14425 if (nafW === i)
14426 b = b.mixedAdd(doubles.points[j]);
14427 else if (nafW === -i)
14428 b = b.mixedAdd(doubles.points[j].neg());
14429 }
14430 a = a.add(b);
14431 }
14432 return a.toP();
14433};
14434
14435BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
14436 var w = 4;
14437
14438 // Precompute window
14439 var nafPoints = p._getNAFPoints(w);
14440 w = nafPoints.wnd;
14441 var wnd = nafPoints.points;
14442
14443 // Get NAF form
14444 var naf = getNAF(k, w);
14445
14446 // Add `this`*(N+1) for every w-NAF index
14447 var acc = this.jpoint(null, null, null);
14448 for (var i = naf.length - 1; i >= 0; i--) {
14449 // Count zeroes
14450 for (var k = 0; i >= 0 && naf[i] === 0; i--)
14451 k++;
14452 if (i >= 0)
14453 k++;
14454 acc = acc.dblp(k);
14455
14456 if (i < 0)
14457 break;
14458 var z = naf[i];
14459 assert(z !== 0);
14460 if (p.type === 'affine') {
14461 // J +- P
14462 if (z > 0)
14463 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
14464 else
14465 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
14466 } else {
14467 // J +- J
14468 if (z > 0)
14469 acc = acc.add(wnd[(z - 1) >> 1]);
14470 else
14471 acc = acc.add(wnd[(-z - 1) >> 1].neg());
14472 }
14473 }
14474 return p.type === 'affine' ? acc.toP() : acc;
14475};
14476
14477BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
14478 points,
14479 coeffs,
14480 len,
14481 jacobianResult) {
14482 var wndWidth = this._wnafT1;
14483 var wnd = this._wnafT2;
14484 var naf = this._wnafT3;
14485
14486 // Fill all arrays
14487 var max = 0;
14488 for (var i = 0; i < len; i++) {
14489 var p = points[i];
14490 var nafPoints = p._getNAFPoints(defW);
14491 wndWidth[i] = nafPoints.wnd;
14492 wnd[i] = nafPoints.points;
14493 }
14494
14495 // Comb small window NAFs
14496 for (var i = len - 1; i >= 1; i -= 2) {
14497 var a = i - 1;
14498 var b = i;
14499 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
14500 naf[a] = getNAF(coeffs[a], wndWidth[a]);
14501 naf[b] = getNAF(coeffs[b], wndWidth[b]);
14502 max = Math.max(naf[a].length, max);
14503 max = Math.max(naf[b].length, max);
14504 continue;
14505 }
14506
14507 var comb = [
14508 points[a], /* 1 */
14509 null, /* 3 */
14510 null, /* 5 */
14511 points[b] /* 7 */
14512 ];
14513
14514 // Try to avoid Projective points, if possible
14515 if (points[a].y.cmp(points[b].y) === 0) {
14516 comb[1] = points[a].add(points[b]);
14517 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
14518 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
14519 comb[1] = points[a].toJ().mixedAdd(points[b]);
14520 comb[2] = points[a].add(points[b].neg());
14521 } else {
14522 comb[1] = points[a].toJ().mixedAdd(points[b]);
14523 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
14524 }
14525
14526 var index = [
14527 -3, /* -1 -1 */
14528 -1, /* -1 0 */
14529 -5, /* -1 1 */
14530 -7, /* 0 -1 */
14531 0, /* 0 0 */
14532 7, /* 0 1 */
14533 5, /* 1 -1 */
14534 1, /* 1 0 */
14535 3 /* 1 1 */
14536 ];
14537
14538 var jsf = getJSF(coeffs[a], coeffs[b]);
14539 max = Math.max(jsf[0].length, max);
14540 naf[a] = new Array(max);
14541 naf[b] = new Array(max);
14542 for (var j = 0; j < max; j++) {
14543 var ja = jsf[0][j] | 0;
14544 var jb = jsf[1][j] | 0;
14545
14546 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
14547 naf[b][j] = 0;
14548 wnd[a] = comb;
14549 }
14550 }
14551
14552 var acc = this.jpoint(null, null, null);
14553 var tmp = this._wnafT4;
14554 for (var i = max; i >= 0; i--) {
14555 var k = 0;
14556
14557 while (i >= 0) {
14558 var zero = true;
14559 for (var j = 0; j < len; j++) {
14560 tmp[j] = naf[j][i] | 0;
14561 if (tmp[j] !== 0)
14562 zero = false;
14563 }
14564 if (!zero)
14565 break;
14566 k++;
14567 i--;
14568 }
14569 if (i >= 0)
14570 k++;
14571 acc = acc.dblp(k);
14572 if (i < 0)
14573 break;
14574
14575 for (var j = 0; j < len; j++) {
14576 var z = tmp[j];
14577 var p;
14578 if (z === 0)
14579 continue;
14580 else if (z > 0)
14581 p = wnd[j][(z - 1) >> 1];
14582 else if (z < 0)
14583 p = wnd[j][(-z - 1) >> 1].neg();
14584
14585 if (p.type === 'affine')
14586 acc = acc.mixedAdd(p);
14587 else
14588 acc = acc.add(p);
14589 }
14590 }
14591 // Zeroify references
14592 for (var i = 0; i < len; i++)
14593 wnd[i] = null;
14594
14595 if (jacobianResult)
14596 return acc;
14597 else
14598 return acc.toP();
14599};
14600
14601function BasePoint(curve, type) {
14602 this.curve = curve;
14603 this.type = type;
14604 this.precomputed = null;
14605}
14606BaseCurve.BasePoint = BasePoint;
14607
14608BasePoint.prototype.eq = function eq(/*other*/) {
14609 throw new Error('Not implemented');
14610};
14611
14612BasePoint.prototype.validate = function validate() {
14613 return this.curve.validate(this);
14614};
14615
14616BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
14617 bytes = utils.toArray(bytes, enc);
14618
14619 var len = this.p.byteLength();
14620
14621 // uncompressed, hybrid-odd, hybrid-even
14622 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
14623 bytes.length - 1 === 2 * len) {
14624 if (bytes[0] === 0x06)
14625 assert(bytes[bytes.length - 1] % 2 === 0);
14626 else if (bytes[0] === 0x07)
14627 assert(bytes[bytes.length - 1] % 2 === 1);
14628
14629 var res = this.point(bytes.slice(1, 1 + len),
14630 bytes.slice(1 + len, 1 + 2 * len));
14631
14632 return res;
14633 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
14634 bytes.length - 1 === len) {
14635 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
14636 }
14637 throw new Error('Unknown point format');
14638};
14639
14640BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
14641 return this.encode(enc, true);
14642};
14643
14644BasePoint.prototype._encode = function _encode(compact) {
14645 var len = this.curve.p.byteLength();
14646 var x = this.getX().toArray('be', len);
14647
14648 if (compact)
14649 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
14650
14651 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
14652};
14653
14654BasePoint.prototype.encode = function encode(enc, compact) {
14655 return utils.encode(this._encode(compact), enc);
14656};
14657
14658BasePoint.prototype.precompute = function precompute(power) {
14659 if (this.precomputed)
14660 return this;
14661
14662 var precomputed = {
14663 doubles: null,
14664 naf: null,
14665 beta: null
14666 };
14667 precomputed.naf = this._getNAFPoints(8);
14668 precomputed.doubles = this._getDoubles(4, power);
14669 precomputed.beta = this._getBeta();
14670 this.precomputed = precomputed;
14671
14672 return this;
14673};
14674
14675BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
14676 if (!this.precomputed)
14677 return false;
14678
14679 var doubles = this.precomputed.doubles;
14680 if (!doubles)
14681 return false;
14682
14683 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
14684};
14685
14686BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
14687 if (this.precomputed && this.precomputed.doubles)
14688 return this.precomputed.doubles;
14689
14690 var doubles = [ this ];
14691 var acc = this;
14692 for (var i = 0; i < power; i += step) {
14693 for (var j = 0; j < step; j++)
14694 acc = acc.dbl();
14695 doubles.push(acc);
14696 }
14697 return {
14698 step: step,
14699 points: doubles
14700 };
14701};
14702
14703BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
14704 if (this.precomputed && this.precomputed.naf)
14705 return this.precomputed.naf;
14706
14707 var res = [ this ];
14708 var max = (1 << wnd) - 1;
14709 var dbl = max === 1 ? null : this.dbl();
14710 for (var i = 1; i < max; i++)
14711 res[i] = res[i - 1].add(dbl);
14712 return {
14713 wnd: wnd,
14714 points: res
14715 };
14716};
14717
14718BasePoint.prototype._getBeta = function _getBeta() {
14719 return null;
14720};
14721
14722BasePoint.prototype.dblp = function dblp(k) {
14723 var r = this;
14724 for (var i = 0; i < k; i++)
14725 r = r.dbl();
14726 return r;
14727};
14728
14729},{"../../elliptic":83,"bn.js":18}],85:[function(require,module,exports){
14730'use strict';
14731
14732var curve = require('../curve');
14733var elliptic = require('../../elliptic');
14734var BN = require('bn.js');
14735var inherits = require('inherits');
14736var Base = curve.base;
14737
14738var assert = elliptic.utils.assert;
14739
14740function EdwardsCurve(conf) {
14741 // NOTE: Important as we are creating point in Base.call()
14742 this.twisted = (conf.a | 0) !== 1;
14743 this.mOneA = this.twisted && (conf.a | 0) === -1;
14744 this.extended = this.mOneA;
14745
14746 Base.call(this, 'edwards', conf);
14747
14748 this.a = new BN(conf.a, 16).umod(this.red.m);
14749 this.a = this.a.toRed(this.red);
14750 this.c = new BN(conf.c, 16).toRed(this.red);
14751 this.c2 = this.c.redSqr();
14752 this.d = new BN(conf.d, 16).toRed(this.red);
14753 this.dd = this.d.redAdd(this.d);
14754
14755 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
14756 this.oneC = (conf.c | 0) === 1;
14757}
14758inherits(EdwardsCurve, Base);
14759module.exports = EdwardsCurve;
14760
14761EdwardsCurve.prototype._mulA = function _mulA(num) {
14762 if (this.mOneA)
14763 return num.redNeg();
14764 else
14765 return this.a.redMul(num);
14766};
14767
14768EdwardsCurve.prototype._mulC = function _mulC(num) {
14769 if (this.oneC)
14770 return num;
14771 else
14772 return this.c.redMul(num);
14773};
14774
14775// Just for compatibility with Short curve
14776EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
14777 return this.point(x, y, z, t);
14778};
14779
14780EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
14781 x = new BN(x, 16);
14782 if (!x.red)
14783 x = x.toRed(this.red);
14784
14785 var x2 = x.redSqr();
14786 var rhs = this.c2.redSub(this.a.redMul(x2));
14787 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
14788
14789 var y2 = rhs.redMul(lhs.redInvm());
14790 var y = y2.redSqrt();
14791 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
14792 throw new Error('invalid point');
14793
14794 var isOdd = y.fromRed().isOdd();
14795 if (odd && !isOdd || !odd && isOdd)
14796 y = y.redNeg();
14797
14798 return this.point(x, y);
14799};
14800
14801EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
14802 y = new BN(y, 16);
14803 if (!y.red)
14804 y = y.toRed(this.red);
14805
14806 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
14807 var y2 = y.redSqr();
14808 var lhs = y2.redSub(this.c2);
14809 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
14810 var x2 = lhs.redMul(rhs.redInvm());
14811
14812 if (x2.cmp(this.zero) === 0) {
14813 if (odd)
14814 throw new Error('invalid point');
14815 else
14816 return this.point(this.zero, y);
14817 }
14818
14819 var x = x2.redSqrt();
14820 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
14821 throw new Error('invalid point');
14822
14823 if (x.fromRed().isOdd() !== odd)
14824 x = x.redNeg();
14825
14826 return this.point(x, y);
14827};
14828
14829EdwardsCurve.prototype.validate = function validate(point) {
14830 if (point.isInfinity())
14831 return true;
14832
14833 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
14834 point.normalize();
14835
14836 var x2 = point.x.redSqr();
14837 var y2 = point.y.redSqr();
14838 var lhs = x2.redMul(this.a).redAdd(y2);
14839 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
14840
14841 return lhs.cmp(rhs) === 0;
14842};
14843
14844function Point(curve, x, y, z, t) {
14845 Base.BasePoint.call(this, curve, 'projective');
14846 if (x === null && y === null && z === null) {
14847 this.x = this.curve.zero;
14848 this.y = this.curve.one;
14849 this.z = this.curve.one;
14850 this.t = this.curve.zero;
14851 this.zOne = true;
14852 } else {
14853 this.x = new BN(x, 16);
14854 this.y = new BN(y, 16);
14855 this.z = z ? new BN(z, 16) : this.curve.one;
14856 this.t = t && new BN(t, 16);
14857 if (!this.x.red)
14858 this.x = this.x.toRed(this.curve.red);
14859 if (!this.y.red)
14860 this.y = this.y.toRed(this.curve.red);
14861 if (!this.z.red)
14862 this.z = this.z.toRed(this.curve.red);
14863 if (this.t && !this.t.red)
14864 this.t = this.t.toRed(this.curve.red);
14865 this.zOne = this.z === this.curve.one;
14866
14867 // Use extended coordinates
14868 if (this.curve.extended && !this.t) {
14869 this.t = this.x.redMul(this.y);
14870 if (!this.zOne)
14871 this.t = this.t.redMul(this.z.redInvm());
14872 }
14873 }
14874}
14875inherits(Point, Base.BasePoint);
14876
14877EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
14878 return Point.fromJSON(this, obj);
14879};
14880
14881EdwardsCurve.prototype.point = function point(x, y, z, t) {
14882 return new Point(this, x, y, z, t);
14883};
14884
14885Point.fromJSON = function fromJSON(curve, obj) {
14886 return new Point(curve, obj[0], obj[1], obj[2]);
14887};
14888
14889Point.prototype.inspect = function inspect() {
14890 if (this.isInfinity())
14891 return '<EC Point Infinity>';
14892 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
14893 ' y: ' + this.y.fromRed().toString(16, 2) +
14894 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
14895};
14896
14897Point.prototype.isInfinity = function isInfinity() {
14898 // XXX This code assumes that zero is always zero in red
14899 return this.x.cmpn(0) === 0 &&
14900 (this.y.cmp(this.z) === 0 ||
14901 (this.zOne && this.y.cmp(this.curve.c) === 0));
14902};
14903
14904Point.prototype._extDbl = function _extDbl() {
14905 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
14906 // #doubling-dbl-2008-hwcd
14907 // 4M + 4S
14908
14909 // A = X1^2
14910 var a = this.x.redSqr();
14911 // B = Y1^2
14912 var b = this.y.redSqr();
14913 // C = 2 * Z1^2
14914 var c = this.z.redSqr();
14915 c = c.redIAdd(c);
14916 // D = a * A
14917 var d = this.curve._mulA(a);
14918 // E = (X1 + Y1)^2 - A - B
14919 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
14920 // G = D + B
14921 var g = d.redAdd(b);
14922 // F = G - C
14923 var f = g.redSub(c);
14924 // H = D - B
14925 var h = d.redSub(b);
14926 // X3 = E * F
14927 var nx = e.redMul(f);
14928 // Y3 = G * H
14929 var ny = g.redMul(h);
14930 // T3 = E * H
14931 var nt = e.redMul(h);
14932 // Z3 = F * G
14933 var nz = f.redMul(g);
14934 return this.curve.point(nx, ny, nz, nt);
14935};
14936
14937Point.prototype._projDbl = function _projDbl() {
14938 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
14939 // #doubling-dbl-2008-bbjlp
14940 // #doubling-dbl-2007-bl
14941 // and others
14942 // Generally 3M + 4S or 2M + 4S
14943
14944 // B = (X1 + Y1)^2
14945 var b = this.x.redAdd(this.y).redSqr();
14946 // C = X1^2
14947 var c = this.x.redSqr();
14948 // D = Y1^2
14949 var d = this.y.redSqr();
14950
14951 var nx;
14952 var ny;
14953 var nz;
14954 if (this.curve.twisted) {
14955 // E = a * C
14956 var e = this.curve._mulA(c);
14957 // F = E + D
14958 var f = e.redAdd(d);
14959 if (this.zOne) {
14960 // X3 = (B - C - D) * (F - 2)
14961 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
14962 // Y3 = F * (E - D)
14963 ny = f.redMul(e.redSub(d));
14964 // Z3 = F^2 - 2 * F
14965 nz = f.redSqr().redSub(f).redSub(f);
14966 } else {
14967 // H = Z1^2
14968 var h = this.z.redSqr();
14969 // J = F - 2 * H
14970 var j = f.redSub(h).redISub(h);
14971 // X3 = (B-C-D)*J
14972 nx = b.redSub(c).redISub(d).redMul(j);
14973 // Y3 = F * (E - D)
14974 ny = f.redMul(e.redSub(d));
14975 // Z3 = F * J
14976 nz = f.redMul(j);
14977 }
14978 } else {
14979 // E = C + D
14980 var e = c.redAdd(d);
14981 // H = (c * Z1)^2
14982 var h = this.curve._mulC(this.z).redSqr();
14983 // J = E - 2 * H
14984 var j = e.redSub(h).redSub(h);
14985 // X3 = c * (B - E) * J
14986 nx = this.curve._mulC(b.redISub(e)).redMul(j);
14987 // Y3 = c * E * (C - D)
14988 ny = this.curve._mulC(e).redMul(c.redISub(d));
14989 // Z3 = E * J
14990 nz = e.redMul(j);
14991 }
14992 return this.curve.point(nx, ny, nz);
14993};
14994
14995Point.prototype.dbl = function dbl() {
14996 if (this.isInfinity())
14997 return this;
14998
14999 // Double in extended coordinates
15000 if (this.curve.extended)
15001 return this._extDbl();
15002 else
15003 return this._projDbl();
15004};
15005
15006Point.prototype._extAdd = function _extAdd(p) {
15007 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
15008 // #addition-add-2008-hwcd-3
15009 // 8M
15010
15011 // A = (Y1 - X1) * (Y2 - X2)
15012 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
15013 // B = (Y1 + X1) * (Y2 + X2)
15014 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
15015 // C = T1 * k * T2
15016 var c = this.t.redMul(this.curve.dd).redMul(p.t);
15017 // D = Z1 * 2 * Z2
15018 var d = this.z.redMul(p.z.redAdd(p.z));
15019 // E = B - A
15020 var e = b.redSub(a);
15021 // F = D - C
15022 var f = d.redSub(c);
15023 // G = D + C
15024 var g = d.redAdd(c);
15025 // H = B + A
15026 var h = b.redAdd(a);
15027 // X3 = E * F
15028 var nx = e.redMul(f);
15029 // Y3 = G * H
15030 var ny = g.redMul(h);
15031 // T3 = E * H
15032 var nt = e.redMul(h);
15033 // Z3 = F * G
15034 var nz = f.redMul(g);
15035 return this.curve.point(nx, ny, nz, nt);
15036};
15037
15038Point.prototype._projAdd = function _projAdd(p) {
15039 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
15040 // #addition-add-2008-bbjlp
15041 // #addition-add-2007-bl
15042 // 10M + 1S
15043
15044 // A = Z1 * Z2
15045 var a = this.z.redMul(p.z);
15046 // B = A^2
15047 var b = a.redSqr();
15048 // C = X1 * X2
15049 var c = this.x.redMul(p.x);
15050 // D = Y1 * Y2
15051 var d = this.y.redMul(p.y);
15052 // E = d * C * D
15053 var e = this.curve.d.redMul(c).redMul(d);
15054 // F = B - E
15055 var f = b.redSub(e);
15056 // G = B + E
15057 var g = b.redAdd(e);
15058 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
15059 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
15060 var nx = a.redMul(f).redMul(tmp);
15061 var ny;
15062 var nz;
15063 if (this.curve.twisted) {
15064 // Y3 = A * G * (D - a * C)
15065 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
15066 // Z3 = F * G
15067 nz = f.redMul(g);
15068 } else {
15069 // Y3 = A * G * (D - C)
15070 ny = a.redMul(g).redMul(d.redSub(c));
15071 // Z3 = c * F * G
15072 nz = this.curve._mulC(f).redMul(g);
15073 }
15074 return this.curve.point(nx, ny, nz);
15075};
15076
15077Point.prototype.add = function add(p) {
15078 if (this.isInfinity())
15079 return p;
15080 if (p.isInfinity())
15081 return this;
15082
15083 if (this.curve.extended)
15084 return this._extAdd(p);
15085 else
15086 return this._projAdd(p);
15087};
15088
15089Point.prototype.mul = function mul(k) {
15090 if (this._hasDoubles(k))
15091 return this.curve._fixedNafMul(this, k);
15092 else
15093 return this.curve._wnafMul(this, k);
15094};
15095
15096Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
15097 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
15098};
15099
15100Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
15101 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
15102};
15103
15104Point.prototype.normalize = function normalize() {
15105 if (this.zOne)
15106 return this;
15107
15108 // Normalize coordinates
15109 var zi = this.z.redInvm();
15110 this.x = this.x.redMul(zi);
15111 this.y = this.y.redMul(zi);
15112 if (this.t)
15113 this.t = this.t.redMul(zi);
15114 this.z = this.curve.one;
15115 this.zOne = true;
15116 return this;
15117};
15118
15119Point.prototype.neg = function neg() {
15120 return this.curve.point(this.x.redNeg(),
15121 this.y,
15122 this.z,
15123 this.t && this.t.redNeg());
15124};
15125
15126Point.prototype.getX = function getX() {
15127 this.normalize();
15128 return this.x.fromRed();
15129};
15130
15131Point.prototype.getY = function getY() {
15132 this.normalize();
15133 return this.y.fromRed();
15134};
15135
15136Point.prototype.eq = function eq(other) {
15137 return this === other ||
15138 this.getX().cmp(other.getX()) === 0 &&
15139 this.getY().cmp(other.getY()) === 0;
15140};
15141
15142Point.prototype.eqXToP = function eqXToP(x) {
15143 var rx = x.toRed(this.curve.red).redMul(this.z);
15144 if (this.x.cmp(rx) === 0)
15145 return true;
15146
15147 var xc = x.clone();
15148 var t = this.curve.redN.redMul(this.z);
15149 for (;;) {
15150 xc.iadd(this.curve.n);
15151 if (xc.cmp(this.curve.p) >= 0)
15152 return false;
15153
15154 rx.redIAdd(t);
15155 if (this.x.cmp(rx) === 0)
15156 return true;
15157 }
15158};
15159
15160// Compatibility with BaseCurve
15161Point.prototype.toP = Point.prototype.normalize;
15162Point.prototype.mixedAdd = Point.prototype.add;
15163
15164},{"../../elliptic":83,"../curve":86,"bn.js":18,"inherits":116}],86:[function(require,module,exports){
15165'use strict';
15166
15167var curve = exports;
15168
15169curve.base = require('./base');
15170curve.short = require('./short');
15171curve.mont = require('./mont');
15172curve.edwards = require('./edwards');
15173
15174},{"./base":84,"./edwards":85,"./mont":87,"./short":88}],87:[function(require,module,exports){
15175'use strict';
15176
15177var curve = require('../curve');
15178var BN = require('bn.js');
15179var inherits = require('inherits');
15180var Base = curve.base;
15181
15182var elliptic = require('../../elliptic');
15183var utils = elliptic.utils;
15184
15185function MontCurve(conf) {
15186 Base.call(this, 'mont', conf);
15187
15188 this.a = new BN(conf.a, 16).toRed(this.red);
15189 this.b = new BN(conf.b, 16).toRed(this.red);
15190 this.i4 = new BN(4).toRed(this.red).redInvm();
15191 this.two = new BN(2).toRed(this.red);
15192 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
15193}
15194inherits(MontCurve, Base);
15195module.exports = MontCurve;
15196
15197MontCurve.prototype.validate = function validate(point) {
15198 var x = point.normalize().x;
15199 var x2 = x.redSqr();
15200 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
15201 var y = rhs.redSqrt();
15202
15203 return y.redSqr().cmp(rhs) === 0;
15204};
15205
15206function Point(curve, x, z) {
15207 Base.BasePoint.call(this, curve, 'projective');
15208 if (x === null && z === null) {
15209 this.x = this.curve.one;
15210 this.z = this.curve.zero;
15211 } else {
15212 this.x = new BN(x, 16);
15213 this.z = new BN(z, 16);
15214 if (!this.x.red)
15215 this.x = this.x.toRed(this.curve.red);
15216 if (!this.z.red)
15217 this.z = this.z.toRed(this.curve.red);
15218 }
15219}
15220inherits(Point, Base.BasePoint);
15221
15222MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
15223 return this.point(utils.toArray(bytes, enc), 1);
15224};
15225
15226MontCurve.prototype.point = function point(x, z) {
15227 return new Point(this, x, z);
15228};
15229
15230MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
15231 return Point.fromJSON(this, obj);
15232};
15233
15234Point.prototype.precompute = function precompute() {
15235 // No-op
15236};
15237
15238Point.prototype._encode = function _encode() {
15239 return this.getX().toArray('be', this.curve.p.byteLength());
15240};
15241
15242Point.fromJSON = function fromJSON(curve, obj) {
15243 return new Point(curve, obj[0], obj[1] || curve.one);
15244};
15245
15246Point.prototype.inspect = function inspect() {
15247 if (this.isInfinity())
15248 return '<EC Point Infinity>';
15249 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
15250 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
15251};
15252
15253Point.prototype.isInfinity = function isInfinity() {
15254 // XXX This code assumes that zero is always zero in red
15255 return this.z.cmpn(0) === 0;
15256};
15257
15258Point.prototype.dbl = function dbl() {
15259 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
15260 // 2M + 2S + 4A
15261
15262 // A = X1 + Z1
15263 var a = this.x.redAdd(this.z);
15264 // AA = A^2
15265 var aa = a.redSqr();
15266 // B = X1 - Z1
15267 var b = this.x.redSub(this.z);
15268 // BB = B^2
15269 var bb = b.redSqr();
15270 // C = AA - BB
15271 var c = aa.redSub(bb);
15272 // X3 = AA * BB
15273 var nx = aa.redMul(bb);
15274 // Z3 = C * (BB + A24 * C)
15275 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
15276 return this.curve.point(nx, nz);
15277};
15278
15279Point.prototype.add = function add() {
15280 throw new Error('Not supported on Montgomery curve');
15281};
15282
15283Point.prototype.diffAdd = function diffAdd(p, diff) {
15284 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
15285 // 4M + 2S + 6A
15286
15287 // A = X2 + Z2
15288 var a = this.x.redAdd(this.z);
15289 // B = X2 - Z2
15290 var b = this.x.redSub(this.z);
15291 // C = X3 + Z3
15292 var c = p.x.redAdd(p.z);
15293 // D = X3 - Z3
15294 var d = p.x.redSub(p.z);
15295 // DA = D * A
15296 var da = d.redMul(a);
15297 // CB = C * B
15298 var cb = c.redMul(b);
15299 // X5 = Z1 * (DA + CB)^2
15300 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
15301 // Z5 = X1 * (DA - CB)^2
15302 var nz = diff.x.redMul(da.redISub(cb).redSqr());
15303 return this.curve.point(nx, nz);
15304};
15305
15306Point.prototype.mul = function mul(k) {
15307 var t = k.clone();
15308 var a = this; // (N / 2) * Q + Q
15309 var b = this.curve.point(null, null); // (N / 2) * Q
15310 var c = this; // Q
15311
15312 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
15313 bits.push(t.andln(1));
15314
15315 for (var i = bits.length - 1; i >= 0; i--) {
15316 if (bits[i] === 0) {
15317 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
15318 a = a.diffAdd(b, c);
15319 // N * Q = 2 * ((N / 2) * Q + Q))
15320 b = b.dbl();
15321 } else {
15322 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
15323 b = a.diffAdd(b, c);
15324 // N * Q + Q = 2 * ((N / 2) * Q + Q)
15325 a = a.dbl();
15326 }
15327 }
15328 return b;
15329};
15330
15331Point.prototype.mulAdd = function mulAdd() {
15332 throw new Error('Not supported on Montgomery curve');
15333};
15334
15335Point.prototype.jumlAdd = function jumlAdd() {
15336 throw new Error('Not supported on Montgomery curve');
15337};
15338
15339Point.prototype.eq = function eq(other) {
15340 return this.getX().cmp(other.getX()) === 0;
15341};
15342
15343Point.prototype.normalize = function normalize() {
15344 this.x = this.x.redMul(this.z.redInvm());
15345 this.z = this.curve.one;
15346 return this;
15347};
15348
15349Point.prototype.getX = function getX() {
15350 // Normalize coordinates
15351 this.normalize();
15352
15353 return this.x.fromRed();
15354};
15355
15356},{"../../elliptic":83,"../curve":86,"bn.js":18,"inherits":116}],88:[function(require,module,exports){
15357'use strict';
15358
15359var curve = require('../curve');
15360var elliptic = require('../../elliptic');
15361var BN = require('bn.js');
15362var inherits = require('inherits');
15363var Base = curve.base;
15364
15365var assert = elliptic.utils.assert;
15366
15367function ShortCurve(conf) {
15368 Base.call(this, 'short', conf);
15369
15370 this.a = new BN(conf.a, 16).toRed(this.red);
15371 this.b = new BN(conf.b, 16).toRed(this.red);
15372 this.tinv = this.two.redInvm();
15373
15374 this.zeroA = this.a.fromRed().cmpn(0) === 0;
15375 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
15376
15377 // If the curve is endomorphic, precalculate beta and lambda
15378 this.endo = this._getEndomorphism(conf);
15379 this._endoWnafT1 = new Array(4);
15380 this._endoWnafT2 = new Array(4);
15381}
15382inherits(ShortCurve, Base);
15383module.exports = ShortCurve;
15384
15385ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
15386 // No efficient endomorphism
15387 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
15388 return;
15389
15390 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
15391 var beta;
15392 var lambda;
15393 if (conf.beta) {
15394 beta = new BN(conf.beta, 16).toRed(this.red);
15395 } else {
15396 var betas = this._getEndoRoots(this.p);
15397 // Choose the smallest beta
15398 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
15399 beta = beta.toRed(this.red);
15400 }
15401 if (conf.lambda) {
15402 lambda = new BN(conf.lambda, 16);
15403 } else {
15404 // Choose the lambda that is matching selected beta
15405 var lambdas = this._getEndoRoots(this.n);
15406 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
15407 lambda = lambdas[0];
15408 } else {
15409 lambda = lambdas[1];
15410 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
15411 }
15412 }
15413
15414 // Get basis vectors, used for balanced length-two representation
15415 var basis;
15416 if (conf.basis) {
15417 basis = conf.basis.map(function(vec) {
15418 return {
15419 a: new BN(vec.a, 16),
15420 b: new BN(vec.b, 16)
15421 };
15422 });
15423 } else {
15424 basis = this._getEndoBasis(lambda);
15425 }
15426
15427 return {
15428 beta: beta,
15429 lambda: lambda,
15430 basis: basis
15431 };
15432};
15433
15434ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
15435 // Find roots of for x^2 + x + 1 in F
15436 // Root = (-1 +- Sqrt(-3)) / 2
15437 //
15438 var red = num === this.p ? this.red : BN.mont(num);
15439 var tinv = new BN(2).toRed(red).redInvm();
15440 var ntinv = tinv.redNeg();
15441
15442 var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
15443
15444 var l1 = ntinv.redAdd(s).fromRed();
15445 var l2 = ntinv.redSub(s).fromRed();
15446 return [ l1, l2 ];
15447};
15448
15449ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
15450 // aprxSqrt >= sqrt(this.n)
15451 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
15452
15453 // 3.74
15454 // Run EGCD, until r(L + 1) < aprxSqrt
15455 var u = lambda;
15456 var v = this.n.clone();
15457 var x1 = new BN(1);
15458 var y1 = new BN(0);
15459 var x2 = new BN(0);
15460 var y2 = new BN(1);
15461
15462 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
15463 var a0;
15464 var b0;
15465 // First vector
15466 var a1;
15467 var b1;
15468 // Second vector
15469 var a2;
15470 var b2;
15471
15472 var prevR;
15473 var i = 0;
15474 var r;
15475 var x;
15476 while (u.cmpn(0) !== 0) {
15477 var q = v.div(u);
15478 r = v.sub(q.mul(u));
15479 x = x2.sub(q.mul(x1));
15480 var y = y2.sub(q.mul(y1));
15481
15482 if (!a1 && r.cmp(aprxSqrt) < 0) {
15483 a0 = prevR.neg();
15484 b0 = x1;
15485 a1 = r.neg();
15486 b1 = x;
15487 } else if (a1 && ++i === 2) {
15488 break;
15489 }
15490 prevR = r;
15491
15492 v = u;
15493 u = r;
15494 x2 = x1;
15495 x1 = x;
15496 y2 = y1;
15497 y1 = y;
15498 }
15499 a2 = r.neg();
15500 b2 = x;
15501
15502 var len1 = a1.sqr().add(b1.sqr());
15503 var len2 = a2.sqr().add(b2.sqr());
15504 if (len2.cmp(len1) >= 0) {
15505 a2 = a0;
15506 b2 = b0;
15507 }
15508
15509 // Normalize signs
15510 if (a1.negative) {
15511 a1 = a1.neg();
15512 b1 = b1.neg();
15513 }
15514 if (a2.negative) {
15515 a2 = a2.neg();
15516 b2 = b2.neg();
15517 }
15518
15519 return [
15520 { a: a1, b: b1 },
15521 { a: a2, b: b2 }
15522 ];
15523};
15524
15525ShortCurve.prototype._endoSplit = function _endoSplit(k) {
15526 var basis = this.endo.basis;
15527 var v1 = basis[0];
15528 var v2 = basis[1];
15529
15530 var c1 = v2.b.mul(k).divRound(this.n);
15531 var c2 = v1.b.neg().mul(k).divRound(this.n);
15532
15533 var p1 = c1.mul(v1.a);
15534 var p2 = c2.mul(v2.a);
15535 var q1 = c1.mul(v1.b);
15536 var q2 = c2.mul(v2.b);
15537
15538 // Calculate answer
15539 var k1 = k.sub(p1).sub(p2);
15540 var k2 = q1.add(q2).neg();
15541 return { k1: k1, k2: k2 };
15542};
15543
15544ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
15545 x = new BN(x, 16);
15546 if (!x.red)
15547 x = x.toRed(this.red);
15548
15549 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
15550 var y = y2.redSqrt();
15551 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
15552 throw new Error('invalid point');
15553
15554 // XXX Is there any way to tell if the number is odd without converting it
15555 // to non-red form?
15556 var isOdd = y.fromRed().isOdd();
15557 if (odd && !isOdd || !odd && isOdd)
15558 y = y.redNeg();
15559
15560 return this.point(x, y);
15561};
15562
15563ShortCurve.prototype.validate = function validate(point) {
15564 if (point.inf)
15565 return true;
15566
15567 var x = point.x;
15568 var y = point.y;
15569
15570 var ax = this.a.redMul(x);
15571 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
15572 return y.redSqr().redISub(rhs).cmpn(0) === 0;
15573};
15574
15575ShortCurve.prototype._endoWnafMulAdd =
15576 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
15577 var npoints = this._endoWnafT1;
15578 var ncoeffs = this._endoWnafT2;
15579 for (var i = 0; i < points.length; i++) {
15580 var split = this._endoSplit(coeffs[i]);
15581 var p = points[i];
15582 var beta = p._getBeta();
15583
15584 if (split.k1.negative) {
15585 split.k1.ineg();
15586 p = p.neg(true);
15587 }
15588 if (split.k2.negative) {
15589 split.k2.ineg();
15590 beta = beta.neg(true);
15591 }
15592
15593 npoints[i * 2] = p;
15594 npoints[i * 2 + 1] = beta;
15595 ncoeffs[i * 2] = split.k1;
15596 ncoeffs[i * 2 + 1] = split.k2;
15597 }
15598 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
15599
15600 // Clean-up references to points and coefficients
15601 for (var j = 0; j < i * 2; j++) {
15602 npoints[j] = null;
15603 ncoeffs[j] = null;
15604 }
15605 return res;
15606};
15607
15608function Point(curve, x, y, isRed) {
15609 Base.BasePoint.call(this, curve, 'affine');
15610 if (x === null && y === null) {
15611 this.x = null;
15612 this.y = null;
15613 this.inf = true;
15614 } else {
15615 this.x = new BN(x, 16);
15616 this.y = new BN(y, 16);
15617 // Force redgomery representation when loading from JSON
15618 if (isRed) {
15619 this.x.forceRed(this.curve.red);
15620 this.y.forceRed(this.curve.red);
15621 }
15622 if (!this.x.red)
15623 this.x = this.x.toRed(this.curve.red);
15624 if (!this.y.red)
15625 this.y = this.y.toRed(this.curve.red);
15626 this.inf = false;
15627 }
15628}
15629inherits(Point, Base.BasePoint);
15630
15631ShortCurve.prototype.point = function point(x, y, isRed) {
15632 return new Point(this, x, y, isRed);
15633};
15634
15635ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
15636 return Point.fromJSON(this, obj, red);
15637};
15638
15639Point.prototype._getBeta = function _getBeta() {
15640 if (!this.curve.endo)
15641 return;
15642
15643 var pre = this.precomputed;
15644 if (pre && pre.beta)
15645 return pre.beta;
15646
15647 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
15648 if (pre) {
15649 var curve = this.curve;
15650 var endoMul = function(p) {
15651 return curve.point(p.x.redMul(curve.endo.beta), p.y);
15652 };
15653 pre.beta = beta;
15654 beta.precomputed = {
15655 beta: null,
15656 naf: pre.naf && {
15657 wnd: pre.naf.wnd,
15658 points: pre.naf.points.map(endoMul)
15659 },
15660 doubles: pre.doubles && {
15661 step: pre.doubles.step,
15662 points: pre.doubles.points.map(endoMul)
15663 }
15664 };
15665 }
15666 return beta;
15667};
15668
15669Point.prototype.toJSON = function toJSON() {
15670 if (!this.precomputed)
15671 return [ this.x, this.y ];
15672
15673 return [ this.x, this.y, this.precomputed && {
15674 doubles: this.precomputed.doubles && {
15675 step: this.precomputed.doubles.step,
15676 points: this.precomputed.doubles.points.slice(1)
15677 },
15678 naf: this.precomputed.naf && {
15679 wnd: this.precomputed.naf.wnd,
15680 points: this.precomputed.naf.points.slice(1)
15681 }
15682 } ];
15683};
15684
15685Point.fromJSON = function fromJSON(curve, obj, red) {
15686 if (typeof obj === 'string')
15687 obj = JSON.parse(obj);
15688 var res = curve.point(obj[0], obj[1], red);
15689 if (!obj[2])
15690 return res;
15691
15692 function obj2point(obj) {
15693 return curve.point(obj[0], obj[1], red);
15694 }
15695
15696 var pre = obj[2];
15697 res.precomputed = {
15698 beta: null,
15699 doubles: pre.doubles && {
15700 step: pre.doubles.step,
15701 points: [ res ].concat(pre.doubles.points.map(obj2point))
15702 },
15703 naf: pre.naf && {
15704 wnd: pre.naf.wnd,
15705 points: [ res ].concat(pre.naf.points.map(obj2point))
15706 }
15707 };
15708 return res;
15709};
15710
15711Point.prototype.inspect = function inspect() {
15712 if (this.isInfinity())
15713 return '<EC Point Infinity>';
15714 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
15715 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
15716};
15717
15718Point.prototype.isInfinity = function isInfinity() {
15719 return this.inf;
15720};
15721
15722Point.prototype.add = function add(p) {
15723 // O + P = P
15724 if (this.inf)
15725 return p;
15726
15727 // P + O = P
15728 if (p.inf)
15729 return this;
15730
15731 // P + P = 2P
15732 if (this.eq(p))
15733 return this.dbl();
15734
15735 // P + (-P) = O
15736 if (this.neg().eq(p))
15737 return this.curve.point(null, null);
15738
15739 // P + Q = O
15740 if (this.x.cmp(p.x) === 0)
15741 return this.curve.point(null, null);
15742
15743 var c = this.y.redSub(p.y);
15744 if (c.cmpn(0) !== 0)
15745 c = c.redMul(this.x.redSub(p.x).redInvm());
15746 var nx = c.redSqr().redISub(this.x).redISub(p.x);
15747 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
15748 return this.curve.point(nx, ny);
15749};
15750
15751Point.prototype.dbl = function dbl() {
15752 if (this.inf)
15753 return this;
15754
15755 // 2P = O
15756 var ys1 = this.y.redAdd(this.y);
15757 if (ys1.cmpn(0) === 0)
15758 return this.curve.point(null, null);
15759
15760 var a = this.curve.a;
15761
15762 var x2 = this.x.redSqr();
15763 var dyinv = ys1.redInvm();
15764 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
15765
15766 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
15767 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
15768 return this.curve.point(nx, ny);
15769};
15770
15771Point.prototype.getX = function getX() {
15772 return this.x.fromRed();
15773};
15774
15775Point.prototype.getY = function getY() {
15776 return this.y.fromRed();
15777};
15778
15779Point.prototype.mul = function mul(k) {
15780 k = new BN(k, 16);
15781
15782 if (this._hasDoubles(k))
15783 return this.curve._fixedNafMul(this, k);
15784 else if (this.curve.endo)
15785 return this.curve._endoWnafMulAdd([ this ], [ k ]);
15786 else
15787 return this.curve._wnafMul(this, k);
15788};
15789
15790Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
15791 var points = [ this, p2 ];
15792 var coeffs = [ k1, k2 ];
15793 if (this.curve.endo)
15794 return this.curve._endoWnafMulAdd(points, coeffs);
15795 else
15796 return this.curve._wnafMulAdd(1, points, coeffs, 2);
15797};
15798
15799Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
15800 var points = [ this, p2 ];
15801 var coeffs = [ k1, k2 ];
15802 if (this.curve.endo)
15803 return this.curve._endoWnafMulAdd(points, coeffs, true);
15804 else
15805 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
15806};
15807
15808Point.prototype.eq = function eq(p) {
15809 return this === p ||
15810 this.inf === p.inf &&
15811 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
15812};
15813
15814Point.prototype.neg = function neg(_precompute) {
15815 if (this.inf)
15816 return this;
15817
15818 var res = this.curve.point(this.x, this.y.redNeg());
15819 if (_precompute && this.precomputed) {
15820 var pre = this.precomputed;
15821 var negate = function(p) {
15822 return p.neg();
15823 };
15824 res.precomputed = {
15825 naf: pre.naf && {
15826 wnd: pre.naf.wnd,
15827 points: pre.naf.points.map(negate)
15828 },
15829 doubles: pre.doubles && {
15830 step: pre.doubles.step,
15831 points: pre.doubles.points.map(negate)
15832 }
15833 };
15834 }
15835 return res;
15836};
15837
15838Point.prototype.toJ = function toJ() {
15839 if (this.inf)
15840 return this.curve.jpoint(null, null, null);
15841
15842 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
15843 return res;
15844};
15845
15846function JPoint(curve, x, y, z) {
15847 Base.BasePoint.call(this, curve, 'jacobian');
15848 if (x === null && y === null && z === null) {
15849 this.x = this.curve.one;
15850 this.y = this.curve.one;
15851 this.z = new BN(0);
15852 } else {
15853 this.x = new BN(x, 16);
15854 this.y = new BN(y, 16);
15855 this.z = new BN(z, 16);
15856 }
15857 if (!this.x.red)
15858 this.x = this.x.toRed(this.curve.red);
15859 if (!this.y.red)
15860 this.y = this.y.toRed(this.curve.red);
15861 if (!this.z.red)
15862 this.z = this.z.toRed(this.curve.red);
15863
15864 this.zOne = this.z === this.curve.one;
15865}
15866inherits(JPoint, Base.BasePoint);
15867
15868ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
15869 return new JPoint(this, x, y, z);
15870};
15871
15872JPoint.prototype.toP = function toP() {
15873 if (this.isInfinity())
15874 return this.curve.point(null, null);
15875
15876 var zinv = this.z.redInvm();
15877 var zinv2 = zinv.redSqr();
15878 var ax = this.x.redMul(zinv2);
15879 var ay = this.y.redMul(zinv2).redMul(zinv);
15880
15881 return this.curve.point(ax, ay);
15882};
15883
15884JPoint.prototype.neg = function neg() {
15885 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
15886};
15887
15888JPoint.prototype.add = function add(p) {
15889 // O + P = P
15890 if (this.isInfinity())
15891 return p;
15892
15893 // P + O = P
15894 if (p.isInfinity())
15895 return this;
15896
15897 // 12M + 4S + 7A
15898 var pz2 = p.z.redSqr();
15899 var z2 = this.z.redSqr();
15900 var u1 = this.x.redMul(pz2);
15901 var u2 = p.x.redMul(z2);
15902 var s1 = this.y.redMul(pz2.redMul(p.z));
15903 var s2 = p.y.redMul(z2.redMul(this.z));
15904
15905 var h = u1.redSub(u2);
15906 var r = s1.redSub(s2);
15907 if (h.cmpn(0) === 0) {
15908 if (r.cmpn(0) !== 0)
15909 return this.curve.jpoint(null, null, null);
15910 else
15911 return this.dbl();
15912 }
15913
15914 var h2 = h.redSqr();
15915 var h3 = h2.redMul(h);
15916 var v = u1.redMul(h2);
15917
15918 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
15919 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
15920 var nz = this.z.redMul(p.z).redMul(h);
15921
15922 return this.curve.jpoint(nx, ny, nz);
15923};
15924
15925JPoint.prototype.mixedAdd = function mixedAdd(p) {
15926 // O + P = P
15927 if (this.isInfinity())
15928 return p.toJ();
15929
15930 // P + O = P
15931 if (p.isInfinity())
15932 return this;
15933
15934 // 8M + 3S + 7A
15935 var z2 = this.z.redSqr();
15936 var u1 = this.x;
15937 var u2 = p.x.redMul(z2);
15938 var s1 = this.y;
15939 var s2 = p.y.redMul(z2).redMul(this.z);
15940
15941 var h = u1.redSub(u2);
15942 var r = s1.redSub(s2);
15943 if (h.cmpn(0) === 0) {
15944 if (r.cmpn(0) !== 0)
15945 return this.curve.jpoint(null, null, null);
15946 else
15947 return this.dbl();
15948 }
15949
15950 var h2 = h.redSqr();
15951 var h3 = h2.redMul(h);
15952 var v = u1.redMul(h2);
15953
15954 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
15955 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
15956 var nz = this.z.redMul(h);
15957
15958 return this.curve.jpoint(nx, ny, nz);
15959};
15960
15961JPoint.prototype.dblp = function dblp(pow) {
15962 if (pow === 0)
15963 return this;
15964 if (this.isInfinity())
15965 return this;
15966 if (!pow)
15967 return this.dbl();
15968
15969 if (this.curve.zeroA || this.curve.threeA) {
15970 var r = this;
15971 for (var i = 0; i < pow; i++)
15972 r = r.dbl();
15973 return r;
15974 }
15975
15976 // 1M + 2S + 1A + N * (4S + 5M + 8A)
15977 // N = 1 => 6M + 6S + 9A
15978 var a = this.curve.a;
15979 var tinv = this.curve.tinv;
15980
15981 var jx = this.x;
15982 var jy = this.y;
15983 var jz = this.z;
15984 var jz4 = jz.redSqr().redSqr();
15985
15986 // Reuse results
15987 var jyd = jy.redAdd(jy);
15988 for (var i = 0; i < pow; i++) {
15989 var jx2 = jx.redSqr();
15990 var jyd2 = jyd.redSqr();
15991 var jyd4 = jyd2.redSqr();
15992 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
15993
15994 var t1 = jx.redMul(jyd2);
15995 var nx = c.redSqr().redISub(t1.redAdd(t1));
15996 var t2 = t1.redISub(nx);
15997 var dny = c.redMul(t2);
15998 dny = dny.redIAdd(dny).redISub(jyd4);
15999 var nz = jyd.redMul(jz);
16000 if (i + 1 < pow)
16001 jz4 = jz4.redMul(jyd4);
16002
16003 jx = nx;
16004 jz = nz;
16005 jyd = dny;
16006 }
16007
16008 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
16009};
16010
16011JPoint.prototype.dbl = function dbl() {
16012 if (this.isInfinity())
16013 return this;
16014
16015 if (this.curve.zeroA)
16016 return this._zeroDbl();
16017 else if (this.curve.threeA)
16018 return this._threeDbl();
16019 else
16020 return this._dbl();
16021};
16022
16023JPoint.prototype._zeroDbl = function _zeroDbl() {
16024 var nx;
16025 var ny;
16026 var nz;
16027 // Z = 1
16028 if (this.zOne) {
16029 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
16030 // #doubling-mdbl-2007-bl
16031 // 1M + 5S + 14A
16032
16033 // XX = X1^2
16034 var xx = this.x.redSqr();
16035 // YY = Y1^2
16036 var yy = this.y.redSqr();
16037 // YYYY = YY^2
16038 var yyyy = yy.redSqr();
16039 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
16040 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
16041 s = s.redIAdd(s);
16042 // M = 3 * XX + a; a = 0
16043 var m = xx.redAdd(xx).redIAdd(xx);
16044 // T = M ^ 2 - 2*S
16045 var t = m.redSqr().redISub(s).redISub(s);
16046
16047 // 8 * YYYY
16048 var yyyy8 = yyyy.redIAdd(yyyy);
16049 yyyy8 = yyyy8.redIAdd(yyyy8);
16050 yyyy8 = yyyy8.redIAdd(yyyy8);
16051
16052 // X3 = T
16053 nx = t;
16054 // Y3 = M * (S - T) - 8 * YYYY
16055 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
16056 // Z3 = 2*Y1
16057 nz = this.y.redAdd(this.y);
16058 } else {
16059 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
16060 // #doubling-dbl-2009-l
16061 // 2M + 5S + 13A
16062
16063 // A = X1^2
16064 var a = this.x.redSqr();
16065 // B = Y1^2
16066 var b = this.y.redSqr();
16067 // C = B^2
16068 var c = b.redSqr();
16069 // D = 2 * ((X1 + B)^2 - A - C)
16070 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
16071 d = d.redIAdd(d);
16072 // E = 3 * A
16073 var e = a.redAdd(a).redIAdd(a);
16074 // F = E^2
16075 var f = e.redSqr();
16076
16077 // 8 * C
16078 var c8 = c.redIAdd(c);
16079 c8 = c8.redIAdd(c8);
16080 c8 = c8.redIAdd(c8);
16081
16082 // X3 = F - 2 * D
16083 nx = f.redISub(d).redISub(d);
16084 // Y3 = E * (D - X3) - 8 * C
16085 ny = e.redMul(d.redISub(nx)).redISub(c8);
16086 // Z3 = 2 * Y1 * Z1
16087 nz = this.y.redMul(this.z);
16088 nz = nz.redIAdd(nz);
16089 }
16090
16091 return this.curve.jpoint(nx, ny, nz);
16092};
16093
16094JPoint.prototype._threeDbl = function _threeDbl() {
16095 var nx;
16096 var ny;
16097 var nz;
16098 // Z = 1
16099 if (this.zOne) {
16100 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
16101 // #doubling-mdbl-2007-bl
16102 // 1M + 5S + 15A
16103
16104 // XX = X1^2
16105 var xx = this.x.redSqr();
16106 // YY = Y1^2
16107 var yy = this.y.redSqr();
16108 // YYYY = YY^2
16109 var yyyy = yy.redSqr();
16110 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
16111 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
16112 s = s.redIAdd(s);
16113 // M = 3 * XX + a
16114 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
16115 // T = M^2 - 2 * S
16116 var t = m.redSqr().redISub(s).redISub(s);
16117 // X3 = T
16118 nx = t;
16119 // Y3 = M * (S - T) - 8 * YYYY
16120 var yyyy8 = yyyy.redIAdd(yyyy);
16121 yyyy8 = yyyy8.redIAdd(yyyy8);
16122 yyyy8 = yyyy8.redIAdd(yyyy8);
16123 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
16124 // Z3 = 2 * Y1
16125 nz = this.y.redAdd(this.y);
16126 } else {
16127 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
16128 // 3M + 5S
16129
16130 // delta = Z1^2
16131 var delta = this.z.redSqr();
16132 // gamma = Y1^2
16133 var gamma = this.y.redSqr();
16134 // beta = X1 * gamma
16135 var beta = this.x.redMul(gamma);
16136 // alpha = 3 * (X1 - delta) * (X1 + delta)
16137 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
16138 alpha = alpha.redAdd(alpha).redIAdd(alpha);
16139 // X3 = alpha^2 - 8 * beta
16140 var beta4 = beta.redIAdd(beta);
16141 beta4 = beta4.redIAdd(beta4);
16142 var beta8 = beta4.redAdd(beta4);
16143 nx = alpha.redSqr().redISub(beta8);
16144 // Z3 = (Y1 + Z1)^2 - gamma - delta
16145 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
16146 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
16147 var ggamma8 = gamma.redSqr();
16148 ggamma8 = ggamma8.redIAdd(ggamma8);
16149 ggamma8 = ggamma8.redIAdd(ggamma8);
16150 ggamma8 = ggamma8.redIAdd(ggamma8);
16151 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
16152 }
16153
16154 return this.curve.jpoint(nx, ny, nz);
16155};
16156
16157JPoint.prototype._dbl = function _dbl() {
16158 var a = this.curve.a;
16159
16160 // 4M + 6S + 10A
16161 var jx = this.x;
16162 var jy = this.y;
16163 var jz = this.z;
16164 var jz4 = jz.redSqr().redSqr();
16165
16166 var jx2 = jx.redSqr();
16167 var jy2 = jy.redSqr();
16168
16169 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
16170
16171 var jxd4 = jx.redAdd(jx);
16172 jxd4 = jxd4.redIAdd(jxd4);
16173 var t1 = jxd4.redMul(jy2);
16174 var nx = c.redSqr().redISub(t1.redAdd(t1));
16175 var t2 = t1.redISub(nx);
16176
16177 var jyd8 = jy2.redSqr();
16178 jyd8 = jyd8.redIAdd(jyd8);
16179 jyd8 = jyd8.redIAdd(jyd8);
16180 jyd8 = jyd8.redIAdd(jyd8);
16181 var ny = c.redMul(t2).redISub(jyd8);
16182 var nz = jy.redAdd(jy).redMul(jz);
16183
16184 return this.curve.jpoint(nx, ny, nz);
16185};
16186
16187JPoint.prototype.trpl = function trpl() {
16188 if (!this.curve.zeroA)
16189 return this.dbl().add(this);
16190
16191 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
16192 // 5M + 10S + ...
16193
16194 // XX = X1^2
16195 var xx = this.x.redSqr();
16196 // YY = Y1^2
16197 var yy = this.y.redSqr();
16198 // ZZ = Z1^2
16199 var zz = this.z.redSqr();
16200 // YYYY = YY^2
16201 var yyyy = yy.redSqr();
16202 // M = 3 * XX + a * ZZ2; a = 0
16203 var m = xx.redAdd(xx).redIAdd(xx);
16204 // MM = M^2
16205 var mm = m.redSqr();
16206 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
16207 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
16208 e = e.redIAdd(e);
16209 e = e.redAdd(e).redIAdd(e);
16210 e = e.redISub(mm);
16211 // EE = E^2
16212 var ee = e.redSqr();
16213 // T = 16*YYYY
16214 var t = yyyy.redIAdd(yyyy);
16215 t = t.redIAdd(t);
16216 t = t.redIAdd(t);
16217 t = t.redIAdd(t);
16218 // U = (M + E)^2 - MM - EE - T
16219 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
16220 // X3 = 4 * (X1 * EE - 4 * YY * U)
16221 var yyu4 = yy.redMul(u);
16222 yyu4 = yyu4.redIAdd(yyu4);
16223 yyu4 = yyu4.redIAdd(yyu4);
16224 var nx = this.x.redMul(ee).redISub(yyu4);
16225 nx = nx.redIAdd(nx);
16226 nx = nx.redIAdd(nx);
16227 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
16228 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
16229 ny = ny.redIAdd(ny);
16230 ny = ny.redIAdd(ny);
16231 ny = ny.redIAdd(ny);
16232 // Z3 = (Z1 + E)^2 - ZZ - EE
16233 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
16234
16235 return this.curve.jpoint(nx, ny, nz);
16236};
16237
16238JPoint.prototype.mul = function mul(k, kbase) {
16239 k = new BN(k, kbase);
16240
16241 return this.curve._wnafMul(this, k);
16242};
16243
16244JPoint.prototype.eq = function eq(p) {
16245 if (p.type === 'affine')
16246 return this.eq(p.toJ());
16247
16248 if (this === p)
16249 return true;
16250
16251 // x1 * z2^2 == x2 * z1^2
16252 var z2 = this.z.redSqr();
16253 var pz2 = p.z.redSqr();
16254 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
16255 return false;
16256
16257 // y1 * z2^3 == y2 * z1^3
16258 var z3 = z2.redMul(this.z);
16259 var pz3 = pz2.redMul(p.z);
16260 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
16261};
16262
16263JPoint.prototype.eqXToP = function eqXToP(x) {
16264 var zs = this.z.redSqr();
16265 var rx = x.toRed(this.curve.red).redMul(zs);
16266 if (this.x.cmp(rx) === 0)
16267 return true;
16268
16269 var xc = x.clone();
16270 var t = this.curve.redN.redMul(zs);
16271 for (;;) {
16272 xc.iadd(this.curve.n);
16273 if (xc.cmp(this.curve.p) >= 0)
16274 return false;
16275
16276 rx.redIAdd(t);
16277 if (this.x.cmp(rx) === 0)
16278 return true;
16279 }
16280};
16281
16282JPoint.prototype.inspect = function inspect() {
16283 if (this.isInfinity())
16284 return '<EC JPoint Infinity>';
16285 return '<EC JPoint x: ' + this.x.toString(16, 2) +
16286 ' y: ' + this.y.toString(16, 2) +
16287 ' z: ' + this.z.toString(16, 2) + '>';
16288};
16289
16290JPoint.prototype.isInfinity = function isInfinity() {
16291 // XXX This code assumes that zero is always zero in red
16292 return this.z.cmpn(0) === 0;
16293};
16294
16295},{"../../elliptic":83,"../curve":86,"bn.js":18,"inherits":116}],89:[function(require,module,exports){
16296'use strict';
16297
16298var curves = exports;
16299
16300var hash = require('hash.js');
16301var elliptic = require('../elliptic');
16302
16303var assert = elliptic.utils.assert;
16304
16305function PresetCurve(options) {
16306 if (options.type === 'short')
16307 this.curve = new elliptic.curve.short(options);
16308 else if (options.type === 'edwards')
16309 this.curve = new elliptic.curve.edwards(options);
16310 else
16311 this.curve = new elliptic.curve.mont(options);
16312 this.g = this.curve.g;
16313 this.n = this.curve.n;
16314 this.hash = options.hash;
16315
16316 assert(this.g.validate(), 'Invalid curve');
16317 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
16318}
16319curves.PresetCurve = PresetCurve;
16320
16321function defineCurve(name, options) {
16322 Object.defineProperty(curves, name, {
16323 configurable: true,
16324 enumerable: true,
16325 get: function() {
16326 var curve = new PresetCurve(options);
16327 Object.defineProperty(curves, name, {
16328 configurable: true,
16329 enumerable: true,
16330 value: curve
16331 });
16332 return curve;
16333 }
16334 });
16335}
16336
16337defineCurve('p192', {
16338 type: 'short',
16339 prime: 'p192',
16340 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
16341 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
16342 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
16343 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
16344 hash: hash.sha256,
16345 gRed: false,
16346 g: [
16347 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
16348 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
16349 ]
16350});
16351
16352defineCurve('p224', {
16353 type: 'short',
16354 prime: 'p224',
16355 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
16356 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
16357 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
16358 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
16359 hash: hash.sha256,
16360 gRed: false,
16361 g: [
16362 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
16363 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
16364 ]
16365});
16366
16367defineCurve('p256', {
16368 type: 'short',
16369 prime: null,
16370 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
16371 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
16372 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
16373 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
16374 hash: hash.sha256,
16375 gRed: false,
16376 g: [
16377 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
16378 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
16379 ]
16380});
16381
16382defineCurve('p384', {
16383 type: 'short',
16384 prime: null,
16385 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16386 'fffffffe ffffffff 00000000 00000000 ffffffff',
16387 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16388 'fffffffe ffffffff 00000000 00000000 fffffffc',
16389 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
16390 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
16391 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
16392 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
16393 hash: hash.sha384,
16394 gRed: false,
16395 g: [
16396 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
16397 '5502f25d bf55296c 3a545e38 72760ab7',
16398 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
16399 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
16400 ]
16401});
16402
16403defineCurve('p521', {
16404 type: 'short',
16405 prime: null,
16406 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16407 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16408 'ffffffff ffffffff ffffffff ffffffff ffffffff',
16409 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16410 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16411 'ffffffff ffffffff ffffffff ffffffff fffffffc',
16412 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
16413 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
16414 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
16415 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
16416 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
16417 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
16418 hash: hash.sha512,
16419 gRed: false,
16420 g: [
16421 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
16422 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
16423 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
16424 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
16425 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
16426 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
16427 ]
16428});
16429
16430defineCurve('curve25519', {
16431 type: 'mont',
16432 prime: 'p25519',
16433 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
16434 a: '76d06',
16435 b: '1',
16436 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
16437 hash: hash.sha256,
16438 gRed: false,
16439 g: [
16440 '9'
16441 ]
16442});
16443
16444defineCurve('ed25519', {
16445 type: 'edwards',
16446 prime: 'p25519',
16447 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
16448 a: '-1',
16449 c: '1',
16450 // -121665 * (121666^(-1)) (mod P)
16451 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
16452 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
16453 hash: hash.sha256,
16454 gRed: false,
16455 g: [
16456 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
16457
16458 // 4/5
16459 '6666666666666666666666666666666666666666666666666666666666666658'
16460 ]
16461});
16462
16463var pre;
16464try {
16465 pre = require('./precomputed/secp256k1');
16466} catch (e) {
16467 pre = undefined;
16468}
16469
16470defineCurve('secp256k1', {
16471 type: 'short',
16472 prime: 'k256',
16473 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
16474 a: '0',
16475 b: '7',
16476 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
16477 h: '1',
16478 hash: hash.sha256,
16479
16480 // Precomputed endomorphism
16481 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
16482 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
16483 basis: [
16484 {
16485 a: '3086d221a7d46bcde86c90e49284eb15',
16486 b: '-e4437ed6010e88286f547fa90abfe4c3'
16487 },
16488 {
16489 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
16490 b: '3086d221a7d46bcde86c90e49284eb15'
16491 }
16492 ],
16493
16494 gRed: false,
16495 g: [
16496 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
16497 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
16498 pre
16499 ]
16500});
16501
16502},{"../elliptic":83,"./precomputed/secp256k1":96,"hash.js":102}],90:[function(require,module,exports){
16503'use strict';
16504
16505var BN = require('bn.js');
16506var HmacDRBG = require('hmac-drbg');
16507var elliptic = require('../../elliptic');
16508var utils = elliptic.utils;
16509var assert = utils.assert;
16510
16511var KeyPair = require('./key');
16512var Signature = require('./signature');
16513
16514function EC(options) {
16515 if (!(this instanceof EC))
16516 return new EC(options);
16517
16518 // Shortcut `elliptic.ec(curve-name)`
16519 if (typeof options === 'string') {
16520 assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
16521
16522 options = elliptic.curves[options];
16523 }
16524
16525 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
16526 if (options instanceof elliptic.curves.PresetCurve)
16527 options = { curve: options };
16528
16529 this.curve = options.curve.curve;
16530 this.n = this.curve.n;
16531 this.nh = this.n.ushrn(1);
16532 this.g = this.curve.g;
16533
16534 // Point on curve
16535 this.g = options.curve.g;
16536 this.g.precompute(options.curve.n.bitLength() + 1);
16537
16538 // Hash for function for DRBG
16539 this.hash = options.hash || options.curve.hash;
16540}
16541module.exports = EC;
16542
16543EC.prototype.keyPair = function keyPair(options) {
16544 return new KeyPair(this, options);
16545};
16546
16547EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
16548 return KeyPair.fromPrivate(this, priv, enc);
16549};
16550
16551EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
16552 return KeyPair.fromPublic(this, pub, enc);
16553};
16554
16555EC.prototype.genKeyPair = function genKeyPair(options) {
16556 if (!options)
16557 options = {};
16558
16559 // Instantiate Hmac_DRBG
16560 var drbg = new HmacDRBG({
16561 hash: this.hash,
16562 pers: options.pers,
16563 persEnc: options.persEnc || 'utf8',
16564 entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
16565 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
16566 nonce: this.n.toArray()
16567 });
16568
16569 var bytes = this.n.byteLength();
16570 var ns2 = this.n.sub(new BN(2));
16571 do {
16572 var priv = new BN(drbg.generate(bytes));
16573 if (priv.cmp(ns2) > 0)
16574 continue;
16575
16576 priv.iaddn(1);
16577 return this.keyFromPrivate(priv);
16578 } while (true);
16579};
16580
16581EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
16582 var delta = msg.byteLength() * 8 - this.n.bitLength();
16583 if (delta > 0)
16584 msg = msg.ushrn(delta);
16585 if (!truncOnly && msg.cmp(this.n) >= 0)
16586 return msg.sub(this.n);
16587 else
16588 return msg;
16589};
16590
16591EC.prototype.sign = function sign(msg, key, enc, options) {
16592 if (typeof enc === 'object') {
16593 options = enc;
16594 enc = null;
16595 }
16596 if (!options)
16597 options = {};
16598
16599 key = this.keyFromPrivate(key, enc);
16600 msg = this._truncateToN(new BN(msg, 16));
16601
16602 // Zero-extend key to provide enough entropy
16603 var bytes = this.n.byteLength();
16604 var bkey = key.getPrivate().toArray('be', bytes);
16605
16606 // Zero-extend nonce to have the same byte size as N
16607 var nonce = msg.toArray('be', bytes);
16608
16609 // Instantiate Hmac_DRBG
16610 var drbg = new HmacDRBG({
16611 hash: this.hash,
16612 entropy: bkey,
16613 nonce: nonce,
16614 pers: options.pers,
16615 persEnc: options.persEnc || 'utf8'
16616 });
16617
16618 // Number of bytes to generate
16619 var ns1 = this.n.sub(new BN(1));
16620
16621 for (var iter = 0; true; iter++) {
16622 var k = options.k ?
16623 options.k(iter) :
16624 new BN(drbg.generate(this.n.byteLength()));
16625 k = this._truncateToN(k, true);
16626 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
16627 continue;
16628
16629 var kp = this.g.mul(k);
16630 if (kp.isInfinity())
16631 continue;
16632
16633 var kpX = kp.getX();
16634 var r = kpX.umod(this.n);
16635 if (r.cmpn(0) === 0)
16636 continue;
16637
16638 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
16639 s = s.umod(this.n);
16640 if (s.cmpn(0) === 0)
16641 continue;
16642
16643 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
16644 (kpX.cmp(r) !== 0 ? 2 : 0);
16645
16646 // Use complement of `s`, if it is > `n / 2`
16647 if (options.canonical && s.cmp(this.nh) > 0) {
16648 s = this.n.sub(s);
16649 recoveryParam ^= 1;
16650 }
16651
16652 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
16653 }
16654};
16655
16656EC.prototype.verify = function verify(msg, signature, key, enc) {
16657 msg = this._truncateToN(new BN(msg, 16));
16658 key = this.keyFromPublic(key, enc);
16659 signature = new Signature(signature, 'hex');
16660
16661 // Perform primitive values validation
16662 var r = signature.r;
16663 var s = signature.s;
16664 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
16665 return false;
16666 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
16667 return false;
16668
16669 // Validate signature
16670 var sinv = s.invm(this.n);
16671 var u1 = sinv.mul(msg).umod(this.n);
16672 var u2 = sinv.mul(r).umod(this.n);
16673
16674 if (!this.curve._maxwellTrick) {
16675 var p = this.g.mulAdd(u1, key.getPublic(), u2);
16676 if (p.isInfinity())
16677 return false;
16678
16679 return p.getX().umod(this.n).cmp(r) === 0;
16680 }
16681
16682 // NOTE: Greg Maxwell's trick, inspired by:
16683 // https://git.io/vad3K
16684
16685 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
16686 if (p.isInfinity())
16687 return false;
16688
16689 // Compare `p.x` of Jacobian point with `r`,
16690 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
16691 // inverse of `p.z^2`
16692 return p.eqXToP(r);
16693};
16694
16695EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
16696 assert((3 & j) === j, 'The recovery param is more than two bits');
16697 signature = new Signature(signature, enc);
16698
16699 var n = this.n;
16700 var e = new BN(msg);
16701 var r = signature.r;
16702 var s = signature.s;
16703
16704 // A set LSB signifies that the y-coordinate is odd
16705 var isYOdd = j & 1;
16706 var isSecondKey = j >> 1;
16707 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
16708 throw new Error('Unable to find sencond key candinate');
16709
16710 // 1.1. Let x = r + jn.
16711 if (isSecondKey)
16712 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
16713 else
16714 r = this.curve.pointFromX(r, isYOdd);
16715
16716 var rInv = signature.r.invm(n);
16717 var s1 = n.sub(e).mul(rInv).umod(n);
16718 var s2 = s.mul(rInv).umod(n);
16719
16720 // 1.6.1 Compute Q = r^-1 (sR - eG)
16721 // Q = r^-1 (sR + -eG)
16722 return this.g.mulAdd(s1, r, s2);
16723};
16724
16725EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
16726 signature = new Signature(signature, enc);
16727 if (signature.recoveryParam !== null)
16728 return signature.recoveryParam;
16729
16730 for (var i = 0; i < 4; i++) {
16731 var Qprime;
16732 try {
16733 Qprime = this.recoverPubKey(e, signature, i);
16734 } catch (e) {
16735 continue;
16736 }
16737
16738 if (Qprime.eq(Q))
16739 return i;
16740 }
16741 throw new Error('Unable to find valid recovery factor');
16742};
16743
16744},{"../../elliptic":83,"./key":91,"./signature":92,"bn.js":18,"hmac-drbg":114}],91:[function(require,module,exports){
16745'use strict';
16746
16747var BN = require('bn.js');
16748var elliptic = require('../../elliptic');
16749var utils = elliptic.utils;
16750var assert = utils.assert;
16751
16752function KeyPair(ec, options) {
16753 this.ec = ec;
16754 this.priv = null;
16755 this.pub = null;
16756
16757 // KeyPair(ec, { priv: ..., pub: ... })
16758 if (options.priv)
16759 this._importPrivate(options.priv, options.privEnc);
16760 if (options.pub)
16761 this._importPublic(options.pub, options.pubEnc);
16762}
16763module.exports = KeyPair;
16764
16765KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
16766 if (pub instanceof KeyPair)
16767 return pub;
16768
16769 return new KeyPair(ec, {
16770 pub: pub,
16771 pubEnc: enc
16772 });
16773};
16774
16775KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
16776 if (priv instanceof KeyPair)
16777 return priv;
16778
16779 return new KeyPair(ec, {
16780 priv: priv,
16781 privEnc: enc
16782 });
16783};
16784
16785KeyPair.prototype.validate = function validate() {
16786 var pub = this.getPublic();
16787
16788 if (pub.isInfinity())
16789 return { result: false, reason: 'Invalid public key' };
16790 if (!pub.validate())
16791 return { result: false, reason: 'Public key is not a point' };
16792 if (!pub.mul(this.ec.curve.n).isInfinity())
16793 return { result: false, reason: 'Public key * N != O' };
16794
16795 return { result: true, reason: null };
16796};
16797
16798KeyPair.prototype.getPublic = function getPublic(compact, enc) {
16799 // compact is optional argument
16800 if (typeof compact === 'string') {
16801 enc = compact;
16802 compact = null;
16803 }
16804
16805 if (!this.pub)
16806 this.pub = this.ec.g.mul(this.priv);
16807
16808 if (!enc)
16809 return this.pub;
16810
16811 return this.pub.encode(enc, compact);
16812};
16813
16814KeyPair.prototype.getPrivate = function getPrivate(enc) {
16815 if (enc === 'hex')
16816 return this.priv.toString(16, 2);
16817 else
16818 return this.priv;
16819};
16820
16821KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
16822 this.priv = new BN(key, enc || 16);
16823
16824 // Ensure that the priv won't be bigger than n, otherwise we may fail
16825 // in fixed multiplication method
16826 this.priv = this.priv.umod(this.ec.curve.n);
16827};
16828
16829KeyPair.prototype._importPublic = function _importPublic(key, enc) {
16830 if (key.x || key.y) {
16831 // Montgomery points only have an `x` coordinate.
16832 // Weierstrass/Edwards points on the other hand have both `x` and
16833 // `y` coordinates.
16834 if (this.ec.curve.type === 'mont') {
16835 assert(key.x, 'Need x coordinate');
16836 } else if (this.ec.curve.type === 'short' ||
16837 this.ec.curve.type === 'edwards') {
16838 assert(key.x && key.y, 'Need both x and y coordinate');
16839 }
16840 this.pub = this.ec.curve.point(key.x, key.y);
16841 return;
16842 }
16843 this.pub = this.ec.curve.decodePoint(key, enc);
16844};
16845
16846// ECDH
16847KeyPair.prototype.derive = function derive(pub) {
16848 return pub.mul(this.priv).getX();
16849};
16850
16851// ECDSA
16852KeyPair.prototype.sign = function sign(msg, enc, options) {
16853 return this.ec.sign(msg, this, enc, options);
16854};
16855
16856KeyPair.prototype.verify = function verify(msg, signature) {
16857 return this.ec.verify(msg, signature, this);
16858};
16859
16860KeyPair.prototype.inspect = function inspect() {
16861 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
16862 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
16863};
16864
16865},{"../../elliptic":83,"bn.js":18}],92:[function(require,module,exports){
16866'use strict';
16867
16868var BN = require('bn.js');
16869
16870var elliptic = require('../../elliptic');
16871var utils = elliptic.utils;
16872var assert = utils.assert;
16873
16874function Signature(options, enc) {
16875 if (options instanceof Signature)
16876 return options;
16877
16878 if (this._importDER(options, enc))
16879 return;
16880
16881 assert(options.r && options.s, 'Signature without r or s');
16882 this.r = new BN(options.r, 16);
16883 this.s = new BN(options.s, 16);
16884 if (options.recoveryParam === undefined)
16885 this.recoveryParam = null;
16886 else
16887 this.recoveryParam = options.recoveryParam;
16888}
16889module.exports = Signature;
16890
16891function Position() {
16892 this.place = 0;
16893}
16894
16895function getLength(buf, p) {
16896 var initial = buf[p.place++];
16897 if (!(initial & 0x80)) {
16898 return initial;
16899 }
16900 var octetLen = initial & 0xf;
16901 var val = 0;
16902 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
16903 val <<= 8;
16904 val |= buf[off];
16905 }
16906 p.place = off;
16907 return val;
16908}
16909
16910function rmPadding(buf) {
16911 var i = 0;
16912 var len = buf.length - 1;
16913 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
16914 i++;
16915 }
16916 if (i === 0) {
16917 return buf;
16918 }
16919 return buf.slice(i);
16920}
16921
16922Signature.prototype._importDER = function _importDER(data, enc) {
16923 data = utils.toArray(data, enc);
16924 var p = new Position();
16925 if (data[p.place++] !== 0x30) {
16926 return false;
16927 }
16928 var len = getLength(data, p);
16929 if ((len + p.place) !== data.length) {
16930 return false;
16931 }
16932 if (data[p.place++] !== 0x02) {
16933 return false;
16934 }
16935 var rlen = getLength(data, p);
16936 var r = data.slice(p.place, rlen + p.place);
16937 p.place += rlen;
16938 if (data[p.place++] !== 0x02) {
16939 return false;
16940 }
16941 var slen = getLength(data, p);
16942 if (data.length !== slen + p.place) {
16943 return false;
16944 }
16945 var s = data.slice(p.place, slen + p.place);
16946 if (r[0] === 0 && (r[1] & 0x80)) {
16947 r = r.slice(1);
16948 }
16949 if (s[0] === 0 && (s[1] & 0x80)) {
16950 s = s.slice(1);
16951 }
16952
16953 this.r = new BN(r);
16954 this.s = new BN(s);
16955 this.recoveryParam = null;
16956
16957 return true;
16958};
16959
16960function constructLength(arr, len) {
16961 if (len < 0x80) {
16962 arr.push(len);
16963 return;
16964 }
16965 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
16966 arr.push(octets | 0x80);
16967 while (--octets) {
16968 arr.push((len >>> (octets << 3)) & 0xff);
16969 }
16970 arr.push(len);
16971}
16972
16973Signature.prototype.toDER = function toDER(enc) {
16974 var r = this.r.toArray();
16975 var s = this.s.toArray();
16976
16977 // Pad values
16978 if (r[0] & 0x80)
16979 r = [ 0 ].concat(r);
16980 // Pad values
16981 if (s[0] & 0x80)
16982 s = [ 0 ].concat(s);
16983
16984 r = rmPadding(r);
16985 s = rmPadding(s);
16986
16987 while (!s[0] && !(s[1] & 0x80)) {
16988 s = s.slice(1);
16989 }
16990 var arr = [ 0x02 ];
16991 constructLength(arr, r.length);
16992 arr = arr.concat(r);
16993 arr.push(0x02);
16994 constructLength(arr, s.length);
16995 var backHalf = arr.concat(s);
16996 var res = [ 0x30 ];
16997 constructLength(res, backHalf.length);
16998 res = res.concat(backHalf);
16999 return utils.encode(res, enc);
17000};
17001
17002},{"../../elliptic":83,"bn.js":18}],93:[function(require,module,exports){
17003'use strict';
17004
17005var hash = require('hash.js');
17006var elliptic = require('../../elliptic');
17007var utils = elliptic.utils;
17008var assert = utils.assert;
17009var parseBytes = utils.parseBytes;
17010var KeyPair = require('./key');
17011var Signature = require('./signature');
17012
17013function EDDSA(curve) {
17014 assert(curve === 'ed25519', 'only tested with ed25519 so far');
17015
17016 if (!(this instanceof EDDSA))
17017 return new EDDSA(curve);
17018
17019 var curve = elliptic.curves[curve].curve;
17020 this.curve = curve;
17021 this.g = curve.g;
17022 this.g.precompute(curve.n.bitLength() + 1);
17023
17024 this.pointClass = curve.point().constructor;
17025 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
17026 this.hash = hash.sha512;
17027}
17028
17029module.exports = EDDSA;
17030
17031/**
17032* @param {Array|String} message - message bytes
17033* @param {Array|String|KeyPair} secret - secret bytes or a keypair
17034* @returns {Signature} - signature
17035*/
17036EDDSA.prototype.sign = function sign(message, secret) {
17037 message = parseBytes(message);
17038 var key = this.keyFromSecret(secret);
17039 var r = this.hashInt(key.messagePrefix(), message);
17040 var R = this.g.mul(r);
17041 var Rencoded = this.encodePoint(R);
17042 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
17043 .mul(key.priv());
17044 var S = r.add(s_).umod(this.curve.n);
17045 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
17046};
17047
17048/**
17049* @param {Array} message - message bytes
17050* @param {Array|String|Signature} sig - sig bytes
17051* @param {Array|String|Point|KeyPair} pub - public key
17052* @returns {Boolean} - true if public key matches sig of message
17053*/
17054EDDSA.prototype.verify = function verify(message, sig, pub) {
17055 message = parseBytes(message);
17056 sig = this.makeSignature(sig);
17057 var key = this.keyFromPublic(pub);
17058 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
17059 var SG = this.g.mul(sig.S());
17060 var RplusAh = sig.R().add(key.pub().mul(h));
17061 return RplusAh.eq(SG);
17062};
17063
17064EDDSA.prototype.hashInt = function hashInt() {
17065 var hash = this.hash();
17066 for (var i = 0; i < arguments.length; i++)
17067 hash.update(arguments[i]);
17068 return utils.intFromLE(hash.digest()).umod(this.curve.n);
17069};
17070
17071EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
17072 return KeyPair.fromPublic(this, pub);
17073};
17074
17075EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
17076 return KeyPair.fromSecret(this, secret);
17077};
17078
17079EDDSA.prototype.makeSignature = function makeSignature(sig) {
17080 if (sig instanceof Signature)
17081 return sig;
17082 return new Signature(this, sig);
17083};
17084
17085/**
17086* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
17087*
17088* EDDSA defines methods for encoding and decoding points and integers. These are
17089* helper convenience methods, that pass along to utility functions implied
17090* parameters.
17091*
17092*/
17093EDDSA.prototype.encodePoint = function encodePoint(point) {
17094 var enc = point.getY().toArray('le', this.encodingLength);
17095 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
17096 return enc;
17097};
17098
17099EDDSA.prototype.decodePoint = function decodePoint(bytes) {
17100 bytes = utils.parseBytes(bytes);
17101
17102 var lastIx = bytes.length - 1;
17103 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
17104 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
17105
17106 var y = utils.intFromLE(normed);
17107 return this.curve.pointFromY(y, xIsOdd);
17108};
17109
17110EDDSA.prototype.encodeInt = function encodeInt(num) {
17111 return num.toArray('le', this.encodingLength);
17112};
17113
17114EDDSA.prototype.decodeInt = function decodeInt(bytes) {
17115 return utils.intFromLE(bytes);
17116};
17117
17118EDDSA.prototype.isPoint = function isPoint(val) {
17119 return val instanceof this.pointClass;
17120};
17121
17122},{"../../elliptic":83,"./key":94,"./signature":95,"hash.js":102}],94:[function(require,module,exports){
17123'use strict';
17124
17125var elliptic = require('../../elliptic');
17126var utils = elliptic.utils;
17127var assert = utils.assert;
17128var parseBytes = utils.parseBytes;
17129var cachedProperty = utils.cachedProperty;
17130
17131/**
17132* @param {EDDSA} eddsa - instance
17133* @param {Object} params - public/private key parameters
17134*
17135* @param {Array<Byte>} [params.secret] - secret seed bytes
17136* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
17137* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
17138*
17139*/
17140function KeyPair(eddsa, params) {
17141 this.eddsa = eddsa;
17142 this._secret = parseBytes(params.secret);
17143 if (eddsa.isPoint(params.pub))
17144 this._pub = params.pub;
17145 else
17146 this._pubBytes = parseBytes(params.pub);
17147}
17148
17149KeyPair.fromPublic = function fromPublic(eddsa, pub) {
17150 if (pub instanceof KeyPair)
17151 return pub;
17152 return new KeyPair(eddsa, { pub: pub });
17153};
17154
17155KeyPair.fromSecret = function fromSecret(eddsa, secret) {
17156 if (secret instanceof KeyPair)
17157 return secret;
17158 return new KeyPair(eddsa, { secret: secret });
17159};
17160
17161KeyPair.prototype.secret = function secret() {
17162 return this._secret;
17163};
17164
17165cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
17166 return this.eddsa.encodePoint(this.pub());
17167});
17168
17169cachedProperty(KeyPair, 'pub', function pub() {
17170 if (this._pubBytes)
17171 return this.eddsa.decodePoint(this._pubBytes);
17172 return this.eddsa.g.mul(this.priv());
17173});
17174
17175cachedProperty(KeyPair, 'privBytes', function privBytes() {
17176 var eddsa = this.eddsa;
17177 var hash = this.hash();
17178 var lastIx = eddsa.encodingLength - 1;
17179
17180 var a = hash.slice(0, eddsa.encodingLength);
17181 a[0] &= 248;
17182 a[lastIx] &= 127;
17183 a[lastIx] |= 64;
17184
17185 return a;
17186});
17187
17188cachedProperty(KeyPair, 'priv', function priv() {
17189 return this.eddsa.decodeInt(this.privBytes());
17190});
17191
17192cachedProperty(KeyPair, 'hash', function hash() {
17193 return this.eddsa.hash().update(this.secret()).digest();
17194});
17195
17196cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
17197 return this.hash().slice(this.eddsa.encodingLength);
17198});
17199
17200KeyPair.prototype.sign = function sign(message) {
17201 assert(this._secret, 'KeyPair can only verify');
17202 return this.eddsa.sign(message, this);
17203};
17204
17205KeyPair.prototype.verify = function verify(message, sig) {
17206 return this.eddsa.verify(message, sig, this);
17207};
17208
17209KeyPair.prototype.getSecret = function getSecret(enc) {
17210 assert(this._secret, 'KeyPair is public only');
17211 return utils.encode(this.secret(), enc);
17212};
17213
17214KeyPair.prototype.getPublic = function getPublic(enc) {
17215 return utils.encode(this.pubBytes(), enc);
17216};
17217
17218module.exports = KeyPair;
17219
17220},{"../../elliptic":83}],95:[function(require,module,exports){
17221'use strict';
17222
17223var BN = require('bn.js');
17224var elliptic = require('../../elliptic');
17225var utils = elliptic.utils;
17226var assert = utils.assert;
17227var cachedProperty = utils.cachedProperty;
17228var parseBytes = utils.parseBytes;
17229
17230/**
17231* @param {EDDSA} eddsa - eddsa instance
17232* @param {Array<Bytes>|Object} sig -
17233* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
17234* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
17235* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
17236* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
17237*/
17238function Signature(eddsa, sig) {
17239 this.eddsa = eddsa;
17240
17241 if (typeof sig !== 'object')
17242 sig = parseBytes(sig);
17243
17244 if (Array.isArray(sig)) {
17245 sig = {
17246 R: sig.slice(0, eddsa.encodingLength),
17247 S: sig.slice(eddsa.encodingLength)
17248 };
17249 }
17250
17251 assert(sig.R && sig.S, 'Signature without R or S');
17252
17253 if (eddsa.isPoint(sig.R))
17254 this._R = sig.R;
17255 if (sig.S instanceof BN)
17256 this._S = sig.S;
17257
17258 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
17259 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
17260}
17261
17262cachedProperty(Signature, 'S', function S() {
17263 return this.eddsa.decodeInt(this.Sencoded());
17264});
17265
17266cachedProperty(Signature, 'R', function R() {
17267 return this.eddsa.decodePoint(this.Rencoded());
17268});
17269
17270cachedProperty(Signature, 'Rencoded', function Rencoded() {
17271 return this.eddsa.encodePoint(this.R());
17272});
17273
17274cachedProperty(Signature, 'Sencoded', function Sencoded() {
17275 return this.eddsa.encodeInt(this.S());
17276});
17277
17278Signature.prototype.toBytes = function toBytes() {
17279 return this.Rencoded().concat(this.Sencoded());
17280};
17281
17282Signature.prototype.toHex = function toHex() {
17283 return utils.encode(this.toBytes(), 'hex').toUpperCase();
17284};
17285
17286module.exports = Signature;
17287
17288},{"../../elliptic":83,"bn.js":18}],96:[function(require,module,exports){
17289module.exports = {
17290 doubles: {
17291 step: 4,
17292 points: [
17293 [
17294 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
17295 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
17296 ],
17297 [
17298 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
17299 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
17300 ],
17301 [
17302 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
17303 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
17304 ],
17305 [
17306 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
17307 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
17308 ],
17309 [
17310 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
17311 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
17312 ],
17313 [
17314 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
17315 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
17316 ],
17317 [
17318 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
17319 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
17320 ],
17321 [
17322 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
17323 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
17324 ],
17325 [
17326 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
17327 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
17328 ],
17329 [
17330 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
17331 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
17332 ],
17333 [
17334 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
17335 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
17336 ],
17337 [
17338 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
17339 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
17340 ],
17341 [
17342 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
17343 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
17344 ],
17345 [
17346 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
17347 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
17348 ],
17349 [
17350 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
17351 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
17352 ],
17353 [
17354 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
17355 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
17356 ],
17357 [
17358 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
17359 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
17360 ],
17361 [
17362 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
17363 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
17364 ],
17365 [
17366 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
17367 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
17368 ],
17369 [
17370 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
17371 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
17372 ],
17373 [
17374 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
17375 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
17376 ],
17377 [
17378 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
17379 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
17380 ],
17381 [
17382 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
17383 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
17384 ],
17385 [
17386 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
17387 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
17388 ],
17389 [
17390 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
17391 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
17392 ],
17393 [
17394 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
17395 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
17396 ],
17397 [
17398 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
17399 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
17400 ],
17401 [
17402 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
17403 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
17404 ],
17405 [
17406 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
17407 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
17408 ],
17409 [
17410 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
17411 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
17412 ],
17413 [
17414 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
17415 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
17416 ],
17417 [
17418 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
17419 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
17420 ],
17421 [
17422 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
17423 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
17424 ],
17425 [
17426 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
17427 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
17428 ],
17429 [
17430 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
17431 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
17432 ],
17433 [
17434 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
17435 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
17436 ],
17437 [
17438 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
17439 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
17440 ],
17441 [
17442 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
17443 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
17444 ],
17445 [
17446 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
17447 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
17448 ],
17449 [
17450 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
17451 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
17452 ],
17453 [
17454 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
17455 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
17456 ],
17457 [
17458 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
17459 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
17460 ],
17461 [
17462 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
17463 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
17464 ],
17465 [
17466 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
17467 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
17468 ],
17469 [
17470 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
17471 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
17472 ],
17473 [
17474 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
17475 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
17476 ],
17477 [
17478 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
17479 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
17480 ],
17481 [
17482 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
17483 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
17484 ],
17485 [
17486 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
17487 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
17488 ],
17489 [
17490 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
17491 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
17492 ],
17493 [
17494 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
17495 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
17496 ],
17497 [
17498 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
17499 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
17500 ],
17501 [
17502 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
17503 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
17504 ],
17505 [
17506 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
17507 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
17508 ],
17509 [
17510 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
17511 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
17512 ],
17513 [
17514 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
17515 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
17516 ],
17517 [
17518 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
17519 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
17520 ],
17521 [
17522 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
17523 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
17524 ],
17525 [
17526 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
17527 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
17528 ],
17529 [
17530 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
17531 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
17532 ],
17533 [
17534 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
17535 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
17536 ],
17537 [
17538 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
17539 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
17540 ],
17541 [
17542 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
17543 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
17544 ],
17545 [
17546 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
17547 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
17548 ],
17549 [
17550 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
17551 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
17552 ]
17553 ]
17554 },
17555 naf: {
17556 wnd: 7,
17557 points: [
17558 [
17559 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
17560 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
17561 ],
17562 [
17563 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
17564 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
17565 ],
17566 [
17567 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
17568 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
17569 ],
17570 [
17571 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
17572 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
17573 ],
17574 [
17575 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
17576 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
17577 ],
17578 [
17579 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
17580 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
17581 ],
17582 [
17583 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
17584 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
17585 ],
17586 [
17587 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
17588 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
17589 ],
17590 [
17591 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
17592 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
17593 ],
17594 [
17595 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
17596 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
17597 ],
17598 [
17599 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
17600 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
17601 ],
17602 [
17603 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
17604 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
17605 ],
17606 [
17607 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
17608 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
17609 ],
17610 [
17611 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
17612 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
17613 ],
17614 [
17615 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
17616 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
17617 ],
17618 [
17619 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
17620 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
17621 ],
17622 [
17623 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
17624 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
17625 ],
17626 [
17627 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
17628 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
17629 ],
17630 [
17631 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
17632 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
17633 ],
17634 [
17635 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
17636 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
17637 ],
17638 [
17639 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
17640 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
17641 ],
17642 [
17643 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
17644 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
17645 ],
17646 [
17647 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
17648 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
17649 ],
17650 [
17651 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
17652 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
17653 ],
17654 [
17655 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
17656 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
17657 ],
17658 [
17659 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
17660 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
17661 ],
17662 [
17663 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
17664 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
17665 ],
17666 [
17667 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
17668 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
17669 ],
17670 [
17671 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
17672 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
17673 ],
17674 [
17675 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
17676 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
17677 ],
17678 [
17679 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
17680 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
17681 ],
17682 [
17683 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
17684 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
17685 ],
17686 [
17687 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
17688 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
17689 ],
17690 [
17691 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
17692 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
17693 ],
17694 [
17695 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
17696 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
17697 ],
17698 [
17699 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
17700 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
17701 ],
17702 [
17703 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
17704 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
17705 ],
17706 [
17707 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
17708 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
17709 ],
17710 [
17711 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
17712 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
17713 ],
17714 [
17715 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
17716 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
17717 ],
17718 [
17719 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
17720 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
17721 ],
17722 [
17723 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
17724 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
17725 ],
17726 [
17727 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
17728 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
17729 ],
17730 [
17731 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
17732 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
17733 ],
17734 [
17735 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
17736 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
17737 ],
17738 [
17739 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
17740 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
17741 ],
17742 [
17743 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
17744 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
17745 ],
17746 [
17747 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
17748 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
17749 ],
17750 [
17751 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
17752 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
17753 ],
17754 [
17755 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
17756 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
17757 ],
17758 [
17759 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
17760 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
17761 ],
17762 [
17763 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
17764 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
17765 ],
17766 [
17767 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
17768 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
17769 ],
17770 [
17771 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
17772 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
17773 ],
17774 [
17775 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
17776 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
17777 ],
17778 [
17779 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
17780 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
17781 ],
17782 [
17783 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
17784 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
17785 ],
17786 [
17787 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
17788 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
17789 ],
17790 [
17791 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
17792 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
17793 ],
17794 [
17795 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
17796 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
17797 ],
17798 [
17799 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
17800 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
17801 ],
17802 [
17803 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
17804 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
17805 ],
17806 [
17807 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
17808 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
17809 ],
17810 [
17811 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
17812 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
17813 ],
17814 [
17815 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
17816 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
17817 ],
17818 [
17819 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
17820 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
17821 ],
17822 [
17823 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
17824 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
17825 ],
17826 [
17827 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
17828 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
17829 ],
17830 [
17831 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
17832 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
17833 ],
17834 [
17835 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
17836 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
17837 ],
17838 [
17839 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
17840 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
17841 ],
17842 [
17843 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
17844 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
17845 ],
17846 [
17847 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
17848 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
17849 ],
17850 [
17851 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
17852 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
17853 ],
17854 [
17855 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
17856 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
17857 ],
17858 [
17859 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
17860 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
17861 ],
17862 [
17863 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
17864 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
17865 ],
17866 [
17867 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
17868 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
17869 ],
17870 [
17871 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
17872 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
17873 ],
17874 [
17875 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
17876 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
17877 ],
17878 [
17879 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
17880 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
17881 ],
17882 [
17883 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
17884 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
17885 ],
17886 [
17887 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
17888 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
17889 ],
17890 [
17891 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
17892 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
17893 ],
17894 [
17895 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
17896 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
17897 ],
17898 [
17899 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
17900 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
17901 ],
17902 [
17903 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
17904 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
17905 ],
17906 [
17907 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
17908 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
17909 ],
17910 [
17911 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
17912 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
17913 ],
17914 [
17915 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
17916 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
17917 ],
17918 [
17919 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
17920 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
17921 ],
17922 [
17923 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
17924 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
17925 ],
17926 [
17927 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
17928 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
17929 ],
17930 [
17931 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
17932 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
17933 ],
17934 [
17935 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
17936 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
17937 ],
17938 [
17939 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
17940 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
17941 ],
17942 [
17943 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
17944 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
17945 ],
17946 [
17947 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
17948 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
17949 ],
17950 [
17951 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
17952 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
17953 ],
17954 [
17955 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
17956 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
17957 ],
17958 [
17959 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
17960 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
17961 ],
17962 [
17963 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
17964 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
17965 ],
17966 [
17967 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
17968 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
17969 ],
17970 [
17971 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
17972 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
17973 ],
17974 [
17975 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
17976 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
17977 ],
17978 [
17979 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
17980 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
17981 ],
17982 [
17983 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
17984 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
17985 ],
17986 [
17987 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
17988 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
17989 ],
17990 [
17991 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
17992 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
17993 ],
17994 [
17995 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
17996 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
17997 ],
17998 [
17999 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
18000 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
18001 ],
18002 [
18003 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
18004 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
18005 ],
18006 [
18007 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
18008 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
18009 ],
18010 [
18011 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
18012 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
18013 ],
18014 [
18015 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
18016 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
18017 ],
18018 [
18019 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
18020 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
18021 ],
18022 [
18023 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
18024 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
18025 ],
18026 [
18027 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
18028 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
18029 ],
18030 [
18031 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
18032 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
18033 ],
18034 [
18035 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
18036 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
18037 ],
18038 [
18039 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
18040 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
18041 ],
18042 [
18043 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
18044 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
18045 ],
18046 [
18047 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
18048 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
18049 ],
18050 [
18051 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
18052 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
18053 ],
18054 [
18055 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
18056 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
18057 ],
18058 [
18059 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
18060 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
18061 ],
18062 [
18063 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
18064 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
18065 ]
18066 ]
18067 }
18068};
18069
18070},{}],97:[function(require,module,exports){
18071'use strict';
18072
18073var utils = exports;
18074var BN = require('bn.js');
18075var minAssert = require('minimalistic-assert');
18076var minUtils = require('minimalistic-crypto-utils');
18077
18078utils.assert = minAssert;
18079utils.toArray = minUtils.toArray;
18080utils.zero2 = minUtils.zero2;
18081utils.toHex = minUtils.toHex;
18082utils.encode = minUtils.encode;
18083
18084// Represent num in a w-NAF form
18085function getNAF(num, w) {
18086 var naf = [];
18087 var ws = 1 << (w + 1);
18088 var k = num.clone();
18089 while (k.cmpn(1) >= 0) {
18090 var z;
18091 if (k.isOdd()) {
18092 var mod = k.andln(ws - 1);
18093 if (mod > (ws >> 1) - 1)
18094 z = (ws >> 1) - mod;
18095 else
18096 z = mod;
18097 k.isubn(z);
18098 } else {
18099 z = 0;
18100 }
18101 naf.push(z);
18102
18103 // Optimization, shift by word if possible
18104 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
18105 for (var i = 1; i < shift; i++)
18106 naf.push(0);
18107 k.iushrn(shift);
18108 }
18109
18110 return naf;
18111}
18112utils.getNAF = getNAF;
18113
18114// Represent k1, k2 in a Joint Sparse Form
18115function getJSF(k1, k2) {
18116 var jsf = [
18117 [],
18118 []
18119 ];
18120
18121 k1 = k1.clone();
18122 k2 = k2.clone();
18123 var d1 = 0;
18124 var d2 = 0;
18125 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
18126
18127 // First phase
18128 var m14 = (k1.andln(3) + d1) & 3;
18129 var m24 = (k2.andln(3) + d2) & 3;
18130 if (m14 === 3)
18131 m14 = -1;
18132 if (m24 === 3)
18133 m24 = -1;
18134 var u1;
18135 if ((m14 & 1) === 0) {
18136 u1 = 0;
18137 } else {
18138 var m8 = (k1.andln(7) + d1) & 7;
18139 if ((m8 === 3 || m8 === 5) && m24 === 2)
18140 u1 = -m14;
18141 else
18142 u1 = m14;
18143 }
18144 jsf[0].push(u1);
18145
18146 var u2;
18147 if ((m24 & 1) === 0) {
18148 u2 = 0;
18149 } else {
18150 var m8 = (k2.andln(7) + d2) & 7;
18151 if ((m8 === 3 || m8 === 5) && m14 === 2)
18152 u2 = -m24;
18153 else
18154 u2 = m24;
18155 }
18156 jsf[1].push(u2);
18157
18158 // Second phase
18159 if (2 * d1 === u1 + 1)
18160 d1 = 1 - d1;
18161 if (2 * d2 === u2 + 1)
18162 d2 = 1 - d2;
18163 k1.iushrn(1);
18164 k2.iushrn(1);
18165 }
18166
18167 return jsf;
18168}
18169utils.getJSF = getJSF;
18170
18171function cachedProperty(obj, name, computer) {
18172 var key = '_' + name;
18173 obj.prototype[name] = function cachedProperty() {
18174 return this[key] !== undefined ? this[key] :
18175 this[key] = computer.call(this);
18176 };
18177}
18178utils.cachedProperty = cachedProperty;
18179
18180function parseBytes(bytes) {
18181 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
18182 bytes;
18183}
18184utils.parseBytes = parseBytes;
18185
18186function intFromLE(bytes) {
18187 return new BN(bytes, 'hex', 'le');
18188}
18189utils.intFromLE = intFromLE;
18190
18191
18192},{"bn.js":18,"minimalistic-assert":356,"minimalistic-crypto-utils":357}],98:[function(require,module,exports){
18193module.exports={
18194 "_from": "elliptic@^6.0.0",
18195 "_id": "elliptic@6.4.1",
18196 "_inBundle": false,
18197 "_integrity": "sha512-BsXLz5sqX8OHcsh7CqBMztyXARmGQ3LWPtGjJi6DiJHq5C/qvi9P3OqgswKSDftbu8+IoI/QDTAm2fFnQ9SZSQ==",
18198 "_location": "/elliptic",
18199 "_phantomChildren": {},
18200 "_requested": {
18201 "type": "range",
18202 "registry": true,
18203 "raw": "elliptic@^6.0.0",
18204 "name": "elliptic",
18205 "escapedName": "elliptic",
18206 "rawSpec": "^6.0.0",
18207 "saveSpec": null,
18208 "fetchSpec": "^6.0.0"
18209 },
18210 "_requiredBy": [
18211 "/browserify-sign",
18212 "/create-ecdh"
18213 ],
18214 "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.1.tgz",
18215 "_shasum": "c2d0b7776911b86722c632c3c06c60f2f819939a",
18216 "_spec": "elliptic@^6.0.0",
18217 "_where": "C:\\Projects\\bip39-2\\libs\\stellar-util\\node_modules\\browserify-sign",
18218 "author": {
18219 "name": "Fedor Indutny",
18220 "email": "fedor@indutny.com"
18221 },
18222 "bugs": {
18223 "url": "https://github.com/indutny/elliptic/issues"
18224 },
18225 "bundleDependencies": false,
18226 "dependencies": {
18227 "bn.js": "^4.4.0",
18228 "brorand": "^1.0.1",
18229 "hash.js": "^1.0.0",
18230 "hmac-drbg": "^1.0.0",
18231 "inherits": "^2.0.1",
18232 "minimalistic-assert": "^1.0.0",
18233 "minimalistic-crypto-utils": "^1.0.0"
18234 },
18235 "deprecated": false,
18236 "description": "EC cryptography",
18237 "devDependencies": {
18238 "brfs": "^1.4.3",
18239 "coveralls": "^2.11.3",
18240 "grunt": "^0.4.5",
18241 "grunt-browserify": "^5.0.0",
18242 "grunt-cli": "^1.2.0",
18243 "grunt-contrib-connect": "^1.0.0",
18244 "grunt-contrib-copy": "^1.0.0",
18245 "grunt-contrib-uglify": "^1.0.1",
18246 "grunt-mocha-istanbul": "^3.0.1",
18247 "grunt-saucelabs": "^8.6.2",
18248 "istanbul": "^0.4.2",
18249 "jscs": "^2.9.0",
18250 "jshint": "^2.6.0",
18251 "mocha": "^2.1.0"
18252 },
18253 "files": [
18254 "lib"
18255 ],
18256 "homepage": "https://github.com/indutny/elliptic",
18257 "keywords": [
18258 "EC",
18259 "Elliptic",
18260 "curve",
18261 "Cryptography"
18262 ],
18263 "license": "MIT",
18264 "main": "lib/elliptic.js",
18265 "name": "elliptic",
18266 "repository": {
18267 "type": "git",
18268 "url": "git+ssh://git@github.com/indutny/elliptic.git"
18269 },
18270 "scripts": {
18271 "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
18272 "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
18273 "lint": "npm run jscs && npm run jshint",
18274 "test": "npm run lint && npm run unit",
18275 "unit": "istanbul test _mocha --reporter=spec test/index.js",
18276 "version": "grunt dist && git add dist/"
18277 },
18278 "version": "6.4.1"
18279}
18280
18281},{}],99:[function(require,module,exports){
18282// Copyright Joyent, Inc. and other Node contributors.
18283//
18284// Permission is hereby granted, free of charge, to any person obtaining a
18285// copy of this software and associated documentation files (the
18286// "Software"), to deal in the Software without restriction, including
18287// without limitation the rights to use, copy, modify, merge, publish,
18288// distribute, sublicense, and/or sell copies of the Software, and to permit
18289// persons to whom the Software is furnished to do so, subject to the
18290// following conditions:
18291//
18292// The above copyright notice and this permission notice shall be included
18293// in all copies or substantial portions of the Software.
18294//
18295// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18296// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18297// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
18298// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18299// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18300// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
18301// USE OR OTHER DEALINGS IN THE SOFTWARE.
18302
18303var objectCreate = Object.create || objectCreatePolyfill
18304var objectKeys = Object.keys || objectKeysPolyfill
18305var bind = Function.prototype.bind || functionBindPolyfill
18306
18307function EventEmitter() {
18308 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
18309 this._events = objectCreate(null);
18310 this._eventsCount = 0;
18311 }
18312
18313 this._maxListeners = this._maxListeners || undefined;
18314}
18315module.exports = EventEmitter;
18316
18317// Backwards-compat with node 0.10.x
18318EventEmitter.EventEmitter = EventEmitter;
18319
18320EventEmitter.prototype._events = undefined;
18321EventEmitter.prototype._maxListeners = undefined;
18322
18323// By default EventEmitters will print a warning if more than 10 listeners are
18324// added to it. This is a useful default which helps finding memory leaks.
18325var defaultMaxListeners = 10;
18326
18327var hasDefineProperty;
18328try {
18329 var o = {};
18330 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
18331 hasDefineProperty = o.x === 0;
18332} catch (err) { hasDefineProperty = false }
18333if (hasDefineProperty) {
18334 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
18335 enumerable: true,
18336 get: function() {
18337 return defaultMaxListeners;
18338 },
18339 set: function(arg) {
18340 // check whether the input is a positive number (whose value is zero or
18341 // greater and not a NaN).
18342 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
18343 throw new TypeError('"defaultMaxListeners" must be a positive number');
18344 defaultMaxListeners = arg;
18345 }
18346 });
18347} else {
18348 EventEmitter.defaultMaxListeners = defaultMaxListeners;
18349}
18350
18351// Obviously not all Emitters should be limited to 10. This function allows
18352// that to be increased. Set to zero for unlimited.
18353EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
18354 if (typeof n !== 'number' || n < 0 || isNaN(n))
18355 throw new TypeError('"n" argument must be a positive number');
18356 this._maxListeners = n;
18357 return this;
18358};
18359
18360function $getMaxListeners(that) {
18361 if (that._maxListeners === undefined)
18362 return EventEmitter.defaultMaxListeners;
18363 return that._maxListeners;
18364}
18365
18366EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
18367 return $getMaxListeners(this);
18368};
18369
18370// These standalone emit* functions are used to optimize calling of event
18371// handlers for fast cases because emit() itself often has a variable number of
18372// arguments and can be deoptimized because of that. These functions always have
18373// the same number of arguments and thus do not get deoptimized, so the code
18374// inside them can execute faster.
18375function emitNone(handler, isFn, self) {
18376 if (isFn)
18377 handler.call(self);
18378 else {
18379 var len = handler.length;
18380 var listeners = arrayClone(handler, len);
18381 for (var i = 0; i < len; ++i)
18382 listeners[i].call(self);
18383 }
18384}
18385function emitOne(handler, isFn, self, arg1) {
18386 if (isFn)
18387 handler.call(self, arg1);
18388 else {
18389 var len = handler.length;
18390 var listeners = arrayClone(handler, len);
18391 for (var i = 0; i < len; ++i)
18392 listeners[i].call(self, arg1);
18393 }
18394}
18395function emitTwo(handler, isFn, self, arg1, arg2) {
18396 if (isFn)
18397 handler.call(self, arg1, arg2);
18398 else {
18399 var len = handler.length;
18400 var listeners = arrayClone(handler, len);
18401 for (var i = 0; i < len; ++i)
18402 listeners[i].call(self, arg1, arg2);
18403 }
18404}
18405function emitThree(handler, isFn, self, arg1, arg2, arg3) {
18406 if (isFn)
18407 handler.call(self, arg1, arg2, arg3);
18408 else {
18409 var len = handler.length;
18410 var listeners = arrayClone(handler, len);
18411 for (var i = 0; i < len; ++i)
18412 listeners[i].call(self, arg1, arg2, arg3);
18413 }
18414}
18415
18416function emitMany(handler, isFn, self, args) {
18417 if (isFn)
18418 handler.apply(self, args);
18419 else {
18420 var len = handler.length;
18421 var listeners = arrayClone(handler, len);
18422 for (var i = 0; i < len; ++i)
18423 listeners[i].apply(self, args);
18424 }
18425}
18426
18427EventEmitter.prototype.emit = function emit(type) {
18428 var er, handler, len, args, i, events;
18429 var doError = (type === 'error');
18430
18431 events = this._events;
18432 if (events)
18433 doError = (doError && events.error == null);
18434 else if (!doError)
18435 return false;
18436
18437 // If there is no 'error' event listener then throw.
18438 if (doError) {
18439 if (arguments.length > 1)
18440 er = arguments[1];
18441 if (er instanceof Error) {
18442 throw er; // Unhandled 'error' event
18443 } else {
18444 // At least give some kind of context to the user
18445 var err = new Error('Unhandled "error" event. (' + er + ')');
18446 err.context = er;
18447 throw err;
18448 }
18449 return false;
18450 }
18451
18452 handler = events[type];
18453
18454 if (!handler)
18455 return false;
18456
18457 var isFn = typeof handler === 'function';
18458 len = arguments.length;
18459 switch (len) {
18460 // fast cases
18461 case 1:
18462 emitNone(handler, isFn, this);
18463 break;
18464 case 2:
18465 emitOne(handler, isFn, this, arguments[1]);
18466 break;
18467 case 3:
18468 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
18469 break;
18470 case 4:
18471 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
18472 break;
18473 // slower
18474 default:
18475 args = new Array(len - 1);
18476 for (i = 1; i < len; i++)
18477 args[i - 1] = arguments[i];
18478 emitMany(handler, isFn, this, args);
18479 }
18480
18481 return true;
18482};
18483
18484function _addListener(target, type, listener, prepend) {
18485 var m;
18486 var events;
18487 var existing;
18488
18489 if (typeof listener !== 'function')
18490 throw new TypeError('"listener" argument must be a function');
18491
18492 events = target._events;
18493 if (!events) {
18494 events = target._events = objectCreate(null);
18495 target._eventsCount = 0;
18496 } else {
18497 // To avoid recursion in the case that type === "newListener"! Before
18498 // adding it to the listeners, first emit "newListener".
18499 if (events.newListener) {
18500 target.emit('newListener', type,
18501 listener.listener ? listener.listener : listener);
18502
18503 // Re-assign `events` because a newListener handler could have caused the
18504 // this._events to be assigned to a new object
18505 events = target._events;
18506 }
18507 existing = events[type];
18508 }
18509
18510 if (!existing) {
18511 // Optimize the case of one listener. Don't need the extra array object.
18512 existing = events[type] = listener;
18513 ++target._eventsCount;
18514 } else {
18515 if (typeof existing === 'function') {
18516 // Adding the second element, need to change to array.
18517 existing = events[type] =
18518 prepend ? [listener, existing] : [existing, listener];
18519 } else {
18520 // If we've already got an array, just append.
18521 if (prepend) {
18522 existing.unshift(listener);
18523 } else {
18524 existing.push(listener);
18525 }
18526 }
18527
18528 // Check for listener leak
18529 if (!existing.warned) {
18530 m = $getMaxListeners(target);
18531 if (m && m > 0 && existing.length > m) {
18532 existing.warned = true;
18533 var w = new Error('Possible EventEmitter memory leak detected. ' +
18534 existing.length + ' "' + String(type) + '" listeners ' +
18535 'added. Use emitter.setMaxListeners() to ' +
18536 'increase limit.');
18537 w.name = 'MaxListenersExceededWarning';
18538 w.emitter = target;
18539 w.type = type;
18540 w.count = existing.length;
18541 if (typeof console === 'object' && console.warn) {
18542 console.warn('%s: %s', w.name, w.message);
18543 }
18544 }
18545 }
18546 }
18547
18548 return target;
18549}
18550
18551EventEmitter.prototype.addListener = function addListener(type, listener) {
18552 return _addListener(this, type, listener, false);
18553};
18554
18555EventEmitter.prototype.on = EventEmitter.prototype.addListener;
18556
18557EventEmitter.prototype.prependListener =
18558 function prependListener(type, listener) {
18559 return _addListener(this, type, listener, true);
18560 };
18561
18562function onceWrapper() {
18563 if (!this.fired) {
18564 this.target.removeListener(this.type, this.wrapFn);
18565 this.fired = true;
18566 switch (arguments.length) {
18567 case 0:
18568 return this.listener.call(this.target);
18569 case 1:
18570 return this.listener.call(this.target, arguments[0]);
18571 case 2:
18572 return this.listener.call(this.target, arguments[0], arguments[1]);
18573 case 3:
18574 return this.listener.call(this.target, arguments[0], arguments[1],
18575 arguments[2]);
18576 default:
18577 var args = new Array(arguments.length);
18578 for (var i = 0; i < args.length; ++i)
18579 args[i] = arguments[i];
18580 this.listener.apply(this.target, args);
18581 }
18582 }
18583}
18584
18585function _onceWrap(target, type, listener) {
18586 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
18587 var wrapped = bind.call(onceWrapper, state);
18588 wrapped.listener = listener;
18589 state.wrapFn = wrapped;
18590 return wrapped;
18591}
18592
18593EventEmitter.prototype.once = function once(type, listener) {
18594 if (typeof listener !== 'function')
18595 throw new TypeError('"listener" argument must be a function');
18596 this.on(type, _onceWrap(this, type, listener));
18597 return this;
18598};
18599
18600EventEmitter.prototype.prependOnceListener =
18601 function prependOnceListener(type, listener) {
18602 if (typeof listener !== 'function')
18603 throw new TypeError('"listener" argument must be a function');
18604 this.prependListener(type, _onceWrap(this, type, listener));
18605 return this;
18606 };
18607
18608// Emits a 'removeListener' event if and only if the listener was removed.
18609EventEmitter.prototype.removeListener =
18610 function removeListener(type, listener) {
18611 var list, events, position, i, originalListener;
18612
18613 if (typeof listener !== 'function')
18614 throw new TypeError('"listener" argument must be a function');
18615
18616 events = this._events;
18617 if (!events)
18618 return this;
18619
18620 list = events[type];
18621 if (!list)
18622 return this;
18623
18624 if (list === listener || list.listener === listener) {
18625 if (--this._eventsCount === 0)
18626 this._events = objectCreate(null);
18627 else {
18628 delete events[type];
18629 if (events.removeListener)
18630 this.emit('removeListener', type, list.listener || listener);
18631 }
18632 } else if (typeof list !== 'function') {
18633 position = -1;
18634
18635 for (i = list.length - 1; i >= 0; i--) {
18636 if (list[i] === listener || list[i].listener === listener) {
18637 originalListener = list[i].listener;
18638 position = i;
18639 break;
18640 }
18641 }
18642
18643 if (position < 0)
18644 return this;
18645
18646 if (position === 0)
18647 list.shift();
18648 else
18649 spliceOne(list, position);
18650
18651 if (list.length === 1)
18652 events[type] = list[0];
18653
18654 if (events.removeListener)
18655 this.emit('removeListener', type, originalListener || listener);
18656 }
18657
18658 return this;
18659 };
18660
18661EventEmitter.prototype.removeAllListeners =
18662 function removeAllListeners(type) {
18663 var listeners, events, i;
18664
18665 events = this._events;
18666 if (!events)
18667 return this;
18668
18669 // not listening for removeListener, no need to emit
18670 if (!events.removeListener) {
18671 if (arguments.length === 0) {
18672 this._events = objectCreate(null);
18673 this._eventsCount = 0;
18674 } else if (events[type]) {
18675 if (--this._eventsCount === 0)
18676 this._events = objectCreate(null);
18677 else
18678 delete events[type];
18679 }
18680 return this;
18681 }
18682
18683 // emit removeListener for all listeners on all events
18684 if (arguments.length === 0) {
18685 var keys = objectKeys(events);
18686 var key;
18687 for (i = 0; i < keys.length; ++i) {
18688 key = keys[i];
18689 if (key === 'removeListener') continue;
18690 this.removeAllListeners(key);
18691 }
18692 this.removeAllListeners('removeListener');
18693 this._events = objectCreate(null);
18694 this._eventsCount = 0;
18695 return this;
18696 }
18697
18698 listeners = events[type];
18699
18700 if (typeof listeners === 'function') {
18701 this.removeListener(type, listeners);
18702 } else if (listeners) {
18703 // LIFO order
18704 for (i = listeners.length - 1; i >= 0; i--) {
18705 this.removeListener(type, listeners[i]);
18706 }
18707 }
18708
18709 return this;
18710 };
18711
18712function _listeners(target, type, unwrap) {
18713 var events = target._events;
18714
18715 if (!events)
18716 return [];
18717
18718 var evlistener = events[type];
18719 if (!evlistener)
18720 return [];
18721
18722 if (typeof evlistener === 'function')
18723 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
18724
18725 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
18726}
18727
18728EventEmitter.prototype.listeners = function listeners(type) {
18729 return _listeners(this, type, true);
18730};
18731
18732EventEmitter.prototype.rawListeners = function rawListeners(type) {
18733 return _listeners(this, type, false);
18734};
18735
18736EventEmitter.listenerCount = function(emitter, type) {
18737 if (typeof emitter.listenerCount === 'function') {
18738 return emitter.listenerCount(type);
18739 } else {
18740 return listenerCount.call(emitter, type);
18741 }
18742};
18743
18744EventEmitter.prototype.listenerCount = listenerCount;
18745function listenerCount(type) {
18746 var events = this._events;
18747
18748 if (events) {
18749 var evlistener = events[type];
18750
18751 if (typeof evlistener === 'function') {
18752 return 1;
18753 } else if (evlistener) {
18754 return evlistener.length;
18755 }
18756 }
18757
18758 return 0;
18759}
18760
18761EventEmitter.prototype.eventNames = function eventNames() {
18762 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
18763};
18764
18765// About 1.5x faster than the two-arg version of Array#splice().
18766function spliceOne(list, index) {
18767 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
18768 list[i] = list[k];
18769 list.pop();
18770}
18771
18772function arrayClone(arr, n) {
18773 var copy = new Array(n);
18774 for (var i = 0; i < n; ++i)
18775 copy[i] = arr[i];
18776 return copy;
18777}
18778
18779function unwrapListeners(arr) {
18780 var ret = new Array(arr.length);
18781 for (var i = 0; i < ret.length; ++i) {
18782 ret[i] = arr[i].listener || arr[i];
18783 }
18784 return ret;
18785}
18786
18787function objectCreatePolyfill(proto) {
18788 var F = function() {};
18789 F.prototype = proto;
18790 return new F;
18791}
18792function objectKeysPolyfill(obj) {
18793 var keys = [];
18794 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
18795 keys.push(k);
18796 }
18797 return k;
18798}
18799function functionBindPolyfill(context) {
18800 var fn = this;
18801 return function () {
18802 return fn.apply(context, arguments);
18803 };
18804}
18805
18806},{}],100:[function(require,module,exports){
18807var Buffer = require('safe-buffer').Buffer
18808var MD5 = require('md5.js')
18809
18810/* eslint-disable camelcase */
18811function EVP_BytesToKey (password, salt, keyBits, ivLen) {
18812 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
18813 if (salt) {
18814 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
18815 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
18816 }
18817
18818 var keyLen = keyBits / 8
18819 var key = Buffer.alloc(keyLen)
18820 var iv = Buffer.alloc(ivLen || 0)
18821 var tmp = Buffer.alloc(0)
18822
18823 while (keyLen > 0 || ivLen > 0) {
18824 var hash = new MD5()
18825 hash.update(tmp)
18826 hash.update(password)
18827 if (salt) hash.update(salt)
18828 tmp = hash.digest()
18829
18830 var used = 0
18831
18832 if (keyLen > 0) {
18833 var keyStart = key.length - keyLen
18834 used = Math.min(keyLen, tmp.length)
18835 tmp.copy(key, keyStart, 0, used)
18836 keyLen -= used
18837 }
18838
18839 if (used < tmp.length && ivLen > 0) {
18840 var ivStart = iv.length - ivLen
18841 var length = Math.min(ivLen, tmp.length - used)
18842 tmp.copy(iv, ivStart, used, used + length)
18843 ivLen -= length
18844 }
18845 }
18846
18847 tmp.fill(0)
18848 return { key: key, iv: iv }
18849}
18850
18851module.exports = EVP_BytesToKey
18852
18853},{"md5.js":354,"safe-buffer":393}],101:[function(require,module,exports){
18854'use strict'
18855var Buffer = require('safe-buffer').Buffer
18856var Transform = require('stream').Transform
18857var inherits = require('inherits')
18858
18859function throwIfNotStringOrBuffer (val, prefix) {
18860 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
18861 throw new TypeError(prefix + ' must be a string or a buffer')
18862 }
18863}
18864
18865function HashBase (blockSize) {
18866 Transform.call(this)
18867
18868 this._block = Buffer.allocUnsafe(blockSize)
18869 this._blockSize = blockSize
18870 this._blockOffset = 0
18871 this._length = [0, 0, 0, 0]
18872
18873 this._finalized = false
18874}
18875
18876inherits(HashBase, Transform)
18877
18878HashBase.prototype._transform = function (chunk, encoding, callback) {
18879 var error = null
18880 try {
18881 this.update(chunk, encoding)
18882 } catch (err) {
18883 error = err
18884 }
18885
18886 callback(error)
18887}
18888
18889HashBase.prototype._flush = function (callback) {
18890 var error = null
18891 try {
18892 this.push(this.digest())
18893 } catch (err) {
18894 error = err
18895 }
18896
18897 callback(error)
18898}
18899
18900HashBase.prototype.update = function (data, encoding) {
18901 throwIfNotStringOrBuffer(data, 'Data')
18902 if (this._finalized) throw new Error('Digest already called')
18903 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
18904
18905 // consume data
18906 var block = this._block
18907 var offset = 0
18908 while (this._blockOffset + data.length - offset >= this._blockSize) {
18909 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
18910 this._update()
18911 this._blockOffset = 0
18912 }
18913 while (offset < data.length) block[this._blockOffset++] = data[offset++]
18914
18915 // update length
18916 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
18917 this._length[j] += carry
18918 carry = (this._length[j] / 0x0100000000) | 0
18919 if (carry > 0) this._length[j] -= 0x0100000000 * carry
18920 }
18921
18922 return this
18923}
18924
18925HashBase.prototype._update = function () {
18926 throw new Error('_update is not implemented')
18927}
18928
18929HashBase.prototype.digest = function (encoding) {
18930 if (this._finalized) throw new Error('Digest already called')
18931 this._finalized = true
18932
18933 var digest = this._digest()
18934 if (encoding !== undefined) digest = digest.toString(encoding)
18935
18936 // reset state
18937 this._block.fill(0)
18938 this._blockOffset = 0
18939 for (var i = 0; i < 4; ++i) this._length[i] = 0
18940
18941 return digest
18942}
18943
18944HashBase.prototype._digest = function () {
18945 throw new Error('_digest is not implemented')
18946}
18947
18948module.exports = HashBase
18949
18950},{"inherits":116,"safe-buffer":393,"stream":432}],102:[function(require,module,exports){
18951var hash = exports;
18952
18953hash.utils = require('./hash/utils');
18954hash.common = require('./hash/common');
18955hash.sha = require('./hash/sha');
18956hash.ripemd = require('./hash/ripemd');
18957hash.hmac = require('./hash/hmac');
18958
18959// Proxy hash functions to the main object
18960hash.sha1 = hash.sha.sha1;
18961hash.sha256 = hash.sha.sha256;
18962hash.sha224 = hash.sha.sha224;
18963hash.sha384 = hash.sha.sha384;
18964hash.sha512 = hash.sha.sha512;
18965hash.ripemd160 = hash.ripemd.ripemd160;
18966
18967},{"./hash/common":103,"./hash/hmac":104,"./hash/ripemd":105,"./hash/sha":106,"./hash/utils":113}],103:[function(require,module,exports){
18968'use strict';
18969
18970var utils = require('./utils');
18971var assert = require('minimalistic-assert');
18972
18973function BlockHash() {
18974 this.pending = null;
18975 this.pendingTotal = 0;
18976 this.blockSize = this.constructor.blockSize;
18977 this.outSize = this.constructor.outSize;
18978 this.hmacStrength = this.constructor.hmacStrength;
18979 this.padLength = this.constructor.padLength / 8;
18980 this.endian = 'big';
18981
18982 this._delta8 = this.blockSize / 8;
18983 this._delta32 = this.blockSize / 32;
18984}
18985exports.BlockHash = BlockHash;
18986
18987BlockHash.prototype.update = function update(msg, enc) {
18988 // Convert message to array, pad it, and join into 32bit blocks
18989 msg = utils.toArray(msg, enc);
18990 if (!this.pending)
18991 this.pending = msg;
18992 else
18993 this.pending = this.pending.concat(msg);
18994 this.pendingTotal += msg.length;
18995
18996 // Enough data, try updating
18997 if (this.pending.length >= this._delta8) {
18998 msg = this.pending;
18999
19000 // Process pending data in blocks
19001 var r = msg.length % this._delta8;
19002 this.pending = msg.slice(msg.length - r, msg.length);
19003 if (this.pending.length === 0)
19004 this.pending = null;
19005
19006 msg = utils.join32(msg, 0, msg.length - r, this.endian);
19007 for (var i = 0; i < msg.length; i += this._delta32)
19008 this._update(msg, i, i + this._delta32);
19009 }
19010
19011 return this;
19012};
19013
19014BlockHash.prototype.digest = function digest(enc) {
19015 this.update(this._pad());
19016 assert(this.pending === null);
19017
19018 return this._digest(enc);
19019};
19020
19021BlockHash.prototype._pad = function pad() {
19022 var len = this.pendingTotal;
19023 var bytes = this._delta8;
19024 var k = bytes - ((len + this.padLength) % bytes);
19025 var res = new Array(k + this.padLength);
19026 res[0] = 0x80;
19027 for (var i = 1; i < k; i++)
19028 res[i] = 0;
19029
19030 // Append length
19031 len <<= 3;
19032 if (this.endian === 'big') {
19033 for (var t = 8; t < this.padLength; t++)
19034 res[i++] = 0;
19035
19036 res[i++] = 0;
19037 res[i++] = 0;
19038 res[i++] = 0;
19039 res[i++] = 0;
19040 res[i++] = (len >>> 24) & 0xff;
19041 res[i++] = (len >>> 16) & 0xff;
19042 res[i++] = (len >>> 8) & 0xff;
19043 res[i++] = len & 0xff;
19044 } else {
19045 res[i++] = len & 0xff;
19046 res[i++] = (len >>> 8) & 0xff;
19047 res[i++] = (len >>> 16) & 0xff;
19048 res[i++] = (len >>> 24) & 0xff;
19049 res[i++] = 0;
19050 res[i++] = 0;
19051 res[i++] = 0;
19052 res[i++] = 0;
19053
19054 for (t = 8; t < this.padLength; t++)
19055 res[i++] = 0;
19056 }
19057
19058 return res;
19059};
19060
19061},{"./utils":113,"minimalistic-assert":356}],104:[function(require,module,exports){
19062'use strict';
19063
19064var utils = require('./utils');
19065var assert = require('minimalistic-assert');
19066
19067function Hmac(hash, key, enc) {
19068 if (!(this instanceof Hmac))
19069 return new Hmac(hash, key, enc);
19070 this.Hash = hash;
19071 this.blockSize = hash.blockSize / 8;
19072 this.outSize = hash.outSize / 8;
19073 this.inner = null;
19074 this.outer = null;
19075
19076 this._init(utils.toArray(key, enc));
19077}
19078module.exports = Hmac;
19079
19080Hmac.prototype._init = function init(key) {
19081 // Shorten key, if needed
19082 if (key.length > this.blockSize)
19083 key = new this.Hash().update(key).digest();
19084 assert(key.length <= this.blockSize);
19085
19086 // Add padding to key
19087 for (var i = key.length; i < this.blockSize; i++)
19088 key.push(0);
19089
19090 for (i = 0; i < key.length; i++)
19091 key[i] ^= 0x36;
19092 this.inner = new this.Hash().update(key);
19093
19094 // 0x36 ^ 0x5c = 0x6a
19095 for (i = 0; i < key.length; i++)
19096 key[i] ^= 0x6a;
19097 this.outer = new this.Hash().update(key);
19098};
19099
19100Hmac.prototype.update = function update(msg, enc) {
19101 this.inner.update(msg, enc);
19102 return this;
19103};
19104
19105Hmac.prototype.digest = function digest(enc) {
19106 this.outer.update(this.inner.digest());
19107 return this.outer.digest(enc);
19108};
19109
19110},{"./utils":113,"minimalistic-assert":356}],105:[function(require,module,exports){
19111'use strict';
19112
19113var utils = require('./utils');
19114var common = require('./common');
19115
19116var rotl32 = utils.rotl32;
19117var sum32 = utils.sum32;
19118var sum32_3 = utils.sum32_3;
19119var sum32_4 = utils.sum32_4;
19120var BlockHash = common.BlockHash;
19121
19122function RIPEMD160() {
19123 if (!(this instanceof RIPEMD160))
19124 return new RIPEMD160();
19125
19126 BlockHash.call(this);
19127
19128 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
19129 this.endian = 'little';
19130}
19131utils.inherits(RIPEMD160, BlockHash);
19132exports.ripemd160 = RIPEMD160;
19133
19134RIPEMD160.blockSize = 512;
19135RIPEMD160.outSize = 160;
19136RIPEMD160.hmacStrength = 192;
19137RIPEMD160.padLength = 64;
19138
19139RIPEMD160.prototype._update = function update(msg, start) {
19140 var A = this.h[0];
19141 var B = this.h[1];
19142 var C = this.h[2];
19143 var D = this.h[3];
19144 var E = this.h[4];
19145 var Ah = A;
19146 var Bh = B;
19147 var Ch = C;
19148 var Dh = D;
19149 var Eh = E;
19150 for (var j = 0; j < 80; j++) {
19151 var T = sum32(
19152 rotl32(
19153 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
19154 s[j]),
19155 E);
19156 A = E;
19157 E = D;
19158 D = rotl32(C, 10);
19159 C = B;
19160 B = T;
19161 T = sum32(
19162 rotl32(
19163 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
19164 sh[j]),
19165 Eh);
19166 Ah = Eh;
19167 Eh = Dh;
19168 Dh = rotl32(Ch, 10);
19169 Ch = Bh;
19170 Bh = T;
19171 }
19172 T = sum32_3(this.h[1], C, Dh);
19173 this.h[1] = sum32_3(this.h[2], D, Eh);
19174 this.h[2] = sum32_3(this.h[3], E, Ah);
19175 this.h[3] = sum32_3(this.h[4], A, Bh);
19176 this.h[4] = sum32_3(this.h[0], B, Ch);
19177 this.h[0] = T;
19178};
19179
19180RIPEMD160.prototype._digest = function digest(enc) {
19181 if (enc === 'hex')
19182 return utils.toHex32(this.h, 'little');
19183 else
19184 return utils.split32(this.h, 'little');
19185};
19186
19187function f(j, x, y, z) {
19188 if (j <= 15)
19189 return x ^ y ^ z;
19190 else if (j <= 31)
19191 return (x & y) | ((~x) & z);
19192 else if (j <= 47)
19193 return (x | (~y)) ^ z;
19194 else if (j <= 63)
19195 return (x & z) | (y & (~z));
19196 else
19197 return x ^ (y | (~z));
19198}
19199
19200function K(j) {
19201 if (j <= 15)
19202 return 0x00000000;
19203 else if (j <= 31)
19204 return 0x5a827999;
19205 else if (j <= 47)
19206 return 0x6ed9eba1;
19207 else if (j <= 63)
19208 return 0x8f1bbcdc;
19209 else
19210 return 0xa953fd4e;
19211}
19212
19213function Kh(j) {
19214 if (j <= 15)
19215 return 0x50a28be6;
19216 else if (j <= 31)
19217 return 0x5c4dd124;
19218 else if (j <= 47)
19219 return 0x6d703ef3;
19220 else if (j <= 63)
19221 return 0x7a6d76e9;
19222 else
19223 return 0x00000000;
19224}
19225
19226var r = [
19227 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
19228 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
19229 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
19230 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
19231 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
19232];
19233
19234var rh = [
19235 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
19236 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
19237 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
19238 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
19239 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
19240];
19241
19242var s = [
19243 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
19244 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
19245 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
19246 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
19247 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
19248];
19249
19250var sh = [
19251 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
19252 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
19253 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
19254 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
19255 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
19256];
19257
19258},{"./common":103,"./utils":113}],106:[function(require,module,exports){
19259'use strict';
19260
19261exports.sha1 = require('./sha/1');
19262exports.sha224 = require('./sha/224');
19263exports.sha256 = require('./sha/256');
19264exports.sha384 = require('./sha/384');
19265exports.sha512 = require('./sha/512');
19266
19267},{"./sha/1":107,"./sha/224":108,"./sha/256":109,"./sha/384":110,"./sha/512":111}],107:[function(require,module,exports){
19268'use strict';
19269
19270var utils = require('../utils');
19271var common = require('../common');
19272var shaCommon = require('./common');
19273
19274var rotl32 = utils.rotl32;
19275var sum32 = utils.sum32;
19276var sum32_5 = utils.sum32_5;
19277var ft_1 = shaCommon.ft_1;
19278var BlockHash = common.BlockHash;
19279
19280var sha1_K = [
19281 0x5A827999, 0x6ED9EBA1,
19282 0x8F1BBCDC, 0xCA62C1D6
19283];
19284
19285function SHA1() {
19286 if (!(this instanceof SHA1))
19287 return new SHA1();
19288
19289 BlockHash.call(this);
19290 this.h = [
19291 0x67452301, 0xefcdab89, 0x98badcfe,
19292 0x10325476, 0xc3d2e1f0 ];
19293 this.W = new Array(80);
19294}
19295
19296utils.inherits(SHA1, BlockHash);
19297module.exports = SHA1;
19298
19299SHA1.blockSize = 512;
19300SHA1.outSize = 160;
19301SHA1.hmacStrength = 80;
19302SHA1.padLength = 64;
19303
19304SHA1.prototype._update = function _update(msg, start) {
19305 var W = this.W;
19306
19307 for (var i = 0; i < 16; i++)
19308 W[i] = msg[start + i];
19309
19310 for(; i < W.length; i++)
19311 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
19312
19313 var a = this.h[0];
19314 var b = this.h[1];
19315 var c = this.h[2];
19316 var d = this.h[3];
19317 var e = this.h[4];
19318
19319 for (i = 0; i < W.length; i++) {
19320 var s = ~~(i / 20);
19321 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
19322 e = d;
19323 d = c;
19324 c = rotl32(b, 30);
19325 b = a;
19326 a = t;
19327 }
19328
19329 this.h[0] = sum32(this.h[0], a);
19330 this.h[1] = sum32(this.h[1], b);
19331 this.h[2] = sum32(this.h[2], c);
19332 this.h[3] = sum32(this.h[3], d);
19333 this.h[4] = sum32(this.h[4], e);
19334};
19335
19336SHA1.prototype._digest = function digest(enc) {
19337 if (enc === 'hex')
19338 return utils.toHex32(this.h, 'big');
19339 else
19340 return utils.split32(this.h, 'big');
19341};
19342
19343},{"../common":103,"../utils":113,"./common":112}],108:[function(require,module,exports){
19344'use strict';
19345
19346var utils = require('../utils');
19347var SHA256 = require('./256');
19348
19349function SHA224() {
19350 if (!(this instanceof SHA224))
19351 return new SHA224();
19352
19353 SHA256.call(this);
19354 this.h = [
19355 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
19356 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
19357}
19358utils.inherits(SHA224, SHA256);
19359module.exports = SHA224;
19360
19361SHA224.blockSize = 512;
19362SHA224.outSize = 224;
19363SHA224.hmacStrength = 192;
19364SHA224.padLength = 64;
19365
19366SHA224.prototype._digest = function digest(enc) {
19367 // Just truncate output
19368 if (enc === 'hex')
19369 return utils.toHex32(this.h.slice(0, 7), 'big');
19370 else
19371 return utils.split32(this.h.slice(0, 7), 'big');
19372};
19373
19374
19375},{"../utils":113,"./256":109}],109:[function(require,module,exports){
19376'use strict';
19377
19378var utils = require('../utils');
19379var common = require('../common');
19380var shaCommon = require('./common');
19381var assert = require('minimalistic-assert');
19382
19383var sum32 = utils.sum32;
19384var sum32_4 = utils.sum32_4;
19385var sum32_5 = utils.sum32_5;
19386var ch32 = shaCommon.ch32;
19387var maj32 = shaCommon.maj32;
19388var s0_256 = shaCommon.s0_256;
19389var s1_256 = shaCommon.s1_256;
19390var g0_256 = shaCommon.g0_256;
19391var g1_256 = shaCommon.g1_256;
19392
19393var BlockHash = common.BlockHash;
19394
19395var sha256_K = [
19396 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
19397 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
19398 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
19399 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
19400 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
19401 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
19402 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
19403 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
19404 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
19405 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
19406 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
19407 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
19408 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
19409 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
19410 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
19411 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
19412];
19413
19414function SHA256() {
19415 if (!(this instanceof SHA256))
19416 return new SHA256();
19417
19418 BlockHash.call(this);
19419 this.h = [
19420 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
19421 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
19422 ];
19423 this.k = sha256_K;
19424 this.W = new Array(64);
19425}
19426utils.inherits(SHA256, BlockHash);
19427module.exports = SHA256;
19428
19429SHA256.blockSize = 512;
19430SHA256.outSize = 256;
19431SHA256.hmacStrength = 192;
19432SHA256.padLength = 64;
19433
19434SHA256.prototype._update = function _update(msg, start) {
19435 var W = this.W;
19436
19437 for (var i = 0; i < 16; i++)
19438 W[i] = msg[start + i];
19439 for (; i < W.length; i++)
19440 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
19441
19442 var a = this.h[0];
19443 var b = this.h[1];
19444 var c = this.h[2];
19445 var d = this.h[3];
19446 var e = this.h[4];
19447 var f = this.h[5];
19448 var g = this.h[6];
19449 var h = this.h[7];
19450
19451 assert(this.k.length === W.length);
19452 for (i = 0; i < W.length; i++) {
19453 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
19454 var T2 = sum32(s0_256(a), maj32(a, b, c));
19455 h = g;
19456 g = f;
19457 f = e;
19458 e = sum32(d, T1);
19459 d = c;
19460 c = b;
19461 b = a;
19462 a = sum32(T1, T2);
19463 }
19464
19465 this.h[0] = sum32(this.h[0], a);
19466 this.h[1] = sum32(this.h[1], b);
19467 this.h[2] = sum32(this.h[2], c);
19468 this.h[3] = sum32(this.h[3], d);
19469 this.h[4] = sum32(this.h[4], e);
19470 this.h[5] = sum32(this.h[5], f);
19471 this.h[6] = sum32(this.h[6], g);
19472 this.h[7] = sum32(this.h[7], h);
19473};
19474
19475SHA256.prototype._digest = function digest(enc) {
19476 if (enc === 'hex')
19477 return utils.toHex32(this.h, 'big');
19478 else
19479 return utils.split32(this.h, 'big');
19480};
19481
19482},{"../common":103,"../utils":113,"./common":112,"minimalistic-assert":356}],110:[function(require,module,exports){
19483'use strict';
19484
19485var utils = require('../utils');
19486
19487var SHA512 = require('./512');
19488
19489function SHA384() {
19490 if (!(this instanceof SHA384))
19491 return new SHA384();
19492
19493 SHA512.call(this);
19494 this.h = [
19495 0xcbbb9d5d, 0xc1059ed8,
19496 0x629a292a, 0x367cd507,
19497 0x9159015a, 0x3070dd17,
19498 0x152fecd8, 0xf70e5939,
19499 0x67332667, 0xffc00b31,
19500 0x8eb44a87, 0x68581511,
19501 0xdb0c2e0d, 0x64f98fa7,
19502 0x47b5481d, 0xbefa4fa4 ];
19503}
19504utils.inherits(SHA384, SHA512);
19505module.exports = SHA384;
19506
19507SHA384.blockSize = 1024;
19508SHA384.outSize = 384;
19509SHA384.hmacStrength = 192;
19510SHA384.padLength = 128;
19511
19512SHA384.prototype._digest = function digest(enc) {
19513 if (enc === 'hex')
19514 return utils.toHex32(this.h.slice(0, 12), 'big');
19515 else
19516 return utils.split32(this.h.slice(0, 12), 'big');
19517};
19518
19519},{"../utils":113,"./512":111}],111:[function(require,module,exports){
19520'use strict';
19521
19522var utils = require('../utils');
19523var common = require('../common');
19524var assert = require('minimalistic-assert');
19525
19526var rotr64_hi = utils.rotr64_hi;
19527var rotr64_lo = utils.rotr64_lo;
19528var shr64_hi = utils.shr64_hi;
19529var shr64_lo = utils.shr64_lo;
19530var sum64 = utils.sum64;
19531var sum64_hi = utils.sum64_hi;
19532var sum64_lo = utils.sum64_lo;
19533var sum64_4_hi = utils.sum64_4_hi;
19534var sum64_4_lo = utils.sum64_4_lo;
19535var sum64_5_hi = utils.sum64_5_hi;
19536var sum64_5_lo = utils.sum64_5_lo;
19537
19538var BlockHash = common.BlockHash;
19539
19540var sha512_K = [
19541 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
19542 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
19543 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
19544 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
19545 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
19546 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
19547 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
19548 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
19549 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
19550 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
19551 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
19552 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
19553 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
19554 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
19555 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
19556 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
19557 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
19558 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
19559 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
19560 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
19561 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
19562 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
19563 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
19564 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
19565 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
19566 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
19567 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
19568 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
19569 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
19570 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
19571 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
19572 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
19573 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
19574 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
19575 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
19576 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
19577 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
19578 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
19579 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
19580 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
19581];
19582
19583function SHA512() {
19584 if (!(this instanceof SHA512))
19585 return new SHA512();
19586
19587 BlockHash.call(this);
19588 this.h = [
19589 0x6a09e667, 0xf3bcc908,
19590 0xbb67ae85, 0x84caa73b,
19591 0x3c6ef372, 0xfe94f82b,
19592 0xa54ff53a, 0x5f1d36f1,
19593 0x510e527f, 0xade682d1,
19594 0x9b05688c, 0x2b3e6c1f,
19595 0x1f83d9ab, 0xfb41bd6b,
19596 0x5be0cd19, 0x137e2179 ];
19597 this.k = sha512_K;
19598 this.W = new Array(160);
19599}
19600utils.inherits(SHA512, BlockHash);
19601module.exports = SHA512;
19602
19603SHA512.blockSize = 1024;
19604SHA512.outSize = 512;
19605SHA512.hmacStrength = 192;
19606SHA512.padLength = 128;
19607
19608SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
19609 var W = this.W;
19610
19611 // 32 x 32bit words
19612 for (var i = 0; i < 32; i++)
19613 W[i] = msg[start + i];
19614 for (; i < W.length; i += 2) {
19615 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
19616 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
19617 var c1_hi = W[i - 14]; // i - 7
19618 var c1_lo = W[i - 13];
19619 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
19620 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
19621 var c3_hi = W[i - 32]; // i - 16
19622 var c3_lo = W[i - 31];
19623
19624 W[i] = sum64_4_hi(
19625 c0_hi, c0_lo,
19626 c1_hi, c1_lo,
19627 c2_hi, c2_lo,
19628 c3_hi, c3_lo);
19629 W[i + 1] = sum64_4_lo(
19630 c0_hi, c0_lo,
19631 c1_hi, c1_lo,
19632 c2_hi, c2_lo,
19633 c3_hi, c3_lo);
19634 }
19635};
19636
19637SHA512.prototype._update = function _update(msg, start) {
19638 this._prepareBlock(msg, start);
19639
19640 var W = this.W;
19641
19642 var ah = this.h[0];
19643 var al = this.h[1];
19644 var bh = this.h[2];
19645 var bl = this.h[3];
19646 var ch = this.h[4];
19647 var cl = this.h[5];
19648 var dh = this.h[6];
19649 var dl = this.h[7];
19650 var eh = this.h[8];
19651 var el = this.h[9];
19652 var fh = this.h[10];
19653 var fl = this.h[11];
19654 var gh = this.h[12];
19655 var gl = this.h[13];
19656 var hh = this.h[14];
19657 var hl = this.h[15];
19658
19659 assert(this.k.length === W.length);
19660 for (var i = 0; i < W.length; i += 2) {
19661 var c0_hi = hh;
19662 var c0_lo = hl;
19663 var c1_hi = s1_512_hi(eh, el);
19664 var c1_lo = s1_512_lo(eh, el);
19665 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
19666 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
19667 var c3_hi = this.k[i];
19668 var c3_lo = this.k[i + 1];
19669 var c4_hi = W[i];
19670 var c4_lo = W[i + 1];
19671
19672 var T1_hi = sum64_5_hi(
19673 c0_hi, c0_lo,
19674 c1_hi, c1_lo,
19675 c2_hi, c2_lo,
19676 c3_hi, c3_lo,
19677 c4_hi, c4_lo);
19678 var T1_lo = sum64_5_lo(
19679 c0_hi, c0_lo,
19680 c1_hi, c1_lo,
19681 c2_hi, c2_lo,
19682 c3_hi, c3_lo,
19683 c4_hi, c4_lo);
19684
19685 c0_hi = s0_512_hi(ah, al);
19686 c0_lo = s0_512_lo(ah, al);
19687 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
19688 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
19689
19690 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
19691 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
19692
19693 hh = gh;
19694 hl = gl;
19695
19696 gh = fh;
19697 gl = fl;
19698
19699 fh = eh;
19700 fl = el;
19701
19702 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
19703 el = sum64_lo(dl, dl, T1_hi, T1_lo);
19704
19705 dh = ch;
19706 dl = cl;
19707
19708 ch = bh;
19709 cl = bl;
19710
19711 bh = ah;
19712 bl = al;
19713
19714 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
19715 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
19716 }
19717
19718 sum64(this.h, 0, ah, al);
19719 sum64(this.h, 2, bh, bl);
19720 sum64(this.h, 4, ch, cl);
19721 sum64(this.h, 6, dh, dl);
19722 sum64(this.h, 8, eh, el);
19723 sum64(this.h, 10, fh, fl);
19724 sum64(this.h, 12, gh, gl);
19725 sum64(this.h, 14, hh, hl);
19726};
19727
19728SHA512.prototype._digest = function digest(enc) {
19729 if (enc === 'hex')
19730 return utils.toHex32(this.h, 'big');
19731 else
19732 return utils.split32(this.h, 'big');
19733};
19734
19735function ch64_hi(xh, xl, yh, yl, zh) {
19736 var r = (xh & yh) ^ ((~xh) & zh);
19737 if (r < 0)
19738 r += 0x100000000;
19739 return r;
19740}
19741
19742function ch64_lo(xh, xl, yh, yl, zh, zl) {
19743 var r = (xl & yl) ^ ((~xl) & zl);
19744 if (r < 0)
19745 r += 0x100000000;
19746 return r;
19747}
19748
19749function maj64_hi(xh, xl, yh, yl, zh) {
19750 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
19751 if (r < 0)
19752 r += 0x100000000;
19753 return r;
19754}
19755
19756function maj64_lo(xh, xl, yh, yl, zh, zl) {
19757 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
19758 if (r < 0)
19759 r += 0x100000000;
19760 return r;
19761}
19762
19763function s0_512_hi(xh, xl) {
19764 var c0_hi = rotr64_hi(xh, xl, 28);
19765 var c1_hi = rotr64_hi(xl, xh, 2); // 34
19766 var c2_hi = rotr64_hi(xl, xh, 7); // 39
19767
19768 var r = c0_hi ^ c1_hi ^ c2_hi;
19769 if (r < 0)
19770 r += 0x100000000;
19771 return r;
19772}
19773
19774function s0_512_lo(xh, xl) {
19775 var c0_lo = rotr64_lo(xh, xl, 28);
19776 var c1_lo = rotr64_lo(xl, xh, 2); // 34
19777 var c2_lo = rotr64_lo(xl, xh, 7); // 39
19778
19779 var r = c0_lo ^ c1_lo ^ c2_lo;
19780 if (r < 0)
19781 r += 0x100000000;
19782 return r;
19783}
19784
19785function s1_512_hi(xh, xl) {
19786 var c0_hi = rotr64_hi(xh, xl, 14);
19787 var c1_hi = rotr64_hi(xh, xl, 18);
19788 var c2_hi = rotr64_hi(xl, xh, 9); // 41
19789
19790 var r = c0_hi ^ c1_hi ^ c2_hi;
19791 if (r < 0)
19792 r += 0x100000000;
19793 return r;
19794}
19795
19796function s1_512_lo(xh, xl) {
19797 var c0_lo = rotr64_lo(xh, xl, 14);
19798 var c1_lo = rotr64_lo(xh, xl, 18);
19799 var c2_lo = rotr64_lo(xl, xh, 9); // 41
19800
19801 var r = c0_lo ^ c1_lo ^ c2_lo;
19802 if (r < 0)
19803 r += 0x100000000;
19804 return r;
19805}
19806
19807function g0_512_hi(xh, xl) {
19808 var c0_hi = rotr64_hi(xh, xl, 1);
19809 var c1_hi = rotr64_hi(xh, xl, 8);
19810 var c2_hi = shr64_hi(xh, xl, 7);
19811
19812 var r = c0_hi ^ c1_hi ^ c2_hi;
19813 if (r < 0)
19814 r += 0x100000000;
19815 return r;
19816}
19817
19818function g0_512_lo(xh, xl) {
19819 var c0_lo = rotr64_lo(xh, xl, 1);
19820 var c1_lo = rotr64_lo(xh, xl, 8);
19821 var c2_lo = shr64_lo(xh, xl, 7);
19822
19823 var r = c0_lo ^ c1_lo ^ c2_lo;
19824 if (r < 0)
19825 r += 0x100000000;
19826 return r;
19827}
19828
19829function g1_512_hi(xh, xl) {
19830 var c0_hi = rotr64_hi(xh, xl, 19);
19831 var c1_hi = rotr64_hi(xl, xh, 29); // 61
19832 var c2_hi = shr64_hi(xh, xl, 6);
19833
19834 var r = c0_hi ^ c1_hi ^ c2_hi;
19835 if (r < 0)
19836 r += 0x100000000;
19837 return r;
19838}
19839
19840function g1_512_lo(xh, xl) {
19841 var c0_lo = rotr64_lo(xh, xl, 19);
19842 var c1_lo = rotr64_lo(xl, xh, 29); // 61
19843 var c2_lo = shr64_lo(xh, xl, 6);
19844
19845 var r = c0_lo ^ c1_lo ^ c2_lo;
19846 if (r < 0)
19847 r += 0x100000000;
19848 return r;
19849}
19850
19851},{"../common":103,"../utils":113,"minimalistic-assert":356}],112:[function(require,module,exports){
19852'use strict';
19853
19854var utils = require('../utils');
19855var rotr32 = utils.rotr32;
19856
19857function ft_1(s, x, y, z) {
19858 if (s === 0)
19859 return ch32(x, y, z);
19860 if (s === 1 || s === 3)
19861 return p32(x, y, z);
19862 if (s === 2)
19863 return maj32(x, y, z);
19864}
19865exports.ft_1 = ft_1;
19866
19867function ch32(x, y, z) {
19868 return (x & y) ^ ((~x) & z);
19869}
19870exports.ch32 = ch32;
19871
19872function maj32(x, y, z) {
19873 return (x & y) ^ (x & z) ^ (y & z);
19874}
19875exports.maj32 = maj32;
19876
19877function p32(x, y, z) {
19878 return x ^ y ^ z;
19879}
19880exports.p32 = p32;
19881
19882function s0_256(x) {
19883 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
19884}
19885exports.s0_256 = s0_256;
19886
19887function s1_256(x) {
19888 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
19889}
19890exports.s1_256 = s1_256;
19891
19892function g0_256(x) {
19893 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
19894}
19895exports.g0_256 = g0_256;
19896
19897function g1_256(x) {
19898 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
19899}
19900exports.g1_256 = g1_256;
19901
19902},{"../utils":113}],113:[function(require,module,exports){
19903'use strict';
19904
19905var assert = require('minimalistic-assert');
19906var inherits = require('inherits');
19907
19908exports.inherits = inherits;
19909
19910function isSurrogatePair(msg, i) {
19911 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
19912 return false;
19913 }
19914 if (i < 0 || i + 1 >= msg.length) {
19915 return false;
19916 }
19917 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
19918}
19919
19920function toArray(msg, enc) {
19921 if (Array.isArray(msg))
19922 return msg.slice();
19923 if (!msg)
19924 return [];
19925 var res = [];
19926 if (typeof msg === 'string') {
19927 if (!enc) {
19928 // Inspired by stringToUtf8ByteArray() in closure-library by Google
19929 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
19930 // Apache License 2.0
19931 // https://github.com/google/closure-library/blob/master/LICENSE
19932 var p = 0;
19933 for (var i = 0; i < msg.length; i++) {
19934 var c = msg.charCodeAt(i);
19935 if (c < 128) {
19936 res[p++] = c;
19937 } else if (c < 2048) {
19938 res[p++] = (c >> 6) | 192;
19939 res[p++] = (c & 63) | 128;
19940 } else if (isSurrogatePair(msg, i)) {
19941 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
19942 res[p++] = (c >> 18) | 240;
19943 res[p++] = ((c >> 12) & 63) | 128;
19944 res[p++] = ((c >> 6) & 63) | 128;
19945 res[p++] = (c & 63) | 128;
19946 } else {
19947 res[p++] = (c >> 12) | 224;
19948 res[p++] = ((c >> 6) & 63) | 128;
19949 res[p++] = (c & 63) | 128;
19950 }
19951 }
19952 } else if (enc === 'hex') {
19953 msg = msg.replace(/[^a-z0-9]+/ig, '');
19954 if (msg.length % 2 !== 0)
19955 msg = '0' + msg;
19956 for (i = 0; i < msg.length; i += 2)
19957 res.push(parseInt(msg[i] + msg[i + 1], 16));
19958 }
19959 } else {
19960 for (i = 0; i < msg.length; i++)
19961 res[i] = msg[i] | 0;
19962 }
19963 return res;
19964}
19965exports.toArray = toArray;
19966
19967function toHex(msg) {
19968 var res = '';
19969 for (var i = 0; i < msg.length; i++)
19970 res += zero2(msg[i].toString(16));
19971 return res;
19972}
19973exports.toHex = toHex;
19974
19975function htonl(w) {
19976 var res = (w >>> 24) |
19977 ((w >>> 8) & 0xff00) |
19978 ((w << 8) & 0xff0000) |
19979 ((w & 0xff) << 24);
19980 return res >>> 0;
19981}
19982exports.htonl = htonl;
19983
19984function toHex32(msg, endian) {
19985 var res = '';
19986 for (var i = 0; i < msg.length; i++) {
19987 var w = msg[i];
19988 if (endian === 'little')
19989 w = htonl(w);
19990 res += zero8(w.toString(16));
19991 }
19992 return res;
19993}
19994exports.toHex32 = toHex32;
19995
19996function zero2(word) {
19997 if (word.length === 1)
19998 return '0' + word;
19999 else
20000 return word;
20001}
20002exports.zero2 = zero2;
20003
20004function zero8(word) {
20005 if (word.length === 7)
20006 return '0' + word;
20007 else if (word.length === 6)
20008 return '00' + word;
20009 else if (word.length === 5)
20010 return '000' + word;
20011 else if (word.length === 4)
20012 return '0000' + word;
20013 else if (word.length === 3)
20014 return '00000' + word;
20015 else if (word.length === 2)
20016 return '000000' + word;
20017 else if (word.length === 1)
20018 return '0000000' + word;
20019 else
20020 return word;
20021}
20022exports.zero8 = zero8;
20023
20024function join32(msg, start, end, endian) {
20025 var len = end - start;
20026 assert(len % 4 === 0);
20027 var res = new Array(len / 4);
20028 for (var i = 0, k = start; i < res.length; i++, k += 4) {
20029 var w;
20030 if (endian === 'big')
20031 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
20032 else
20033 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
20034 res[i] = w >>> 0;
20035 }
20036 return res;
20037}
20038exports.join32 = join32;
20039
20040function split32(msg, endian) {
20041 var res = new Array(msg.length * 4);
20042 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
20043 var m = msg[i];
20044 if (endian === 'big') {
20045 res[k] = m >>> 24;
20046 res[k + 1] = (m >>> 16) & 0xff;
20047 res[k + 2] = (m >>> 8) & 0xff;
20048 res[k + 3] = m & 0xff;
20049 } else {
20050 res[k + 3] = m >>> 24;
20051 res[k + 2] = (m >>> 16) & 0xff;
20052 res[k + 1] = (m >>> 8) & 0xff;
20053 res[k] = m & 0xff;
20054 }
20055 }
20056 return res;
20057}
20058exports.split32 = split32;
20059
20060function rotr32(w, b) {
20061 return (w >>> b) | (w << (32 - b));
20062}
20063exports.rotr32 = rotr32;
20064
20065function rotl32(w, b) {
20066 return (w << b) | (w >>> (32 - b));
20067}
20068exports.rotl32 = rotl32;
20069
20070function sum32(a, b) {
20071 return (a + b) >>> 0;
20072}
20073exports.sum32 = sum32;
20074
20075function sum32_3(a, b, c) {
20076 return (a + b + c) >>> 0;
20077}
20078exports.sum32_3 = sum32_3;
20079
20080function sum32_4(a, b, c, d) {
20081 return (a + b + c + d) >>> 0;
20082}
20083exports.sum32_4 = sum32_4;
20084
20085function sum32_5(a, b, c, d, e) {
20086 return (a + b + c + d + e) >>> 0;
20087}
20088exports.sum32_5 = sum32_5;
20089
20090function sum64(buf, pos, ah, al) {
20091 var bh = buf[pos];
20092 var bl = buf[pos + 1];
20093
20094 var lo = (al + bl) >>> 0;
20095 var hi = (lo < al ? 1 : 0) + ah + bh;
20096 buf[pos] = hi >>> 0;
20097 buf[pos + 1] = lo;
20098}
20099exports.sum64 = sum64;
20100
20101function sum64_hi(ah, al, bh, bl) {
20102 var lo = (al + bl) >>> 0;
20103 var hi = (lo < al ? 1 : 0) + ah + bh;
20104 return hi >>> 0;
20105}
20106exports.sum64_hi = sum64_hi;
20107
20108function sum64_lo(ah, al, bh, bl) {
20109 var lo = al + bl;
20110 return lo >>> 0;
20111}
20112exports.sum64_lo = sum64_lo;
20113
20114function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
20115 var carry = 0;
20116 var lo = al;
20117 lo = (lo + bl) >>> 0;
20118 carry += lo < al ? 1 : 0;
20119 lo = (lo + cl) >>> 0;
20120 carry += lo < cl ? 1 : 0;
20121 lo = (lo + dl) >>> 0;
20122 carry += lo < dl ? 1 : 0;
20123
20124 var hi = ah + bh + ch + dh + carry;
20125 return hi >>> 0;
20126}
20127exports.sum64_4_hi = sum64_4_hi;
20128
20129function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
20130 var lo = al + bl + cl + dl;
20131 return lo >>> 0;
20132}
20133exports.sum64_4_lo = sum64_4_lo;
20134
20135function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
20136 var carry = 0;
20137 var lo = al;
20138 lo = (lo + bl) >>> 0;
20139 carry += lo < al ? 1 : 0;
20140 lo = (lo + cl) >>> 0;
20141 carry += lo < cl ? 1 : 0;
20142 lo = (lo + dl) >>> 0;
20143 carry += lo < dl ? 1 : 0;
20144 lo = (lo + el) >>> 0;
20145 carry += lo < el ? 1 : 0;
20146
20147 var hi = ah + bh + ch + dh + eh + carry;
20148 return hi >>> 0;
20149}
20150exports.sum64_5_hi = sum64_5_hi;
20151
20152function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
20153 var lo = al + bl + cl + dl + el;
20154
20155 return lo >>> 0;
20156}
20157exports.sum64_5_lo = sum64_5_lo;
20158
20159function rotr64_hi(ah, al, num) {
20160 var r = (al << (32 - num)) | (ah >>> num);
20161 return r >>> 0;
20162}
20163exports.rotr64_hi = rotr64_hi;
20164
20165function rotr64_lo(ah, al, num) {
20166 var r = (ah << (32 - num)) | (al >>> num);
20167 return r >>> 0;
20168}
20169exports.rotr64_lo = rotr64_lo;
20170
20171function shr64_hi(ah, al, num) {
20172 return ah >>> num;
20173}
20174exports.shr64_hi = shr64_hi;
20175
20176function shr64_lo(ah, al, num) {
20177 var r = (ah << (32 - num)) | (al >>> num);
20178 return r >>> 0;
20179}
20180exports.shr64_lo = shr64_lo;
20181
20182},{"inherits":116,"minimalistic-assert":356}],114:[function(require,module,exports){
20183'use strict';
20184
20185var hash = require('hash.js');
20186var utils = require('minimalistic-crypto-utils');
20187var assert = require('minimalistic-assert');
20188
20189function HmacDRBG(options) {
20190 if (!(this instanceof HmacDRBG))
20191 return new HmacDRBG(options);
20192 this.hash = options.hash;
20193 this.predResist = !!options.predResist;
20194
20195 this.outLen = this.hash.outSize;
20196 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
20197
20198 this._reseed = null;
20199 this.reseedInterval = null;
20200 this.K = null;
20201 this.V = null;
20202
20203 var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
20204 var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
20205 var pers = utils.toArray(options.pers, options.persEnc || 'hex');
20206 assert(entropy.length >= (this.minEntropy / 8),
20207 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
20208 this._init(entropy, nonce, pers);
20209}
20210module.exports = HmacDRBG;
20211
20212HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
20213 var seed = entropy.concat(nonce).concat(pers);
20214
20215 this.K = new Array(this.outLen / 8);
20216 this.V = new Array(this.outLen / 8);
20217 for (var i = 0; i < this.V.length; i++) {
20218 this.K[i] = 0x00;
20219 this.V[i] = 0x01;
20220 }
20221
20222 this._update(seed);
20223 this._reseed = 1;
20224 this.reseedInterval = 0x1000000000000; // 2^48
20225};
20226
20227HmacDRBG.prototype._hmac = function hmac() {
20228 return new hash.hmac(this.hash, this.K);
20229};
20230
20231HmacDRBG.prototype._update = function update(seed) {
20232 var kmac = this._hmac()
20233 .update(this.V)
20234 .update([ 0x00 ]);
20235 if (seed)
20236 kmac = kmac.update(seed);
20237 this.K = kmac.digest();
20238 this.V = this._hmac().update(this.V).digest();
20239 if (!seed)
20240 return;
20241
20242 this.K = this._hmac()
20243 .update(this.V)
20244 .update([ 0x01 ])
20245 .update(seed)
20246 .digest();
20247 this.V = this._hmac().update(this.V).digest();
20248};
20249
20250HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
20251 // Optional entropy enc
20252 if (typeof entropyEnc !== 'string') {
20253 addEnc = add;
20254 add = entropyEnc;
20255 entropyEnc = null;
20256 }
20257
20258 entropy = utils.toArray(entropy, entropyEnc);
20259 add = utils.toArray(add, addEnc);
20260
20261 assert(entropy.length >= (this.minEntropy / 8),
20262 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
20263
20264 this._update(entropy.concat(add || []));
20265 this._reseed = 1;
20266};
20267
20268HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
20269 if (this._reseed > this.reseedInterval)
20270 throw new Error('Reseed is required');
20271
20272 // Optional encoding
20273 if (typeof enc !== 'string') {
20274 addEnc = add;
20275 add = enc;
20276 enc = null;
20277 }
20278
20279 // Optional additional data
20280 if (add) {
20281 add = utils.toArray(add, addEnc || 'hex');
20282 this._update(add);
20283 }
20284
20285 var temp = [];
20286 while (temp.length < len) {
20287 this.V = this._hmac().update(this.V).digest();
20288 temp = temp.concat(this.V);
20289 }
20290
20291 var res = temp.slice(0, len);
20292 this._update(add);
20293 this._reseed++;
20294 return utils.encode(res, enc);
20295};
20296
20297},{"hash.js":102,"minimalistic-assert":356,"minimalistic-crypto-utils":357}],115:[function(require,module,exports){
20298exports.read = function (buffer, offset, isLE, mLen, nBytes) {
20299 var e, m
20300 var eLen = (nBytes * 8) - mLen - 1
20301 var eMax = (1 << eLen) - 1
20302 var eBias = eMax >> 1
20303 var nBits = -7
20304 var i = isLE ? (nBytes - 1) : 0
20305 var d = isLE ? -1 : 1
20306 var s = buffer[offset + i]
20307
20308 i += d
20309
20310 e = s & ((1 << (-nBits)) - 1)
20311 s >>= (-nBits)
20312 nBits += eLen
20313 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
20314
20315 m = e & ((1 << (-nBits)) - 1)
20316 e >>= (-nBits)
20317 nBits += mLen
20318 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
20319
20320 if (e === 0) {
20321 e = 1 - eBias
20322 } else if (e === eMax) {
20323 return m ? NaN : ((s ? -1 : 1) * Infinity)
20324 } else {
20325 m = m + Math.pow(2, mLen)
20326 e = e - eBias
20327 }
20328 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
20329}
20330
20331exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
20332 var e, m, c
20333 var eLen = (nBytes * 8) - mLen - 1
20334 var eMax = (1 << eLen) - 1
20335 var eBias = eMax >> 1
20336 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
20337 var i = isLE ? 0 : (nBytes - 1)
20338 var d = isLE ? 1 : -1
20339 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
20340
20341 value = Math.abs(value)
20342
20343 if (isNaN(value) || value === Infinity) {
20344 m = isNaN(value) ? 1 : 0
20345 e = eMax
20346 } else {
20347 e = Math.floor(Math.log(value) / Math.LN2)
20348 if (value * (c = Math.pow(2, -e)) < 1) {
20349 e--
20350 c *= 2
20351 }
20352 if (e + eBias >= 1) {
20353 value += rt / c
20354 } else {
20355 value += rt * Math.pow(2, 1 - eBias)
20356 }
20357 if (value * c >= 2) {
20358 e++
20359 c /= 2
20360 }
20361
20362 if (e + eBias >= eMax) {
20363 m = 0
20364 e = eMax
20365 } else if (e + eBias >= 1) {
20366 m = ((value * c) - 1) * Math.pow(2, mLen)
20367 e = e + eBias
20368 } else {
20369 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
20370 e = 0
20371 }
20372 }
20373
20374 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
20375
20376 e = (e << mLen) | m
20377 eLen += mLen
20378 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
20379
20380 buffer[offset + i - d] |= s * 128
20381}
20382
20383},{}],116:[function(require,module,exports){
20384if (typeof Object.create === 'function') {
20385 // implementation from standard node.js 'util' module
20386 module.exports = function inherits(ctor, superCtor) {
20387 ctor.super_ = superCtor
20388 ctor.prototype = Object.create(superCtor.prototype, {
20389 constructor: {
20390 value: ctor,
20391 enumerable: false,
20392 writable: true,
20393 configurable: true
20394 }
20395 });
20396 };
20397} else {
20398 // old school shim for old browsers
20399 module.exports = function inherits(ctor, superCtor) {
20400 ctor.super_ = superCtor
20401 var TempCtor = function () {}
20402 TempCtor.prototype = superCtor.prototype
20403 ctor.prototype = new TempCtor()
20404 ctor.prototype.constructor = ctor
20405 }
20406}
20407
20408},{}],117:[function(require,module,exports){
20409/*!
20410 * Determine if an object is a Buffer
20411 *
20412 * @author Feross Aboukhadijeh <https://feross.org>
20413 * @license MIT
20414 */
20415
20416// The _isBuffer check is for Safari 5-7 support, because it's missing
20417// Object.prototype.constructor. Remove this eventually
20418module.exports = function (obj) {
20419 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
20420}
20421
20422function isBuffer (obj) {
20423 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
20424}
20425
20426// For Node v0.10 support. Remove this eventually.
20427function isSlowBuffer (obj) {
20428 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
20429}
20430
20431},{}],118:[function(require,module,exports){
20432var toString = {}.toString;
20433
20434module.exports = Array.isArray || function (arr) {
20435 return toString.call(arr) == '[object Array]';
20436};
20437
20438},{}],119:[function(require,module,exports){
20439"use strict";
20440
20441var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
20442
20443var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
20444
20445var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
20446
20447Object.defineProperty(exports, "__esModule", {
20448 value: true
20449});
20450
20451var every = _interopRequire(require("lodash/every"));
20452
20453var each = _interopRequire(require("lodash/each"));
20454
20455var times = _interopRequire(require("lodash/times"));
20456
20457var isArray = _interopRequire(require("lodash/isArray"));
20458
20459var includeIoMixin = _interopRequire(require("./io-mixin"));
20460
20461var Array = exports.Array = (function () {
20462 function Array(childType, length) {
20463 _classCallCheck(this, Array);
20464
20465 this._childType = childType;
20466 this._length = length;
20467 }
20468
20469 _createClass(Array, {
20470 read: {
20471 value: function read(io) {
20472 var _this = this;
20473
20474 return times(this._length, function () {
20475 return _this._childType.read(io);
20476 });
20477 }
20478 },
20479 write: {
20480 value: function write(value, io) {
20481 var _this = this;
20482
20483 if (!isArray(value)) {
20484 throw new Error("XDR Write Error: value is not array");
20485 }
20486
20487 if (value.length !== this._length) {
20488 throw new Error("XDR Write Error: Got array of size " + value.length + "," + ("expected " + this._length));
20489 }
20490
20491 each(value, function (child) {
20492 return _this._childType.write(child, io);
20493 });
20494 }
20495 },
20496 isValid: {
20497 value: function isValid(value) {
20498 var _this = this;
20499
20500 if (!isArray(value)) {
20501 return false;
20502 }
20503 if (value.length !== this._length) {
20504 return false;
20505 }
20506
20507 return every(value, function (child) {
20508 return _this._childType.isValid(child);
20509 });
20510 }
20511 }
20512 });
20513
20514 return Array;
20515})();
20516
20517includeIoMixin(Array.prototype);
20518},{"./io-mixin":129,"lodash/each":308,"lodash/every":310,"lodash/isArray":319,"lodash/times":346}],120:[function(require,module,exports){
20519"use strict";
20520
20521var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
20522
20523Object.defineProperty(exports, "__esModule", {
20524 value: true
20525});
20526
20527var Int = require("./int").Int;
20528
20529var isBoolean = _interopRequire(require("lodash/isBoolean"));
20530
20531var includeIoMixin = _interopRequire(require("./io-mixin"));
20532
20533var Bool = {
20534 read: function read(io) {
20535 var value = Int.read(io);
20536
20537 switch (value) {
20538 case 0:
20539 return false;
20540 case 1:
20541 return true;
20542 default:
20543 throw new Error("XDR Read Error: Got " + value + " when trying to read a bool");
20544 }
20545 },
20546
20547 write: function write(value, io) {
20548 var intVal = value ? 1 : 0;
20549 return Int.write(intVal, io);
20550 },
20551
20552 isValid: function isValid(value) {
20553 return isBoolean(value);
20554 }
20555};
20556
20557exports.Bool = Bool;
20558includeIoMixin(Bool);
20559},{"./int":128,"./io-mixin":129,"lodash/isBoolean":321}],121:[function(require,module,exports){
20560"use strict";
20561
20562var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
20563
20564var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
20565
20566var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
20567
20568var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
20569
20570var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
20571
20572exports.config = config;
20573Object.defineProperty(exports, "__esModule", {
20574 value: true
20575});
20576
20577var XDR = _interopRequireWildcard(require("./types"));
20578
20579var isUndefined = _interopRequire(require("lodash/isUndefined"));
20580
20581var isPlainObject = _interopRequire(require("lodash/isPlainObject"));
20582
20583var isArray = _interopRequire(require("lodash/isArray"));
20584
20585var each = _interopRequire(require("lodash/each"));
20586
20587var map = _interopRequire(require("lodash/map"));
20588
20589var pick = _interopRequire(require("lodash/pick"));
20590
20591function config(fn) {
20592 var types = arguments[1] === undefined ? {} : arguments[1];
20593
20594 if (fn) {
20595 var builder = new TypeBuilder(types);
20596 fn(builder);
20597 builder.resolve();
20598 }
20599
20600 return types;
20601}
20602
20603var Reference = exports.Reference = (function () {
20604 function Reference() {
20605 _classCallCheck(this, Reference);
20606 }
20607
20608 _createClass(Reference, {
20609 resolve: {
20610 /* jshint unused: false */
20611
20612 value: function resolve(context) {
20613 throw new Error("implement resolve in child class");
20614 }
20615 }
20616 });
20617
20618 return Reference;
20619})();
20620
20621var SimpleReference = (function (_Reference) {
20622 function SimpleReference(name) {
20623 _classCallCheck(this, SimpleReference);
20624
20625 this.name = name;
20626 }
20627
20628 _inherits(SimpleReference, _Reference);
20629
20630 _createClass(SimpleReference, {
20631 resolve: {
20632 value: function resolve(context) {
20633 var defn = context.definitions[this.name];
20634 return defn.resolve(context);
20635 }
20636 }
20637 });
20638
20639 return SimpleReference;
20640})(Reference);
20641
20642var ArrayReference = (function (_Reference2) {
20643 function ArrayReference(childReference, length) {
20644 var variable = arguments[2] === undefined ? false : arguments[2];
20645
20646 _classCallCheck(this, ArrayReference);
20647
20648 this.childReference = childReference;
20649 this.length = length;
20650 this.variable = variable;
20651 }
20652
20653 _inherits(ArrayReference, _Reference2);
20654
20655 _createClass(ArrayReference, {
20656 resolve: {
20657 value: function resolve(context) {
20658 var resolvedChild = this.childReference;
20659 var length = this.length;
20660
20661 if (resolvedChild instanceof Reference) {
20662 resolvedChild = resolvedChild.resolve(context);
20663 }
20664
20665 if (length instanceof Reference) {
20666 length = length.resolve(context);
20667 }
20668
20669 if (this.variable) {
20670 return new XDR.VarArray(resolvedChild, length);
20671 } else {
20672 return new XDR.Array(resolvedChild, length);
20673 }
20674 }
20675 }
20676 });
20677
20678 return ArrayReference;
20679})(Reference);
20680
20681var OptionReference = (function (_Reference3) {
20682 function OptionReference(childReference) {
20683 _classCallCheck(this, OptionReference);
20684
20685 this.childReference = childReference;
20686 this.name = childReference.name;
20687 }
20688
20689 _inherits(OptionReference, _Reference3);
20690
20691 _createClass(OptionReference, {
20692 resolve: {
20693 value: function resolve(context) {
20694 var resolvedChild = this.childReference;
20695
20696 if (resolvedChild instanceof Reference) {
20697 resolvedChild = resolvedChild.resolve(context);
20698 }
20699
20700 return new XDR.Option(resolvedChild);
20701 }
20702 }
20703 });
20704
20705 return OptionReference;
20706})(Reference);
20707
20708var SizedReference = (function (_Reference4) {
20709 function SizedReference(sizedType, length) {
20710 _classCallCheck(this, SizedReference);
20711
20712 this.sizedType = sizedType;
20713 this.length = length;
20714 }
20715
20716 _inherits(SizedReference, _Reference4);
20717
20718 _createClass(SizedReference, {
20719 resolve: {
20720 value: function resolve(context) {
20721 var length = this.length;
20722
20723 if (length instanceof Reference) {
20724 length = length.resolve(context);
20725 }
20726
20727 return new this.sizedType(length);
20728 }
20729 }
20730 });
20731
20732 return SizedReference;
20733})(Reference);
20734
20735var Definition = (function () {
20736 function Definition(constructor, name, config) {
20737 _classCallCheck(this, Definition);
20738
20739 this.constructor = constructor;
20740 this.name = name;
20741 this.config = config;
20742 }
20743
20744 _createClass(Definition, {
20745 resolve: {
20746
20747 // resolve calls the constructor of this definition with the provided context
20748 // and this definitions config values. The definitions constructor should
20749 // populate the final type on `context.results`, and may refer to other
20750 // definitions through `context.definitions`
20751
20752 value: function resolve(context) {
20753 if (this.name in context.results) {
20754 return context.results[this.name];
20755 }
20756
20757 return this.constructor(context, this.name, this.config);
20758 }
20759 }
20760 });
20761
20762 return Definition;
20763})();
20764
20765var TypeBuilder = (function () {
20766 function TypeBuilder(destination) {
20767 _classCallCheck(this, TypeBuilder);
20768
20769 this._destination = destination;
20770 this._definitions = {};
20771 }
20772
20773 _createClass(TypeBuilder, {
20774 "enum": {
20775 value: function _enum(name, members) {
20776 var result = new Definition(XDR.Enum.create, name, members);
20777 this.define(name, result);
20778 }
20779 },
20780 struct: {
20781 value: function struct(name, members) {
20782 var result = new Definition(XDR.Struct.create, name, members);
20783 this.define(name, result);
20784 }
20785 },
20786 union: {
20787 value: function union(name, config) {
20788 var result = new Definition(XDR.Union.create, name, config);
20789 this.define(name, result);
20790 }
20791 },
20792 typedef: {
20793 value: function typedef(name, config) {
20794 // let the reference resoltion system do it's thing
20795 // the "constructor" for a typedef just returns the resolved value
20796 var createTypedef = function (context, name, value) {
20797 if (value instanceof Reference) {
20798 value = value.resolve(context);
20799 }
20800 context.results[name] = value;
20801 return value;
20802 };
20803
20804 var result = new Definition(createTypedef, name, config);
20805 this.define(name, result);
20806 }
20807 },
20808 "const": {
20809 value: function _const(name, config) {
20810 var createConst = function (context, name, value) {
20811 context.results[name] = value;
20812 return value;
20813 };
20814
20815 var result = new Definition(createConst, name, config);
20816 this.define(name, result);
20817 }
20818 },
20819 "void": {
20820 value: function _void() {
20821 return XDR.Void;
20822 }
20823 },
20824 bool: {
20825 value: function bool() {
20826 return XDR.Bool;
20827 }
20828 },
20829 int: {
20830 value: function int() {
20831 return XDR.Int;
20832 }
20833 },
20834 hyper: {
20835 value: function hyper() {
20836 return XDR.Hyper;
20837 }
20838 },
20839 uint: {
20840 value: function uint() {
20841 return XDR.UnsignedInt;
20842 }
20843 },
20844 uhyper: {
20845 value: function uhyper() {
20846 return XDR.UnsignedHyper;
20847 }
20848 },
20849 float: {
20850 value: function float() {
20851 return XDR.Float;
20852 }
20853 },
20854 double: {
20855 value: function double() {
20856 return XDR.Double;
20857 }
20858 },
20859 quadruple: {
20860 value: function quadruple() {
20861 return XDR.Quadruple;
20862 }
20863 },
20864 string: {
20865 value: function string(length) {
20866 return new SizedReference(XDR.String, length);
20867 }
20868 },
20869 opaque: {
20870 value: function opaque(length) {
20871 return new SizedReference(XDR.Opaque, length);
20872 }
20873 },
20874 varOpaque: {
20875 value: function varOpaque(length) {
20876 return new SizedReference(XDR.VarOpaque, length);
20877 }
20878 },
20879 array: {
20880 value: function array(childType, length) {
20881 return new ArrayReference(childType, length);
20882 }
20883 },
20884 varArray: {
20885 value: function varArray(childType, maxLength) {
20886 return new ArrayReference(childType, maxLength, true);
20887 }
20888 },
20889 option: {
20890 value: function option(childType) {
20891 return new OptionReference(childType);
20892 }
20893 },
20894 define: {
20895 value: function define(name, definition) {
20896 if (isUndefined(this._destination[name])) {
20897 this._definitions[name] = definition;
20898 } else {
20899 throw new Error("XDR Error:" + name + " is already defined");
20900 }
20901 }
20902 },
20903 lookup: {
20904 value: function lookup(name) {
20905 return new SimpleReference(name);
20906 }
20907 },
20908 resolve: {
20909 value: function resolve() {
20910 var _this = this;
20911
20912 each(this._definitions, function (defn, name) {
20913 defn.resolve({
20914 definitions: _this._definitions,
20915 results: _this._destination
20916 });
20917 });
20918 }
20919 }
20920 });
20921
20922 return TypeBuilder;
20923})();
20924},{"./types":135,"lodash/each":308,"lodash/isArray":319,"lodash/isPlainObject":331,"lodash/isUndefined":336,"lodash/map":339,"lodash/pick":342}],122:[function(require,module,exports){
20925(function (Buffer){
20926"use strict";
20927
20928var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
20929
20930var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
20931
20932var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
20933
20934var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
20935
20936Object.defineProperty(exports, "__esModule", {
20937 value: true
20938});
20939
20940var BaseCursor = _interopRequire(require("cursor"));
20941
20942var calculatePadding = require("./util").calculatePadding;
20943
20944var Cursor = exports.Cursor = (function (_BaseCursor) {
20945 function Cursor() {
20946 _classCallCheck(this, Cursor);
20947
20948 if (_BaseCursor != null) {
20949 _BaseCursor.apply(this, arguments);
20950 }
20951 }
20952
20953 _inherits(Cursor, _BaseCursor);
20954
20955 _createClass(Cursor, {
20956 writeBufferPadded: {
20957 value: function writeBufferPadded(buffer) {
20958 var padding = calculatePadding(buffer.length);
20959 var paddingBuffer = Buffer.alloc(padding);
20960
20961 return this.copyFrom(new Cursor(buffer)).copyFrom(new Cursor(paddingBuffer));
20962 }
20963 }
20964 });
20965
20966 return Cursor;
20967})(BaseCursor);
20968}).call(this,require("buffer").Buffer)
20969},{"./util":139,"buffer":49,"cursor":72}],123:[function(require,module,exports){
20970"use strict";
20971
20972var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
20973
20974Object.defineProperty(exports, "__esModule", {
20975 value: true
20976});
20977
20978var isNumber = _interopRequire(require("lodash/isNumber"));
20979
20980var includeIoMixin = _interopRequire(require("./io-mixin"));
20981
20982var Double = {
20983
20984 read: function read(io) {
20985 return io.readDoubleBE();
20986 },
20987
20988 write: function write(value, io) {
20989 if (!isNumber(value)) {
20990 throw new Error("XDR Write Error: not a number");
20991 }
20992
20993 io.writeDoubleBE(value);
20994 },
20995
20996 isValid: function isValid(value) {
20997 return isNumber(value);
20998 } };
20999
21000exports.Double = Double;
21001includeIoMixin(Double);
21002},{"./io-mixin":129,"lodash/isNumber":328}],124:[function(require,module,exports){
21003"use strict";
21004
21005var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21006
21007var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
21008
21009var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
21010
21011var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21012
21013var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
21014
21015Object.defineProperty(exports, "__esModule", {
21016 value: true
21017});
21018
21019var Int = require("./int").Int;
21020
21021var each = _interopRequire(require("lodash/each"));
21022
21023var vals = _interopRequire(require("lodash/values"));
21024
21025var includeIoMixin = _interopRequire(require("./io-mixin"));
21026
21027var Enum = exports.Enum = (function () {
21028 function Enum(name, value) {
21029 _classCallCheck(this, Enum);
21030
21031 this.name = name;
21032 this.value = value;
21033 }
21034
21035 _createClass(Enum, null, {
21036 read: {
21037 value: function read(io) {
21038 var intVal = Int.read(io);
21039
21040 if (!this._byValue.has(intVal)) {
21041 throw new Error("XDR Read Error: Unknown " + this.enumName + " member for value " + intVal);
21042 }
21043
21044 return this._byValue.get(intVal);
21045 }
21046 },
21047 write: {
21048 value: function write(value, io) {
21049 if (!(value instanceof this)) {
21050 throw new Error("XDR Write Error: Unknown " + value + " is not a " + this.enumName);
21051 }
21052
21053 Int.write(value.value, io);
21054 }
21055 },
21056 isValid: {
21057 value: function isValid(value) {
21058 return value instanceof this;
21059 }
21060 },
21061 members: {
21062 value: function members() {
21063 return this._members;
21064 }
21065 },
21066 values: {
21067 value: function values() {
21068 return vals(this._members);
21069 }
21070 },
21071 fromName: {
21072 value: function fromName(name) {
21073 var result = this._members[name];
21074
21075 if (!result) {
21076 throw new Error("" + name + " is not a member of " + this.enumName);
21077 }
21078
21079 return result;
21080 }
21081 },
21082 fromValue: {
21083 value: function fromValue(value) {
21084 var result = this._byValue.get(value);
21085
21086 if (!result) {
21087 throw new Error("" + value + " is not a value of any member of " + this.enumName);
21088 }
21089
21090 return result;
21091 }
21092 },
21093 create: {
21094 value: function create(context, name, members) {
21095 var ChildEnum = (function (_Enum) {
21096 var _class = function ChildEnum() {
21097 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
21098 args[_key] = arguments[_key];
21099 }
21100
21101 _classCallCheck(this, _class);
21102
21103 _get(Object.getPrototypeOf(_class.prototype), "constructor", this).apply(this, args);
21104 };
21105
21106 _inherits(_class, _Enum);
21107
21108 return _class;
21109 })(Enum);
21110
21111 ChildEnum.enumName = name;
21112 context.results[name] = ChildEnum;
21113
21114 ChildEnum._members = {};
21115 ChildEnum._byValue = new Map();
21116
21117 each(members, function (value, key) {
21118 var inst = new ChildEnum(key, value);
21119 ChildEnum._members[key] = inst;
21120 ChildEnum._byValue.set(value, inst);
21121 ChildEnum[key] = function () {
21122 return inst;
21123 };
21124 });
21125
21126 return ChildEnum;
21127 }
21128 }
21129 });
21130
21131 return Enum;
21132})();
21133
21134includeIoMixin(Enum);
21135},{"./int":128,"./io-mixin":129,"lodash/each":308,"lodash/values":352}],125:[function(require,module,exports){
21136"use strict";
21137
21138var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21139
21140Object.defineProperty(exports, "__esModule", {
21141 value: true
21142});
21143
21144var isNumber = _interopRequire(require("lodash/isNumber"));
21145
21146var includeIoMixin = _interopRequire(require("./io-mixin"));
21147
21148var Float = {
21149
21150 read: function read(io) {
21151 return io.readFloatBE();
21152 },
21153
21154 write: function write(value, io) {
21155 if (!isNumber(value)) {
21156 throw new Error("XDR Write Error: not a number");
21157 }
21158
21159 io.writeFloatBE(value);
21160 },
21161
21162 isValid: function isValid(value) {
21163 return isNumber(value);
21164 } };
21165
21166exports.Float = Float;
21167includeIoMixin(Float);
21168},{"./io-mixin":129,"lodash/isNumber":328}],126:[function(require,module,exports){
21169"use strict";
21170
21171var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21172
21173var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21174
21175var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
21176
21177var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
21178
21179var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
21180
21181Object.defineProperty(exports, "__esModule", {
21182 value: true
21183});
21184
21185var Long = _interopRequire(require("long"));
21186
21187var includeIoMixin = _interopRequire(require("./io-mixin"));
21188
21189var Hyper = exports.Hyper = (function (_Long) {
21190 function Hyper(low, high) {
21191 _classCallCheck(this, Hyper);
21192
21193 _get(Object.getPrototypeOf(Hyper.prototype), "constructor", this).call(this, low, high, false);
21194 }
21195
21196 _inherits(Hyper, _Long);
21197
21198 _createClass(Hyper, null, {
21199 read: {
21200 value: function read(io) {
21201 var high = io.readInt32BE();
21202 var low = io.readInt32BE();
21203 return this.fromBits(low, high);
21204 }
21205 },
21206 write: {
21207 value: function write(value, io) {
21208 if (!(value instanceof this)) {
21209 throw new Error("XDR Write Error: " + value + " is not a Hyper");
21210 }
21211
21212 io.writeInt32BE(value.high);
21213 io.writeInt32BE(value.low);
21214 }
21215 },
21216 fromString: {
21217 value: function fromString(string) {
21218 if (!/^-?\d+$/.test(string)) {
21219 throw new Error("Invalid hyper string: " + string);
21220 }
21221 var result = _get(Object.getPrototypeOf(Hyper), "fromString", this).call(this, string, false);
21222 return new this(result.low, result.high);
21223 }
21224 },
21225 fromBits: {
21226 value: function fromBits(low, high) {
21227 var result = _get(Object.getPrototypeOf(Hyper), "fromBits", this).call(this, low, high, false);
21228 return new this(result.low, result.high);
21229 }
21230 },
21231 isValid: {
21232 value: function isValid(value) {
21233 return value instanceof this;
21234 }
21235 }
21236 });
21237
21238 return Hyper;
21239})(Long);
21240
21241includeIoMixin(Hyper);
21242
21243Hyper.MAX_VALUE = new Hyper(Long.MAX_VALUE.low, Long.MAX_VALUE.high);
21244Hyper.MIN_VALUE = new Hyper(Long.MIN_VALUE.low, Long.MIN_VALUE.high);
21245},{"./io-mixin":129,"long":353}],127:[function(require,module,exports){
21246"use strict";
21247
21248var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
21249
21250var _defaults = function (obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; };
21251
21252Object.defineProperty(exports, "__esModule", {
21253 value: true
21254});
21255
21256_defaults(exports, _interopRequireWildcard(require("./types")));
21257
21258var _config = require("./config");
21259
21260_defaults(exports, _interopRequireWildcard(_config));
21261
21262var config = _config.config;
21263},{"./config":121,"./types":135}],128:[function(require,module,exports){
21264"use strict";
21265
21266var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21267
21268Object.defineProperty(exports, "__esModule", {
21269 value: true
21270});
21271
21272var isNumber = _interopRequire(require("lodash/isNumber"));
21273
21274var includeIoMixin = _interopRequire(require("./io-mixin"));
21275
21276var Int = {
21277
21278 read: function read(io) {
21279 return io.readInt32BE();
21280 },
21281
21282 write: function write(value, io) {
21283 if (!isNumber(value)) {
21284 throw new Error("XDR Write Error: not a number");
21285 }
21286
21287 if (Math.floor(value) !== value) {
21288 throw new Error("XDR Write Error: not an integer");
21289 }
21290
21291 io.writeInt32BE(value);
21292 },
21293
21294 isValid: function isValid(value) {
21295 if (!isNumber(value)) {
21296 return false;
21297 }
21298 if (Math.floor(value) !== value) {
21299 return false;
21300 }
21301
21302 return value >= Int.MIN_VALUE && value <= Int.MAX_VALUE;
21303 } };
21304
21305exports.Int = Int;
21306Int.MAX_VALUE = Math.pow(2, 31) - 1;
21307Int.MIN_VALUE = -Math.pow(2, 31);
21308
21309includeIoMixin(Int);
21310},{"./io-mixin":129,"lodash/isNumber":328}],129:[function(require,module,exports){
21311(function (Buffer){
21312"use strict";
21313
21314var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21315
21316module.exports = includeIoMixin;
21317
21318var Cursor = require("./cursor").Cursor;
21319
21320var extend = _interopRequire(require("lodash/extend"));
21321
21322var isFunction = _interopRequire(require("lodash/isFunction"));
21323
21324//TODO: build a system to grow a buffer as we write to it
21325var BUFFER_SIZE = Math.pow(2, 16);
21326
21327var staticMethods = {
21328 toXDR: function toXDR(val) {
21329 var cursor = new Cursor(BUFFER_SIZE);
21330 this.write(val, cursor);
21331 var bytesWritten = cursor.tell();
21332 cursor.rewind();
21333
21334 return cursor.slice(bytesWritten).buffer();
21335 },
21336
21337 fromXDR: function fromXDR(input) {
21338 var format = arguments[1] === undefined ? "raw" : arguments[1];
21339
21340 var buffer = undefined;
21341 switch (format) {
21342 case "raw":
21343 buffer = input;break;
21344 case "hex":
21345 buffer = Buffer.from(input, "hex");break;
21346 case "base64":
21347 buffer = Buffer.from(input, "base64");break;
21348 default:
21349 throw new Error("Invalid format " + format + ", must be \"raw\", \"hex\", \"base64\"");
21350 }
21351
21352 var cursor = new Cursor(buffer);
21353 var result = this.read(cursor);
21354
21355 //TODO: error out if the entire buffer isn't consumed
21356
21357 return result;
21358 } };
21359
21360var instanceMethods = {
21361 toXDR: function toXDR() {
21362 var format = arguments[0] === undefined ? "raw" : arguments[0];
21363
21364 var buffer = this.constructor.toXDR(this);
21365 switch (format) {
21366 case "raw":
21367 return buffer;
21368 case "hex":
21369 return buffer.toString("hex");
21370 case "base64":
21371 return buffer.toString("base64");
21372 default:
21373 throw new Error("Invalid format " + format + ", must be \"raw\", \"hex\", \"base64\"");
21374 }
21375 }
21376};
21377
21378function includeIoMixin(obj) {
21379 extend(obj, staticMethods);
21380
21381 if (isFunction(obj)) {
21382 extend(obj.prototype, instanceMethods);
21383 }
21384}
21385}).call(this,require("buffer").Buffer)
21386},{"./cursor":122,"buffer":49,"lodash/extend":311,"lodash/isFunction":324}],130:[function(require,module,exports){
21387(function (Buffer){
21388"use strict";
21389
21390var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21391
21392var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21393
21394var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
21395
21396Object.defineProperty(exports, "__esModule", {
21397 value: true
21398});
21399
21400var _util = require("./util");
21401
21402var calculatePadding = _util.calculatePadding;
21403var slicePadding = _util.slicePadding;
21404
21405var includeIoMixin = _interopRequire(require("./io-mixin"));
21406
21407var Opaque = exports.Opaque = (function () {
21408 function Opaque(length) {
21409 _classCallCheck(this, Opaque);
21410
21411 this._length = length;
21412 this._padding = calculatePadding(length);
21413 }
21414
21415 _createClass(Opaque, {
21416 read: {
21417 value: function read(io) {
21418 var result = io.slice(this._length);
21419 slicePadding(io, this._padding);
21420 return result.buffer();
21421 }
21422 },
21423 write: {
21424 value: function write(value, io) {
21425 if (value.length !== this._length) {
21426 throw new Error("XDR Write Error: Got " + value.length + " bytes, expected " + this._length);
21427 }
21428
21429 io.writeBufferPadded(value);
21430 }
21431 },
21432 isValid: {
21433 value: function isValid(value) {
21434 return Buffer.isBuffer(value) && value.length === this._length;
21435 }
21436 }
21437 });
21438
21439 return Opaque;
21440})();
21441
21442includeIoMixin(Opaque.prototype);
21443}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
21444},{"../../is-buffer/index.js":117,"./io-mixin":129,"./util":139}],131:[function(require,module,exports){
21445"use strict";
21446
21447var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21448
21449var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21450
21451var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
21452
21453Object.defineProperty(exports, "__esModule", {
21454 value: true
21455});
21456
21457var Bool = require("./bool").Bool;
21458
21459var isNull = _interopRequire(require("lodash/isNull"));
21460
21461var isUndefined = _interopRequire(require("lodash/isUndefined"));
21462
21463var includeIoMixin = _interopRequire(require("./io-mixin"));
21464
21465var Option = exports.Option = (function () {
21466 function Option(childType) {
21467 _classCallCheck(this, Option);
21468
21469 this._childType = childType;
21470 }
21471
21472 _createClass(Option, {
21473 read: {
21474 value: function read(io) {
21475 if (Bool.read(io)) {
21476 return this._childType.read(io);
21477 }
21478 }
21479 },
21480 write: {
21481 value: function write(value, io) {
21482 var isPresent = !(isNull(value) || isUndefined(value));
21483
21484 Bool.write(isPresent, io);
21485
21486 if (isPresent) {
21487 this._childType.write(value, io);
21488 }
21489 }
21490 },
21491 isValid: {
21492 value: function isValid(value) {
21493 if (isNull(value)) {
21494 return true;
21495 }
21496 if (isUndefined(value)) {
21497 return true;
21498 }
21499
21500 return this._childType.isValid(value);
21501 }
21502 }
21503 });
21504
21505 return Option;
21506})();
21507
21508includeIoMixin(Option.prototype);
21509},{"./bool":120,"./io-mixin":129,"lodash/isNull":327,"lodash/isUndefined":336}],132:[function(require,module,exports){
21510"use strict";
21511
21512var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21513
21514Object.defineProperty(exports, "__esModule", {
21515 value: true
21516});
21517
21518var includeIoMixin = _interopRequire(require("./io-mixin"));
21519
21520var Quadruple = {
21521 /* jshint unused: false */
21522
21523 read: function read(io) {
21524 throw new Error("XDR Read Error: quadruple not supported");
21525 },
21526
21527 write: function write(value, io) {
21528 throw new Error("XDR Write Error: quadruple not supported");
21529 },
21530
21531 isValid: function isValid(value) {
21532 return false;
21533 } };
21534
21535exports.Quadruple = Quadruple;
21536includeIoMixin(Quadruple);
21537},{"./io-mixin":129}],133:[function(require,module,exports){
21538(function (Buffer){
21539"use strict";
21540
21541var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21542
21543var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21544
21545var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
21546
21547Object.defineProperty(exports, "__esModule", {
21548 value: true
21549});
21550
21551var Int = require("./int").Int;
21552
21553var UnsignedInt = require("./unsigned-int").UnsignedInt;
21554
21555var _util = require("./util");
21556
21557var calculatePadding = _util.calculatePadding;
21558var slicePadding = _util.slicePadding;
21559
21560var isString = _interopRequire(require("lodash/isString"));
21561
21562var isArray = _interopRequire(require("lodash/isArray"));
21563
21564var includeIoMixin = _interopRequire(require("./io-mixin"));
21565
21566var String = exports.String = (function () {
21567 function String() {
21568 var maxLength = arguments[0] === undefined ? UnsignedInt.MAX_VALUE : arguments[0];
21569
21570 _classCallCheck(this, String);
21571
21572 this._maxLength = maxLength;
21573 }
21574
21575 _createClass(String, {
21576 read: {
21577 value: function read(io) {
21578 var length = Int.read(io);
21579
21580 if (length > this._maxLength) {
21581 throw new Error("XDR Read Error: Saw " + length + " length String," + ("max allowed is " + this._maxLength));
21582 }
21583 var padding = calculatePadding(length);
21584 var result = io.slice(length);
21585 slicePadding(io, padding);
21586 return result.buffer();
21587 }
21588 },
21589 readString: {
21590 value: function readString(io) {
21591 return this.read(io).toString("utf8");
21592 }
21593 },
21594 write: {
21595 value: function write(value, io) {
21596 if (value.length > this._maxLength) {
21597 throw new Error("XDR Write Error: Got " + value.length + " bytes," + ("max allows is " + this._maxLength));
21598 }
21599
21600 var buffer = undefined;
21601 if (isString(value)) {
21602 buffer = Buffer.from(value, "utf8");
21603 } else {
21604 buffer = Buffer.from(value);
21605 }
21606
21607 Int.write(buffer.length, io);
21608 io.writeBufferPadded(buffer);
21609 }
21610 },
21611 isValid: {
21612 value: function isValid(value) {
21613 var buffer = undefined;
21614 if (isString(value)) {
21615 buffer = Buffer.from(value, "utf8");
21616 } else if (isArray(value) || Buffer.isBuffer(value)) {
21617 buffer = Buffer.from(value);
21618 } else {
21619 return false;
21620 }
21621 return buffer.length <= this._maxLength;
21622 }
21623 }
21624 });
21625
21626 return String;
21627})();
21628
21629includeIoMixin(String.prototype);
21630}).call(this,require("buffer").Buffer)
21631},{"./int":128,"./io-mixin":129,"./unsigned-int":138,"./util":139,"buffer":49,"lodash/isArray":319,"lodash/isString":333}],134:[function(require,module,exports){
21632"use strict";
21633
21634var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21635
21636var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
21637
21638var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
21639
21640var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
21641
21642var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21643
21644var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
21645
21646Object.defineProperty(exports, "__esModule", {
21647 value: true
21648});
21649
21650var each = _interopRequire(require("lodash/each"));
21651
21652var map = _interopRequire(require("lodash/map"));
21653
21654var isUndefined = _interopRequire(require("lodash/isUndefined"));
21655
21656var fromPairs = _interopRequire(require("lodash/fromPairs"));
21657
21658var Reference = require("./config").Reference;
21659
21660var includeIoMixin = _interopRequire(require("./io-mixin"));
21661
21662var Struct = exports.Struct = (function () {
21663 function Struct(attributes) {
21664 _classCallCheck(this, Struct);
21665
21666 this._attributes = attributes || {};
21667 }
21668
21669 _createClass(Struct, null, {
21670 read: {
21671 value: function read(io) {
21672 var fields = map(this._fields, function (field) {
21673 var _field = _slicedToArray(field, 2);
21674
21675 var name = _field[0];
21676 var type = _field[1];
21677
21678 var value = type.read(io);
21679 return [name, value];
21680 });
21681
21682 return new this(fromPairs(fields));
21683 }
21684 },
21685 write: {
21686 value: function write(value, io) {
21687 if (!(value instanceof this)) {
21688 throw new Error("XDR Write Error: " + value + " is not a " + this.structName);
21689 }
21690 each(this._fields, function (field) {
21691 var _field = _slicedToArray(field, 2);
21692
21693 var name = _field[0];
21694 var type = _field[1];
21695
21696 var attribute = value._attributes[name];
21697 type.write(attribute, io);
21698 });
21699 }
21700 },
21701 isValid: {
21702 value: function isValid(value) {
21703 return value instanceof this;
21704 }
21705 },
21706 create: {
21707 value: function create(context, name, fields) {
21708 var ChildStruct = (function (_Struct) {
21709 var _class = function ChildStruct() {
21710 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
21711 args[_key] = arguments[_key];
21712 }
21713
21714 _classCallCheck(this, _class);
21715
21716 _get(Object.getPrototypeOf(_class.prototype), "constructor", this).apply(this, args);
21717 };
21718
21719 _inherits(_class, _Struct);
21720
21721 return _class;
21722 })(Struct);
21723
21724 ChildStruct.structName = name;
21725
21726 context.results[name] = ChildStruct;
21727
21728 ChildStruct._fields = fields.map(function (_ref) {
21729 var _ref2 = _slicedToArray(_ref, 2);
21730
21731 var name = _ref2[0];
21732 var field = _ref2[1];
21733
21734 if (field instanceof Reference) {
21735 field = field.resolve(context);
21736 }
21737
21738 return [name, field];
21739 });
21740
21741 each(ChildStruct._fields, function (field) {
21742 var _field = _slicedToArray(field, 1);
21743
21744 var fieldName = _field[0];
21745
21746 ChildStruct.prototype[fieldName] = readOrWriteAttribute(fieldName);
21747 });
21748
21749 return ChildStruct;
21750 }
21751 }
21752 });
21753
21754 return Struct;
21755})();
21756
21757includeIoMixin(Struct);
21758
21759function readOrWriteAttribute(name) {
21760 return function (value) {
21761 if (!isUndefined(value)) {
21762 this._attributes[name] = value;
21763 }
21764
21765 return this._attributes[name];
21766 };
21767}
21768},{"./config":121,"./io-mixin":129,"lodash/each":308,"lodash/fromPairs":314,"lodash/isUndefined":336,"lodash/map":339}],135:[function(require,module,exports){
21769"use strict";
21770
21771var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
21772
21773var _defaults = function (obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; };
21774
21775Object.defineProperty(exports, "__esModule", {
21776 value: true
21777});
21778
21779_defaults(exports, _interopRequireWildcard(require("./int")));
21780
21781_defaults(exports, _interopRequireWildcard(require("./hyper")));
21782
21783_defaults(exports, _interopRequireWildcard(require("./unsigned-int")));
21784
21785_defaults(exports, _interopRequireWildcard(require("./unsigned-hyper")));
21786
21787_defaults(exports, _interopRequireWildcard(require("./float")));
21788
21789_defaults(exports, _interopRequireWildcard(require("./double")));
21790
21791_defaults(exports, _interopRequireWildcard(require("./quadruple")));
21792
21793_defaults(exports, _interopRequireWildcard(require("./bool")));
21794
21795_defaults(exports, _interopRequireWildcard(require("./string")));
21796
21797_defaults(exports, _interopRequireWildcard(require("./opaque")));
21798
21799_defaults(exports, _interopRequireWildcard(require("./var-opaque")));
21800
21801_defaults(exports, _interopRequireWildcard(require("./array")));
21802
21803_defaults(exports, _interopRequireWildcard(require("./var-array")));
21804
21805_defaults(exports, _interopRequireWildcard(require("./option")));
21806
21807_defaults(exports, _interopRequireWildcard(require("./void")));
21808
21809_defaults(exports, _interopRequireWildcard(require("./enum")));
21810
21811_defaults(exports, _interopRequireWildcard(require("./struct")));
21812
21813_defaults(exports, _interopRequireWildcard(require("./union")));
21814},{"./array":119,"./bool":120,"./double":123,"./enum":124,"./float":125,"./hyper":126,"./int":128,"./opaque":130,"./option":131,"./quadruple":132,"./string":133,"./struct":134,"./union":136,"./unsigned-hyper":137,"./unsigned-int":138,"./var-array":140,"./var-opaque":141,"./void":142}],136:[function(require,module,exports){
21815"use strict";
21816
21817var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
21818
21819var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
21820
21821var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
21822
21823var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
21824
21825var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
21826
21827var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
21828
21829Object.defineProperty(exports, "__esModule", {
21830 value: true
21831});
21832
21833var each = _interopRequire(require("lodash/each"));
21834
21835var isUndefined = _interopRequire(require("lodash/isUndefined"));
21836
21837var isString = _interopRequire(require("lodash/isString"));
21838
21839var Void = require("./void").Void;
21840
21841var Reference = require("./config").Reference;
21842
21843var includeIoMixin = _interopRequire(require("./io-mixin"));
21844
21845var Union = exports.Union = (function () {
21846 function Union(aSwitch, value) {
21847 _classCallCheck(this, Union);
21848
21849 this.set(aSwitch, value);
21850 }
21851
21852 _createClass(Union, {
21853 set: {
21854 value: function set(aSwitch, value) {
21855 if (isString(aSwitch)) {
21856 aSwitch = this.constructor._switchOn.fromName(aSwitch);
21857 }
21858
21859 this._switch = aSwitch;
21860 this._arm = this.constructor.armForSwitch(this._switch);
21861 this._armType = this.constructor.armTypeForArm(this._arm);
21862 this._value = value;
21863 }
21864 },
21865 get: {
21866 value: function get() {
21867 var armName = arguments[0] === undefined ? this._arm : arguments[0];
21868
21869 if (this._arm !== Void && this._arm !== armName) {
21870 throw new Error("" + armName + " not set");
21871 }
21872 return this._value;
21873 }
21874 },
21875 "switch": {
21876 value: function _switch() {
21877 return this._switch;
21878 }
21879 },
21880 arm: {
21881 value: function arm() {
21882 return this._arm;
21883 }
21884 },
21885 armType: {
21886 value: function armType() {
21887 return this._armType;
21888 }
21889 },
21890 value: {
21891 value: function value() {
21892 return this._value;
21893 }
21894 }
21895 }, {
21896 armForSwitch: {
21897 value: function armForSwitch(aSwitch) {
21898 if (this._switches.has(aSwitch)) {
21899 return this._switches.get(aSwitch);
21900 } else if (this._defaultArm) {
21901 return this._defaultArm;
21902 } else {
21903 throw new Error("Bad union switch: " + aSwitch);
21904 }
21905 }
21906 },
21907 armTypeForArm: {
21908 value: function armTypeForArm(arm) {
21909 if (arm === Void) {
21910 return Void;
21911 } else {
21912 return this._arms[arm];
21913 }
21914 }
21915 },
21916 read: {
21917 value: function read(io) {
21918 var aSwitch = this._switchOn.read(io);
21919 var arm = this.armForSwitch(aSwitch);
21920 var armType = this.armTypeForArm(arm);
21921 var value = armType.read(io);
21922 return new this(aSwitch, value);
21923 }
21924 },
21925 write: {
21926 value: function write(value, io) {
21927 if (!(value instanceof this)) {
21928 throw new Error("XDR Write Error: " + value + " is not a " + this.unionName);
21929 }
21930
21931 this._switchOn.write(value["switch"](), io);
21932 value.armType().write(value.value(), io);
21933 }
21934 },
21935 isValid: {
21936 value: function isValid(value) {
21937 return value instanceof this;
21938 }
21939 },
21940 create: {
21941 value: function create(context, name, config) {
21942 var ChildUnion = (function (_Union) {
21943 var _class = function ChildUnion() {
21944 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
21945 args[_key] = arguments[_key];
21946 }
21947
21948 _classCallCheck(this, _class);
21949
21950 _get(Object.getPrototypeOf(_class.prototype), "constructor", this).apply(this, args);
21951 };
21952
21953 _inherits(_class, _Union);
21954
21955 return _class;
21956 })(Union);
21957
21958 ChildUnion.unionName = name;
21959 context.results[name] = ChildUnion;
21960
21961 if (config.switchOn instanceof Reference) {
21962 ChildUnion._switchOn = config.switchOn.resolve(context);
21963 } else {
21964 ChildUnion._switchOn = config.switchOn;
21965 }
21966
21967 ChildUnion._switches = new Map();
21968 ChildUnion._arms = {};
21969
21970 each(config.arms, function (value, name) {
21971 if (value instanceof Reference) {
21972 value = value.resolve(context);
21973 }
21974
21975 ChildUnion._arms[name] = value;
21976 });
21977
21978 // resolve default arm
21979 var defaultArm = config.defaultArm;
21980 if (defaultArm instanceof Reference) {
21981 defaultArm = defaultArm.resolve(context);
21982 }
21983
21984 ChildUnion._defaultArm = defaultArm;
21985
21986 each(config.switches, function (_ref) {
21987 var _ref2 = _slicedToArray(_ref, 2);
21988
21989 var aSwitch = _ref2[0];
21990 var armName = _ref2[1];
21991
21992 if (isString(aSwitch)) {
21993 aSwitch = ChildUnion._switchOn.fromName(aSwitch);
21994 }
21995
21996 ChildUnion._switches.set(aSwitch, armName);
21997 });
21998
21999 // add enum-based helpers
22000 // NOTE: we don't have good notation for "is a subclass of XDR.Enum",
22001 // and so we use the following check (does _switchOn have a `values`
22002 // attribute) to approximate the intent.
22003 if (!isUndefined(ChildUnion._switchOn.values)) {
22004 each(ChildUnion._switchOn.values(), function (aSwitch) {
22005 // Add enum-based constrocutors
22006 ChildUnion[aSwitch.name] = function (value) {
22007 return new ChildUnion(aSwitch, value);
22008 };
22009
22010 // Add enum-based "set" helpers
22011 ChildUnion.prototype[aSwitch.name] = function (value) {
22012 return this.set(aSwitch, value);
22013 };
22014 });
22015 }
22016
22017 // Add arm accessor helpers
22018 each(ChildUnion._arms, function (type, name) {
22019 if (type === Void) {
22020 return;
22021 }
22022
22023 ChildUnion.prototype[name] = function () {
22024 return this.get(name);
22025 };
22026 });
22027
22028 return ChildUnion;
22029 }
22030 }
22031 });
22032
22033 return Union;
22034})();
22035
22036includeIoMixin(Union);
22037},{"./config":121,"./io-mixin":129,"./void":142,"lodash/each":308,"lodash/isString":333,"lodash/isUndefined":336}],137:[function(require,module,exports){
22038"use strict";
22039
22040var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
22041
22042var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
22043
22044var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
22045
22046var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
22047
22048var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
22049
22050Object.defineProperty(exports, "__esModule", {
22051 value: true
22052});
22053
22054var Long = _interopRequire(require("long"));
22055
22056var includeIoMixin = _interopRequire(require("./io-mixin"));
22057
22058var UnsignedHyper = exports.UnsignedHyper = (function (_Long) {
22059 function UnsignedHyper(low, high) {
22060 _classCallCheck(this, UnsignedHyper);
22061
22062 _get(Object.getPrototypeOf(UnsignedHyper.prototype), "constructor", this).call(this, low, high, true);
22063 }
22064
22065 _inherits(UnsignedHyper, _Long);
22066
22067 _createClass(UnsignedHyper, null, {
22068 read: {
22069 value: function read(io) {
22070 var high = io.readInt32BE();
22071 var low = io.readInt32BE();
22072 return this.fromBits(low, high);
22073 }
22074 },
22075 write: {
22076 value: function write(value, io) {
22077 if (!(value instanceof this)) {
22078 throw new Error("XDR Write Error: " + value + " is not an UnsignedHyper");
22079 }
22080
22081 io.writeInt32BE(value.high);
22082 io.writeInt32BE(value.low);
22083 }
22084 },
22085 fromString: {
22086 value: function fromString(string) {
22087 if (!/^\d+$/.test(string)) {
22088 throw new Error("Invalid hyper string: " + string);
22089 }
22090 var result = _get(Object.getPrototypeOf(UnsignedHyper), "fromString", this).call(this, string, true);
22091 return new this(result.low, result.high);
22092 }
22093 },
22094 fromBits: {
22095 value: function fromBits(low, high) {
22096 var result = _get(Object.getPrototypeOf(UnsignedHyper), "fromBits", this).call(this, low, high, true);
22097 return new this(result.low, result.high);
22098 }
22099 },
22100 isValid: {
22101 value: function isValid(value) {
22102 return value instanceof this;
22103 }
22104 }
22105 });
22106
22107 return UnsignedHyper;
22108})(Long);
22109
22110includeIoMixin(UnsignedHyper);
22111
22112UnsignedHyper.MAX_VALUE = new UnsignedHyper(Long.MAX_UNSIGNED_VALUE.low, Long.MAX_UNSIGNED_VALUE.high);
22113
22114UnsignedHyper.MIN_VALUE = new UnsignedHyper(Long.MIN_VALUE.low, Long.MIN_VALUE.high);
22115},{"./io-mixin":129,"long":353}],138:[function(require,module,exports){
22116"use strict";
22117
22118var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
22119
22120Object.defineProperty(exports, "__esModule", {
22121 value: true
22122});
22123
22124var isNumber = _interopRequire(require("lodash/isNumber"));
22125
22126var includeIoMixin = _interopRequire(require("./io-mixin"));
22127
22128var UnsignedInt = {
22129
22130 read: function read(io) {
22131 return io.readUInt32BE();
22132 },
22133
22134 write: function write(value, io) {
22135 if (!isNumber(value)) {
22136 throw new Error("XDR Write Error: not a number");
22137 }
22138
22139 if (Math.floor(value) !== value) {
22140 throw new Error("XDR Write Error: not an integer");
22141 }
22142
22143 if (value < 0) {
22144 throw new Error("XDR Write Error: negative number " + value);
22145 }
22146
22147 io.writeUInt32BE(value);
22148 },
22149
22150 isValid: function isValid(value) {
22151 if (!isNumber(value)) {
22152 return false;
22153 }
22154 if (Math.floor(value) !== value) {
22155 return false;
22156 }
22157
22158 return value >= UnsignedInt.MIN_VALUE && value <= UnsignedInt.MAX_VALUE;
22159 } };
22160
22161exports.UnsignedInt = UnsignedInt;
22162UnsignedInt.MAX_VALUE = Math.pow(2, 32) - 1;
22163UnsignedInt.MIN_VALUE = 0;
22164
22165includeIoMixin(UnsignedInt);
22166},{"./io-mixin":129,"lodash/isNumber":328}],139:[function(require,module,exports){
22167"use strict";
22168
22169var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
22170
22171exports.calculatePadding = calculatePadding;
22172exports.slicePadding = slicePadding;
22173Object.defineProperty(exports, "__esModule", {
22174 value: true
22175});
22176
22177var every = _interopRequire(require("lodash/every"));
22178
22179function calculatePadding(length) {
22180 switch (length % 4) {
22181 case 0:
22182 return 0;
22183 case 1:
22184 return 3;
22185 case 2:
22186 return 2;
22187 case 3:
22188 return 1;
22189 }
22190}
22191
22192function slicePadding(io, length) {
22193 var padding = io.slice(length);
22194 var allZero = every(padding.buffer(), function (byte) {
22195 return byte === 0;
22196 });
22197
22198 if (allZero !== true) {
22199 throw new Error("XDR Read Error: invalid padding");
22200 }
22201}
22202},{"lodash/every":310}],140:[function(require,module,exports){
22203"use strict";
22204
22205var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
22206
22207var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
22208
22209var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
22210
22211Object.defineProperty(exports, "__esModule", {
22212 value: true
22213});
22214
22215var Int = require("./int").Int;
22216
22217var UnsignedInt = require("./unsigned-int").UnsignedInt;
22218
22219var every = _interopRequire(require("lodash/every"));
22220
22221var each = _interopRequire(require("lodash/each"));
22222
22223var times = _interopRequire(require("lodash/times"));
22224
22225var isArray = _interopRequire(require("lodash/isArray"));
22226
22227var includeIoMixin = _interopRequire(require("./io-mixin"));
22228
22229var VarArray = exports.VarArray = (function () {
22230 function VarArray(childType) {
22231 var maxLength = arguments[1] === undefined ? UnsignedInt.MAX_VALUE : arguments[1];
22232
22233 _classCallCheck(this, VarArray);
22234
22235 this._childType = childType;
22236 this._maxLength = maxLength;
22237 }
22238
22239 _createClass(VarArray, {
22240 read: {
22241 value: function read(io) {
22242 var _this = this;
22243
22244 var length = Int.read(io);
22245
22246 if (length > this._maxLength) {
22247 throw new Error("XDR Read Error: Saw " + length + " length VarArray," + ("max allowed is " + this._maxLength));
22248 }
22249
22250 return times(length, function () {
22251 return _this._childType.read(io);
22252 });
22253 }
22254 },
22255 write: {
22256 value: function write(value, io) {
22257 var _this = this;
22258
22259 if (!isArray(value)) {
22260 throw new Error("XDR Write Error: value is not array");
22261 }
22262
22263 if (value.length > this._maxLength) {
22264 throw new Error("XDR Write Error: Got array of size " + value.length + "," + ("max allowed is " + this._maxLength));
22265 }
22266
22267 Int.write(value.length, io);
22268 each(value, function (child) {
22269 return _this._childType.write(child, io);
22270 });
22271 }
22272 },
22273 isValid: {
22274 value: function isValid(value) {
22275 var _this = this;
22276
22277 if (!isArray(value)) {
22278 return false;
22279 }
22280 if (value.length > this._maxLength) {
22281 return false;
22282 }
22283
22284 return every(value, function (child) {
22285 return _this._childType.isValid(child);
22286 });
22287 }
22288 }
22289 });
22290
22291 return VarArray;
22292})();
22293
22294includeIoMixin(VarArray.prototype);
22295},{"./int":128,"./io-mixin":129,"./unsigned-int":138,"lodash/each":308,"lodash/every":310,"lodash/isArray":319,"lodash/times":346}],141:[function(require,module,exports){
22296(function (Buffer){
22297"use strict";
22298
22299var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
22300
22301var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
22302
22303var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
22304
22305Object.defineProperty(exports, "__esModule", {
22306 value: true
22307});
22308
22309var Int = require("./int").Int;
22310
22311var UnsignedInt = require("./unsigned-int").UnsignedInt;
22312
22313var _util = require("./util");
22314
22315var calculatePadding = _util.calculatePadding;
22316var slicePadding = _util.slicePadding;
22317
22318var includeIoMixin = _interopRequire(require("./io-mixin"));
22319
22320var VarOpaque = exports.VarOpaque = (function () {
22321 function VarOpaque() {
22322 var maxLength = arguments[0] === undefined ? UnsignedInt.MAX_VALUE : arguments[0];
22323
22324 _classCallCheck(this, VarOpaque);
22325
22326 this._maxLength = maxLength;
22327 }
22328
22329 _createClass(VarOpaque, {
22330 read: {
22331 value: function read(io) {
22332 var length = Int.read(io);
22333
22334 if (length > this._maxLength) {
22335 throw new Error("XDR Read Error: Saw " + length + " length VarOpaque," + ("max allowed is " + this._maxLength));
22336 }
22337 var padding = calculatePadding(length);
22338 var result = io.slice(length);
22339 slicePadding(io, padding);
22340 return result.buffer();
22341 }
22342 },
22343 write: {
22344 value: function write(value, io) {
22345 if (value.length > this._maxLength) {
22346 throw new Error("XDR Write Error: Got " + value.length + " bytes," + ("max allows is " + this._maxLength));
22347 }
22348 Int.write(value.length, io);
22349 io.writeBufferPadded(value);
22350 }
22351 },
22352 isValid: {
22353 value: function isValid(value) {
22354 return Buffer.isBuffer(value) && value.length <= this._maxLength;
22355 }
22356 }
22357 });
22358
22359 return VarOpaque;
22360})();
22361
22362includeIoMixin(VarOpaque.prototype);
22363}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
22364},{"../../is-buffer/index.js":117,"./int":128,"./io-mixin":129,"./unsigned-int":138,"./util":139}],142:[function(require,module,exports){
22365"use strict";
22366
22367var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
22368
22369Object.defineProperty(exports, "__esModule", {
22370 value: true
22371});
22372
22373var isUndefined = _interopRequire(require("lodash/isUndefined"));
22374
22375var includeIoMixin = _interopRequire(require("./io-mixin"));
22376
22377var Void = {
22378 /* jshint unused: false */
22379
22380 read: function read(io) {
22381 return undefined;
22382 },
22383
22384 write: function write(value, io) {
22385 if (!isUndefined(value)) {
22386 throw new Error("XDR Write Error: trying to write value to a void slot");
22387 }
22388 },
22389
22390 isValid: function isValid(value) {
22391 return isUndefined(value);
22392 } };
22393
22394exports.Void = Void;
22395includeIoMixin(Void);
22396},{"./io-mixin":129,"lodash/isUndefined":336}],143:[function(require,module,exports){
22397var getNative = require('./_getNative'),
22398 root = require('./_root');
22399
22400/* Built-in method references that are verified to be native. */
22401var DataView = getNative(root, 'DataView');
22402
22403module.exports = DataView;
22404
22405},{"./_getNative":241,"./_root":286}],144:[function(require,module,exports){
22406var hashClear = require('./_hashClear'),
22407 hashDelete = require('./_hashDelete'),
22408 hashGet = require('./_hashGet'),
22409 hashHas = require('./_hashHas'),
22410 hashSet = require('./_hashSet');
22411
22412/**
22413 * Creates a hash object.
22414 *
22415 * @private
22416 * @constructor
22417 * @param {Array} [entries] The key-value pairs to cache.
22418 */
22419function Hash(entries) {
22420 var index = -1,
22421 length = entries == null ? 0 : entries.length;
22422
22423 this.clear();
22424 while (++index < length) {
22425 var entry = entries[index];
22426 this.set(entry[0], entry[1]);
22427 }
22428}
22429
22430// Add methods to `Hash`.
22431Hash.prototype.clear = hashClear;
22432Hash.prototype['delete'] = hashDelete;
22433Hash.prototype.get = hashGet;
22434Hash.prototype.has = hashHas;
22435Hash.prototype.set = hashSet;
22436
22437module.exports = Hash;
22438
22439},{"./_hashClear":250,"./_hashDelete":251,"./_hashGet":252,"./_hashHas":253,"./_hashSet":254}],145:[function(require,module,exports){
22440var listCacheClear = require('./_listCacheClear'),
22441 listCacheDelete = require('./_listCacheDelete'),
22442 listCacheGet = require('./_listCacheGet'),
22443 listCacheHas = require('./_listCacheHas'),
22444 listCacheSet = require('./_listCacheSet');
22445
22446/**
22447 * Creates an list cache object.
22448 *
22449 * @private
22450 * @constructor
22451 * @param {Array} [entries] The key-value pairs to cache.
22452 */
22453function ListCache(entries) {
22454 var index = -1,
22455 length = entries == null ? 0 : entries.length;
22456
22457 this.clear();
22458 while (++index < length) {
22459 var entry = entries[index];
22460 this.set(entry[0], entry[1]);
22461 }
22462}
22463
22464// Add methods to `ListCache`.
22465ListCache.prototype.clear = listCacheClear;
22466ListCache.prototype['delete'] = listCacheDelete;
22467ListCache.prototype.get = listCacheGet;
22468ListCache.prototype.has = listCacheHas;
22469ListCache.prototype.set = listCacheSet;
22470
22471module.exports = ListCache;
22472
22473},{"./_listCacheClear":266,"./_listCacheDelete":267,"./_listCacheGet":268,"./_listCacheHas":269,"./_listCacheSet":270}],146:[function(require,module,exports){
22474var getNative = require('./_getNative'),
22475 root = require('./_root');
22476
22477/* Built-in method references that are verified to be native. */
22478var Map = getNative(root, 'Map');
22479
22480module.exports = Map;
22481
22482},{"./_getNative":241,"./_root":286}],147:[function(require,module,exports){
22483var mapCacheClear = require('./_mapCacheClear'),
22484 mapCacheDelete = require('./_mapCacheDelete'),
22485 mapCacheGet = require('./_mapCacheGet'),
22486 mapCacheHas = require('./_mapCacheHas'),
22487 mapCacheSet = require('./_mapCacheSet');
22488
22489/**
22490 * Creates a map cache object to store key-value pairs.
22491 *
22492 * @private
22493 * @constructor
22494 * @param {Array} [entries] The key-value pairs to cache.
22495 */
22496function MapCache(entries) {
22497 var index = -1,
22498 length = entries == null ? 0 : entries.length;
22499
22500 this.clear();
22501 while (++index < length) {
22502 var entry = entries[index];
22503 this.set(entry[0], entry[1]);
22504 }
22505}
22506
22507// Add methods to `MapCache`.
22508MapCache.prototype.clear = mapCacheClear;
22509MapCache.prototype['delete'] = mapCacheDelete;
22510MapCache.prototype.get = mapCacheGet;
22511MapCache.prototype.has = mapCacheHas;
22512MapCache.prototype.set = mapCacheSet;
22513
22514module.exports = MapCache;
22515
22516},{"./_mapCacheClear":271,"./_mapCacheDelete":272,"./_mapCacheGet":273,"./_mapCacheHas":274,"./_mapCacheSet":275}],148:[function(require,module,exports){
22517var getNative = require('./_getNative'),
22518 root = require('./_root');
22519
22520/* Built-in method references that are verified to be native. */
22521var Promise = getNative(root, 'Promise');
22522
22523module.exports = Promise;
22524
22525},{"./_getNative":241,"./_root":286}],149:[function(require,module,exports){
22526var getNative = require('./_getNative'),
22527 root = require('./_root');
22528
22529/* Built-in method references that are verified to be native. */
22530var Set = getNative(root, 'Set');
22531
22532module.exports = Set;
22533
22534},{"./_getNative":241,"./_root":286}],150:[function(require,module,exports){
22535var MapCache = require('./_MapCache'),
22536 setCacheAdd = require('./_setCacheAdd'),
22537 setCacheHas = require('./_setCacheHas');
22538
22539/**
22540 *
22541 * Creates an array cache object to store unique values.
22542 *
22543 * @private
22544 * @constructor
22545 * @param {Array} [values] The values to cache.
22546 */
22547function SetCache(values) {
22548 var index = -1,
22549 length = values == null ? 0 : values.length;
22550
22551 this.__data__ = new MapCache;
22552 while (++index < length) {
22553 this.add(values[index]);
22554 }
22555}
22556
22557// Add methods to `SetCache`.
22558SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
22559SetCache.prototype.has = setCacheHas;
22560
22561module.exports = SetCache;
22562
22563},{"./_MapCache":147,"./_setCacheAdd":287,"./_setCacheHas":288}],151:[function(require,module,exports){
22564var ListCache = require('./_ListCache'),
22565 stackClear = require('./_stackClear'),
22566 stackDelete = require('./_stackDelete'),
22567 stackGet = require('./_stackGet'),
22568 stackHas = require('./_stackHas'),
22569 stackSet = require('./_stackSet');
22570
22571/**
22572 * Creates a stack cache object to store key-value pairs.
22573 *
22574 * @private
22575 * @constructor
22576 * @param {Array} [entries] The key-value pairs to cache.
22577 */
22578function Stack(entries) {
22579 var data = this.__data__ = new ListCache(entries);
22580 this.size = data.size;
22581}
22582
22583// Add methods to `Stack`.
22584Stack.prototype.clear = stackClear;
22585Stack.prototype['delete'] = stackDelete;
22586Stack.prototype.get = stackGet;
22587Stack.prototype.has = stackHas;
22588Stack.prototype.set = stackSet;
22589
22590module.exports = Stack;
22591
22592},{"./_ListCache":145,"./_stackClear":292,"./_stackDelete":293,"./_stackGet":294,"./_stackHas":295,"./_stackSet":296}],152:[function(require,module,exports){
22593var root = require('./_root');
22594
22595/** Built-in value references. */
22596var Symbol = root.Symbol;
22597
22598module.exports = Symbol;
22599
22600},{"./_root":286}],153:[function(require,module,exports){
22601var root = require('./_root');
22602
22603/** Built-in value references. */
22604var Uint8Array = root.Uint8Array;
22605
22606module.exports = Uint8Array;
22607
22608},{"./_root":286}],154:[function(require,module,exports){
22609var getNative = require('./_getNative'),
22610 root = require('./_root');
22611
22612/* Built-in method references that are verified to be native. */
22613var WeakMap = getNative(root, 'WeakMap');
22614
22615module.exports = WeakMap;
22616
22617},{"./_getNative":241,"./_root":286}],155:[function(require,module,exports){
22618/**
22619 * A faster alternative to `Function#apply`, this function invokes `func`
22620 * with the `this` binding of `thisArg` and the arguments of `args`.
22621 *
22622 * @private
22623 * @param {Function} func The function to invoke.
22624 * @param {*} thisArg The `this` binding of `func`.
22625 * @param {Array} args The arguments to invoke `func` with.
22626 * @returns {*} Returns the result of `func`.
22627 */
22628function apply(func, thisArg, args) {
22629 switch (args.length) {
22630 case 0: return func.call(thisArg);
22631 case 1: return func.call(thisArg, args[0]);
22632 case 2: return func.call(thisArg, args[0], args[1]);
22633 case 3: return func.call(thisArg, args[0], args[1], args[2]);
22634 }
22635 return func.apply(thisArg, args);
22636}
22637
22638module.exports = apply;
22639
22640},{}],156:[function(require,module,exports){
22641/**
22642 * A specialized version of `_.forEach` for arrays without support for
22643 * iteratee shorthands.
22644 *
22645 * @private
22646 * @param {Array} [array] The array to iterate over.
22647 * @param {Function} iteratee The function invoked per iteration.
22648 * @returns {Array} Returns `array`.
22649 */
22650function arrayEach(array, iteratee) {
22651 var index = -1,
22652 length = array == null ? 0 : array.length;
22653
22654 while (++index < length) {
22655 if (iteratee(array[index], index, array) === false) {
22656 break;
22657 }
22658 }
22659 return array;
22660}
22661
22662module.exports = arrayEach;
22663
22664},{}],157:[function(require,module,exports){
22665/**
22666 * A specialized version of `_.every` for arrays without support for
22667 * iteratee shorthands.
22668 *
22669 * @private
22670 * @param {Array} [array] The array to iterate over.
22671 * @param {Function} predicate The function invoked per iteration.
22672 * @returns {boolean} Returns `true` if all elements pass the predicate check,
22673 * else `false`.
22674 */
22675function arrayEvery(array, predicate) {
22676 var index = -1,
22677 length = array == null ? 0 : array.length;
22678
22679 while (++index < length) {
22680 if (!predicate(array[index], index, array)) {
22681 return false;
22682 }
22683 }
22684 return true;
22685}
22686
22687module.exports = arrayEvery;
22688
22689},{}],158:[function(require,module,exports){
22690/**
22691 * A specialized version of `_.filter` for arrays without support for
22692 * iteratee shorthands.
22693 *
22694 * @private
22695 * @param {Array} [array] The array to iterate over.
22696 * @param {Function} predicate The function invoked per iteration.
22697 * @returns {Array} Returns the new filtered array.
22698 */
22699function arrayFilter(array, predicate) {
22700 var index = -1,
22701 length = array == null ? 0 : array.length,
22702 resIndex = 0,
22703 result = [];
22704
22705 while (++index < length) {
22706 var value = array[index];
22707 if (predicate(value, index, array)) {
22708 result[resIndex++] = value;
22709 }
22710 }
22711 return result;
22712}
22713
22714module.exports = arrayFilter;
22715
22716},{}],159:[function(require,module,exports){
22717var baseTimes = require('./_baseTimes'),
22718 isArguments = require('./isArguments'),
22719 isArray = require('./isArray'),
22720 isBuffer = require('./isBuffer'),
22721 isIndex = require('./_isIndex'),
22722 isTypedArray = require('./isTypedArray');
22723
22724/** Used for built-in method references. */
22725var objectProto = Object.prototype;
22726
22727/** Used to check objects for own properties. */
22728var hasOwnProperty = objectProto.hasOwnProperty;
22729
22730/**
22731 * Creates an array of the enumerable property names of the array-like `value`.
22732 *
22733 * @private
22734 * @param {*} value The value to query.
22735 * @param {boolean} inherited Specify returning inherited property names.
22736 * @returns {Array} Returns the array of property names.
22737 */
22738function arrayLikeKeys(value, inherited) {
22739 var isArr = isArray(value),
22740 isArg = !isArr && isArguments(value),
22741 isBuff = !isArr && !isArg && isBuffer(value),
22742 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
22743 skipIndexes = isArr || isArg || isBuff || isType,
22744 result = skipIndexes ? baseTimes(value.length, String) : [],
22745 length = result.length;
22746
22747 for (var key in value) {
22748 if ((inherited || hasOwnProperty.call(value, key)) &&
22749 !(skipIndexes && (
22750 // Safari 9 has enumerable `arguments.length` in strict mode.
22751 key == 'length' ||
22752 // Node.js 0.10 has enumerable non-index properties on buffers.
22753 (isBuff && (key == 'offset' || key == 'parent')) ||
22754 // PhantomJS 2 has enumerable non-index properties on typed arrays.
22755 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
22756 // Skip index properties.
22757 isIndex(key, length)
22758 ))) {
22759 result.push(key);
22760 }
22761 }
22762 return result;
22763}
22764
22765module.exports = arrayLikeKeys;
22766
22767},{"./_baseTimes":207,"./_isIndex":259,"./isArguments":318,"./isArray":319,"./isBuffer":322,"./isTypedArray":335}],160:[function(require,module,exports){
22768/**
22769 * A specialized version of `_.map` for arrays without support for iteratee
22770 * shorthands.
22771 *
22772 * @private
22773 * @param {Array} [array] The array to iterate over.
22774 * @param {Function} iteratee The function invoked per iteration.
22775 * @returns {Array} Returns the new mapped array.
22776 */
22777function arrayMap(array, iteratee) {
22778 var index = -1,
22779 length = array == null ? 0 : array.length,
22780 result = Array(length);
22781
22782 while (++index < length) {
22783 result[index] = iteratee(array[index], index, array);
22784 }
22785 return result;
22786}
22787
22788module.exports = arrayMap;
22789
22790},{}],161:[function(require,module,exports){
22791/**
22792 * Appends the elements of `values` to `array`.
22793 *
22794 * @private
22795 * @param {Array} array The array to modify.
22796 * @param {Array} values The values to append.
22797 * @returns {Array} Returns `array`.
22798 */
22799function arrayPush(array, values) {
22800 var index = -1,
22801 length = values.length,
22802 offset = array.length;
22803
22804 while (++index < length) {
22805 array[offset + index] = values[index];
22806 }
22807 return array;
22808}
22809
22810module.exports = arrayPush;
22811
22812},{}],162:[function(require,module,exports){
22813/**
22814 * A specialized version of `_.some` for arrays without support for iteratee
22815 * shorthands.
22816 *
22817 * @private
22818 * @param {Array} [array] The array to iterate over.
22819 * @param {Function} predicate The function invoked per iteration.
22820 * @returns {boolean} Returns `true` if any element passes the predicate check,
22821 * else `false`.
22822 */
22823function arraySome(array, predicate) {
22824 var index = -1,
22825 length = array == null ? 0 : array.length;
22826
22827 while (++index < length) {
22828 if (predicate(array[index], index, array)) {
22829 return true;
22830 }
22831 }
22832 return false;
22833}
22834
22835module.exports = arraySome;
22836
22837},{}],163:[function(require,module,exports){
22838var baseProperty = require('./_baseProperty');
22839
22840/**
22841 * Gets the size of an ASCII `string`.
22842 *
22843 * @private
22844 * @param {string} string The string inspect.
22845 * @returns {number} Returns the string size.
22846 */
22847var asciiSize = baseProperty('length');
22848
22849module.exports = asciiSize;
22850
22851},{"./_baseProperty":200}],164:[function(require,module,exports){
22852/**
22853 * Converts an ASCII `string` to an array.
22854 *
22855 * @private
22856 * @param {string} string The string to convert.
22857 * @returns {Array} Returns the converted array.
22858 */
22859function asciiToArray(string) {
22860 return string.split('');
22861}
22862
22863module.exports = asciiToArray;
22864
22865},{}],165:[function(require,module,exports){
22866var baseAssignValue = require('./_baseAssignValue'),
22867 eq = require('./eq');
22868
22869/** Used for built-in method references. */
22870var objectProto = Object.prototype;
22871
22872/** Used to check objects for own properties. */
22873var hasOwnProperty = objectProto.hasOwnProperty;
22874
22875/**
22876 * Assigns `value` to `key` of `object` if the existing value is not equivalent
22877 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
22878 * for equality comparisons.
22879 *
22880 * @private
22881 * @param {Object} object The object to modify.
22882 * @param {string} key The key of the property to assign.
22883 * @param {*} value The value to assign.
22884 */
22885function assignValue(object, key, value) {
22886 var objValue = object[key];
22887 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
22888 (value === undefined && !(key in object))) {
22889 baseAssignValue(object, key, value);
22890 }
22891}
22892
22893module.exports = assignValue;
22894
22895},{"./_baseAssignValue":169,"./eq":309}],166:[function(require,module,exports){
22896var eq = require('./eq');
22897
22898/**
22899 * Gets the index at which the `key` is found in `array` of key-value pairs.
22900 *
22901 * @private
22902 * @param {Array} array The array to inspect.
22903 * @param {*} key The key to search for.
22904 * @returns {number} Returns the index of the matched value, else `-1`.
22905 */
22906function assocIndexOf(array, key) {
22907 var length = array.length;
22908 while (length--) {
22909 if (eq(array[length][0], key)) {
22910 return length;
22911 }
22912 }
22913 return -1;
22914}
22915
22916module.exports = assocIndexOf;
22917
22918},{"./eq":309}],167:[function(require,module,exports){
22919var copyObject = require('./_copyObject'),
22920 keys = require('./keys');
22921
22922/**
22923 * The base implementation of `_.assign` without support for multiple sources
22924 * or `customizer` functions.
22925 *
22926 * @private
22927 * @param {Object} object The destination object.
22928 * @param {Object} source The source object.
22929 * @returns {Object} Returns `object`.
22930 */
22931function baseAssign(object, source) {
22932 return object && copyObject(source, keys(source), object);
22933}
22934
22935module.exports = baseAssign;
22936
22937},{"./_copyObject":223,"./keys":337}],168:[function(require,module,exports){
22938var copyObject = require('./_copyObject'),
22939 keysIn = require('./keysIn');
22940
22941/**
22942 * The base implementation of `_.assignIn` without support for multiple sources
22943 * or `customizer` functions.
22944 *
22945 * @private
22946 * @param {Object} object The destination object.
22947 * @param {Object} source The source object.
22948 * @returns {Object} Returns `object`.
22949 */
22950function baseAssignIn(object, source) {
22951 return object && copyObject(source, keysIn(source), object);
22952}
22953
22954module.exports = baseAssignIn;
22955
22956},{"./_copyObject":223,"./keysIn":338}],169:[function(require,module,exports){
22957var defineProperty = require('./_defineProperty');
22958
22959/**
22960 * The base implementation of `assignValue` and `assignMergeValue` without
22961 * value checks.
22962 *
22963 * @private
22964 * @param {Object} object The object to modify.
22965 * @param {string} key The key of the property to assign.
22966 * @param {*} value The value to assign.
22967 */
22968function baseAssignValue(object, key, value) {
22969 if (key == '__proto__' && defineProperty) {
22970 defineProperty(object, key, {
22971 'configurable': true,
22972 'enumerable': true,
22973 'value': value,
22974 'writable': true
22975 });
22976 } else {
22977 object[key] = value;
22978 }
22979}
22980
22981module.exports = baseAssignValue;
22982
22983},{"./_defineProperty":231}],170:[function(require,module,exports){
22984var Stack = require('./_Stack'),
22985 arrayEach = require('./_arrayEach'),
22986 assignValue = require('./_assignValue'),
22987 baseAssign = require('./_baseAssign'),
22988 baseAssignIn = require('./_baseAssignIn'),
22989 cloneBuffer = require('./_cloneBuffer'),
22990 copyArray = require('./_copyArray'),
22991 copySymbols = require('./_copySymbols'),
22992 copySymbolsIn = require('./_copySymbolsIn'),
22993 getAllKeys = require('./_getAllKeys'),
22994 getAllKeysIn = require('./_getAllKeysIn'),
22995 getTag = require('./_getTag'),
22996 initCloneArray = require('./_initCloneArray'),
22997 initCloneByTag = require('./_initCloneByTag'),
22998 initCloneObject = require('./_initCloneObject'),
22999 isArray = require('./isArray'),
23000 isBuffer = require('./isBuffer'),
23001 isMap = require('./isMap'),
23002 isObject = require('./isObject'),
23003 isSet = require('./isSet'),
23004 keys = require('./keys');
23005
23006/** Used to compose bitmasks for cloning. */
23007var CLONE_DEEP_FLAG = 1,
23008 CLONE_FLAT_FLAG = 2,
23009 CLONE_SYMBOLS_FLAG = 4;
23010
23011/** `Object#toString` result references. */
23012var argsTag = '[object Arguments]',
23013 arrayTag = '[object Array]',
23014 boolTag = '[object Boolean]',
23015 dateTag = '[object Date]',
23016 errorTag = '[object Error]',
23017 funcTag = '[object Function]',
23018 genTag = '[object GeneratorFunction]',
23019 mapTag = '[object Map]',
23020 numberTag = '[object Number]',
23021 objectTag = '[object Object]',
23022 regexpTag = '[object RegExp]',
23023 setTag = '[object Set]',
23024 stringTag = '[object String]',
23025 symbolTag = '[object Symbol]',
23026 weakMapTag = '[object WeakMap]';
23027
23028var arrayBufferTag = '[object ArrayBuffer]',
23029 dataViewTag = '[object DataView]',
23030 float32Tag = '[object Float32Array]',
23031 float64Tag = '[object Float64Array]',
23032 int8Tag = '[object Int8Array]',
23033 int16Tag = '[object Int16Array]',
23034 int32Tag = '[object Int32Array]',
23035 uint8Tag = '[object Uint8Array]',
23036 uint8ClampedTag = '[object Uint8ClampedArray]',
23037 uint16Tag = '[object Uint16Array]',
23038 uint32Tag = '[object Uint32Array]';
23039
23040/** Used to identify `toStringTag` values supported by `_.clone`. */
23041var cloneableTags = {};
23042cloneableTags[argsTag] = cloneableTags[arrayTag] =
23043cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
23044cloneableTags[boolTag] = cloneableTags[dateTag] =
23045cloneableTags[float32Tag] = cloneableTags[float64Tag] =
23046cloneableTags[int8Tag] = cloneableTags[int16Tag] =
23047cloneableTags[int32Tag] = cloneableTags[mapTag] =
23048cloneableTags[numberTag] = cloneableTags[objectTag] =
23049cloneableTags[regexpTag] = cloneableTags[setTag] =
23050cloneableTags[stringTag] = cloneableTags[symbolTag] =
23051cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
23052cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
23053cloneableTags[errorTag] = cloneableTags[funcTag] =
23054cloneableTags[weakMapTag] = false;
23055
23056/**
23057 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
23058 * traversed objects.
23059 *
23060 * @private
23061 * @param {*} value The value to clone.
23062 * @param {boolean} bitmask The bitmask flags.
23063 * 1 - Deep clone
23064 * 2 - Flatten inherited properties
23065 * 4 - Clone symbols
23066 * @param {Function} [customizer] The function to customize cloning.
23067 * @param {string} [key] The key of `value`.
23068 * @param {Object} [object] The parent object of `value`.
23069 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
23070 * @returns {*} Returns the cloned value.
23071 */
23072function baseClone(value, bitmask, customizer, key, object, stack) {
23073 var result,
23074 isDeep = bitmask & CLONE_DEEP_FLAG,
23075 isFlat = bitmask & CLONE_FLAT_FLAG,
23076 isFull = bitmask & CLONE_SYMBOLS_FLAG;
23077
23078 if (customizer) {
23079 result = object ? customizer(value, key, object, stack) : customizer(value);
23080 }
23081 if (result !== undefined) {
23082 return result;
23083 }
23084 if (!isObject(value)) {
23085 return value;
23086 }
23087 var isArr = isArray(value);
23088 if (isArr) {
23089 result = initCloneArray(value);
23090 if (!isDeep) {
23091 return copyArray(value, result);
23092 }
23093 } else {
23094 var tag = getTag(value),
23095 isFunc = tag == funcTag || tag == genTag;
23096
23097 if (isBuffer(value)) {
23098 return cloneBuffer(value, isDeep);
23099 }
23100 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
23101 result = (isFlat || isFunc) ? {} : initCloneObject(value);
23102 if (!isDeep) {
23103 return isFlat
23104 ? copySymbolsIn(value, baseAssignIn(result, value))
23105 : copySymbols(value, baseAssign(result, value));
23106 }
23107 } else {
23108 if (!cloneableTags[tag]) {
23109 return object ? value : {};
23110 }
23111 result = initCloneByTag(value, tag, isDeep);
23112 }
23113 }
23114 // Check for circular references and return its corresponding clone.
23115 stack || (stack = new Stack);
23116 var stacked = stack.get(value);
23117 if (stacked) {
23118 return stacked;
23119 }
23120 stack.set(value, result);
23121
23122 if (isSet(value)) {
23123 value.forEach(function(subValue) {
23124 result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
23125 });
23126
23127 return result;
23128 }
23129
23130 if (isMap(value)) {
23131 value.forEach(function(subValue, key) {
23132 result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
23133 });
23134
23135 return result;
23136 }
23137
23138 var keysFunc = isFull
23139 ? (isFlat ? getAllKeysIn : getAllKeys)
23140 : (isFlat ? keysIn : keys);
23141
23142 var props = isArr ? undefined : keysFunc(value);
23143 arrayEach(props || value, function(subValue, key) {
23144 if (props) {
23145 key = subValue;
23146 subValue = value[key];
23147 }
23148 // Recursively populate clone (susceptible to call stack limits).
23149 assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
23150 });
23151 return result;
23152}
23153
23154module.exports = baseClone;
23155
23156},{"./_Stack":151,"./_arrayEach":156,"./_assignValue":165,"./_baseAssign":167,"./_baseAssignIn":168,"./_cloneBuffer":217,"./_copyArray":222,"./_copySymbols":224,"./_copySymbolsIn":225,"./_getAllKeys":237,"./_getAllKeysIn":238,"./_getTag":246,"./_initCloneArray":255,"./_initCloneByTag":256,"./_initCloneObject":257,"./isArray":319,"./isBuffer":322,"./isMap":326,"./isObject":329,"./isSet":332,"./keys":337}],171:[function(require,module,exports){
23157var isObject = require('./isObject');
23158
23159/** Built-in value references. */
23160var objectCreate = Object.create;
23161
23162/**
23163 * The base implementation of `_.create` without support for assigning
23164 * properties to the created object.
23165 *
23166 * @private
23167 * @param {Object} proto The object to inherit from.
23168 * @returns {Object} Returns the new object.
23169 */
23170var baseCreate = (function() {
23171 function object() {}
23172 return function(proto) {
23173 if (!isObject(proto)) {
23174 return {};
23175 }
23176 if (objectCreate) {
23177 return objectCreate(proto);
23178 }
23179 object.prototype = proto;
23180 var result = new object;
23181 object.prototype = undefined;
23182 return result;
23183 };
23184}());
23185
23186module.exports = baseCreate;
23187
23188},{"./isObject":329}],172:[function(require,module,exports){
23189var baseForOwn = require('./_baseForOwn'),
23190 createBaseEach = require('./_createBaseEach');
23191
23192/**
23193 * The base implementation of `_.forEach` without support for iteratee shorthands.
23194 *
23195 * @private
23196 * @param {Array|Object} collection The collection to iterate over.
23197 * @param {Function} iteratee The function invoked per iteration.
23198 * @returns {Array|Object} Returns `collection`.
23199 */
23200var baseEach = createBaseEach(baseForOwn);
23201
23202module.exports = baseEach;
23203
23204},{"./_baseForOwn":177,"./_createBaseEach":228}],173:[function(require,module,exports){
23205var baseEach = require('./_baseEach');
23206
23207/**
23208 * The base implementation of `_.every` without support for iteratee shorthands.
23209 *
23210 * @private
23211 * @param {Array|Object} collection The collection to iterate over.
23212 * @param {Function} predicate The function invoked per iteration.
23213 * @returns {boolean} Returns `true` if all elements pass the predicate check,
23214 * else `false`
23215 */
23216function baseEvery(collection, predicate) {
23217 var result = true;
23218 baseEach(collection, function(value, index, collection) {
23219 result = !!predicate(value, index, collection);
23220 return result;
23221 });
23222 return result;
23223}
23224
23225module.exports = baseEvery;
23226
23227},{"./_baseEach":172}],174:[function(require,module,exports){
23228/**
23229 * The base implementation of `_.findIndex` and `_.findLastIndex` without
23230 * support for iteratee shorthands.
23231 *
23232 * @private
23233 * @param {Array} array The array to inspect.
23234 * @param {Function} predicate The function invoked per iteration.
23235 * @param {number} fromIndex The index to search from.
23236 * @param {boolean} [fromRight] Specify iterating from right to left.
23237 * @returns {number} Returns the index of the matched value, else `-1`.
23238 */
23239function baseFindIndex(array, predicate, fromIndex, fromRight) {
23240 var length = array.length,
23241 index = fromIndex + (fromRight ? 1 : -1);
23242
23243 while ((fromRight ? index-- : ++index < length)) {
23244 if (predicate(array[index], index, array)) {
23245 return index;
23246 }
23247 }
23248 return -1;
23249}
23250
23251module.exports = baseFindIndex;
23252
23253},{}],175:[function(require,module,exports){
23254var arrayPush = require('./_arrayPush'),
23255 isFlattenable = require('./_isFlattenable');
23256
23257/**
23258 * The base implementation of `_.flatten` with support for restricting flattening.
23259 *
23260 * @private
23261 * @param {Array} array The array to flatten.
23262 * @param {number} depth The maximum recursion depth.
23263 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
23264 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
23265 * @param {Array} [result=[]] The initial result value.
23266 * @returns {Array} Returns the new flattened array.
23267 */
23268function baseFlatten(array, depth, predicate, isStrict, result) {
23269 var index = -1,
23270 length = array.length;
23271
23272 predicate || (predicate = isFlattenable);
23273 result || (result = []);
23274
23275 while (++index < length) {
23276 var value = array[index];
23277 if (depth > 0 && predicate(value)) {
23278 if (depth > 1) {
23279 // Recursively flatten arrays (susceptible to call stack limits).
23280 baseFlatten(value, depth - 1, predicate, isStrict, result);
23281 } else {
23282 arrayPush(result, value);
23283 }
23284 } else if (!isStrict) {
23285 result[result.length] = value;
23286 }
23287 }
23288 return result;
23289}
23290
23291module.exports = baseFlatten;
23292
23293},{"./_arrayPush":161,"./_isFlattenable":258}],176:[function(require,module,exports){
23294var createBaseFor = require('./_createBaseFor');
23295
23296/**
23297 * The base implementation of `baseForOwn` which iterates over `object`
23298 * properties returned by `keysFunc` and invokes `iteratee` for each property.
23299 * Iteratee functions may exit iteration early by explicitly returning `false`.
23300 *
23301 * @private
23302 * @param {Object} object The object to iterate over.
23303 * @param {Function} iteratee The function invoked per iteration.
23304 * @param {Function} keysFunc The function to get the keys of `object`.
23305 * @returns {Object} Returns `object`.
23306 */
23307var baseFor = createBaseFor();
23308
23309module.exports = baseFor;
23310
23311},{"./_createBaseFor":229}],177:[function(require,module,exports){
23312var baseFor = require('./_baseFor'),
23313 keys = require('./keys');
23314
23315/**
23316 * The base implementation of `_.forOwn` without support for iteratee shorthands.
23317 *
23318 * @private
23319 * @param {Object} object The object to iterate over.
23320 * @param {Function} iteratee The function invoked per iteration.
23321 * @returns {Object} Returns `object`.
23322 */
23323function baseForOwn(object, iteratee) {
23324 return object && baseFor(object, iteratee, keys);
23325}
23326
23327module.exports = baseForOwn;
23328
23329},{"./_baseFor":176,"./keys":337}],178:[function(require,module,exports){
23330var castPath = require('./_castPath'),
23331 toKey = require('./_toKey');
23332
23333/**
23334 * The base implementation of `_.get` without support for default values.
23335 *
23336 * @private
23337 * @param {Object} object The object to query.
23338 * @param {Array|string} path The path of the property to get.
23339 * @returns {*} Returns the resolved value.
23340 */
23341function baseGet(object, path) {
23342 path = castPath(path, object);
23343
23344 var index = 0,
23345 length = path.length;
23346
23347 while (object != null && index < length) {
23348 object = object[toKey(path[index++])];
23349 }
23350 return (index && index == length) ? object : undefined;
23351}
23352
23353module.exports = baseGet;
23354
23355},{"./_castPath":213,"./_toKey":301}],179:[function(require,module,exports){
23356var arrayPush = require('./_arrayPush'),
23357 isArray = require('./isArray');
23358
23359/**
23360 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
23361 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
23362 * symbols of `object`.
23363 *
23364 * @private
23365 * @param {Object} object The object to query.
23366 * @param {Function} keysFunc The function to get the keys of `object`.
23367 * @param {Function} symbolsFunc The function to get the symbols of `object`.
23368 * @returns {Array} Returns the array of property names and symbols.
23369 */
23370function baseGetAllKeys(object, keysFunc, symbolsFunc) {
23371 var result = keysFunc(object);
23372 return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
23373}
23374
23375module.exports = baseGetAllKeys;
23376
23377},{"./_arrayPush":161,"./isArray":319}],180:[function(require,module,exports){
23378var Symbol = require('./_Symbol'),
23379 getRawTag = require('./_getRawTag'),
23380 objectToString = require('./_objectToString');
23381
23382/** `Object#toString` result references. */
23383var nullTag = '[object Null]',
23384 undefinedTag = '[object Undefined]';
23385
23386/** Built-in value references. */
23387var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
23388
23389/**
23390 * The base implementation of `getTag` without fallbacks for buggy environments.
23391 *
23392 * @private
23393 * @param {*} value The value to query.
23394 * @returns {string} Returns the `toStringTag`.
23395 */
23396function baseGetTag(value) {
23397 if (value == null) {
23398 return value === undefined ? undefinedTag : nullTag;
23399 }
23400 return (symToStringTag && symToStringTag in Object(value))
23401 ? getRawTag(value)
23402 : objectToString(value);
23403}
23404
23405module.exports = baseGetTag;
23406
23407},{"./_Symbol":152,"./_getRawTag":243,"./_objectToString":283}],181:[function(require,module,exports){
23408/**
23409 * The base implementation of `_.hasIn` without support for deep paths.
23410 *
23411 * @private
23412 * @param {Object} [object] The object to query.
23413 * @param {Array|string} key The key to check.
23414 * @returns {boolean} Returns `true` if `key` exists, else `false`.
23415 */
23416function baseHasIn(object, key) {
23417 return object != null && key in Object(object);
23418}
23419
23420module.exports = baseHasIn;
23421
23422},{}],182:[function(require,module,exports){
23423var baseFindIndex = require('./_baseFindIndex'),
23424 baseIsNaN = require('./_baseIsNaN'),
23425 strictIndexOf = require('./_strictIndexOf');
23426
23427/**
23428 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
23429 *
23430 * @private
23431 * @param {Array} array The array to inspect.
23432 * @param {*} value The value to search for.
23433 * @param {number} fromIndex The index to search from.
23434 * @returns {number} Returns the index of the matched value, else `-1`.
23435 */
23436function baseIndexOf(array, value, fromIndex) {
23437 return value === value
23438 ? strictIndexOf(array, value, fromIndex)
23439 : baseFindIndex(array, baseIsNaN, fromIndex);
23440}
23441
23442module.exports = baseIndexOf;
23443
23444},{"./_baseFindIndex":174,"./_baseIsNaN":188,"./_strictIndexOf":297}],183:[function(require,module,exports){
23445var baseGetTag = require('./_baseGetTag'),
23446 isObjectLike = require('./isObjectLike');
23447
23448/** `Object#toString` result references. */
23449var argsTag = '[object Arguments]';
23450
23451/**
23452 * The base implementation of `_.isArguments`.
23453 *
23454 * @private
23455 * @param {*} value The value to check.
23456 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
23457 */
23458function baseIsArguments(value) {
23459 return isObjectLike(value) && baseGetTag(value) == argsTag;
23460}
23461
23462module.exports = baseIsArguments;
23463
23464},{"./_baseGetTag":180,"./isObjectLike":330}],184:[function(require,module,exports){
23465var baseIsEqualDeep = require('./_baseIsEqualDeep'),
23466 isObjectLike = require('./isObjectLike');
23467
23468/**
23469 * The base implementation of `_.isEqual` which supports partial comparisons
23470 * and tracks traversed objects.
23471 *
23472 * @private
23473 * @param {*} value The value to compare.
23474 * @param {*} other The other value to compare.
23475 * @param {boolean} bitmask The bitmask flags.
23476 * 1 - Unordered comparison
23477 * 2 - Partial comparison
23478 * @param {Function} [customizer] The function to customize comparisons.
23479 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
23480 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
23481 */
23482function baseIsEqual(value, other, bitmask, customizer, stack) {
23483 if (value === other) {
23484 return true;
23485 }
23486 if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
23487 return value !== value && other !== other;
23488 }
23489 return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
23490}
23491
23492module.exports = baseIsEqual;
23493
23494},{"./_baseIsEqualDeep":185,"./isObjectLike":330}],185:[function(require,module,exports){
23495var Stack = require('./_Stack'),
23496 equalArrays = require('./_equalArrays'),
23497 equalByTag = require('./_equalByTag'),
23498 equalObjects = require('./_equalObjects'),
23499 getTag = require('./_getTag'),
23500 isArray = require('./isArray'),
23501 isBuffer = require('./isBuffer'),
23502 isTypedArray = require('./isTypedArray');
23503
23504/** Used to compose bitmasks for value comparisons. */
23505var COMPARE_PARTIAL_FLAG = 1;
23506
23507/** `Object#toString` result references. */
23508var argsTag = '[object Arguments]',
23509 arrayTag = '[object Array]',
23510 objectTag = '[object Object]';
23511
23512/** Used for built-in method references. */
23513var objectProto = Object.prototype;
23514
23515/** Used to check objects for own properties. */
23516var hasOwnProperty = objectProto.hasOwnProperty;
23517
23518/**
23519 * A specialized version of `baseIsEqual` for arrays and objects which performs
23520 * deep comparisons and tracks traversed objects enabling objects with circular
23521 * references to be compared.
23522 *
23523 * @private
23524 * @param {Object} object The object to compare.
23525 * @param {Object} other The other object to compare.
23526 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
23527 * @param {Function} customizer The function to customize comparisons.
23528 * @param {Function} equalFunc The function to determine equivalents of values.
23529 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
23530 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
23531 */
23532function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
23533 var objIsArr = isArray(object),
23534 othIsArr = isArray(other),
23535 objTag = objIsArr ? arrayTag : getTag(object),
23536 othTag = othIsArr ? arrayTag : getTag(other);
23537
23538 objTag = objTag == argsTag ? objectTag : objTag;
23539 othTag = othTag == argsTag ? objectTag : othTag;
23540
23541 var objIsObj = objTag == objectTag,
23542 othIsObj = othTag == objectTag,
23543 isSameTag = objTag == othTag;
23544
23545 if (isSameTag && isBuffer(object)) {
23546 if (!isBuffer(other)) {
23547 return false;
23548 }
23549 objIsArr = true;
23550 objIsObj = false;
23551 }
23552 if (isSameTag && !objIsObj) {
23553 stack || (stack = new Stack);
23554 return (objIsArr || isTypedArray(object))
23555 ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
23556 : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
23557 }
23558 if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
23559 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
23560 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
23561
23562 if (objIsWrapped || othIsWrapped) {
23563 var objUnwrapped = objIsWrapped ? object.value() : object,
23564 othUnwrapped = othIsWrapped ? other.value() : other;
23565
23566 stack || (stack = new Stack);
23567 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
23568 }
23569 }
23570 if (!isSameTag) {
23571 return false;
23572 }
23573 stack || (stack = new Stack);
23574 return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
23575}
23576
23577module.exports = baseIsEqualDeep;
23578
23579},{"./_Stack":151,"./_equalArrays":232,"./_equalByTag":233,"./_equalObjects":234,"./_getTag":246,"./isArray":319,"./isBuffer":322,"./isTypedArray":335}],186:[function(require,module,exports){
23580var getTag = require('./_getTag'),
23581 isObjectLike = require('./isObjectLike');
23582
23583/** `Object#toString` result references. */
23584var mapTag = '[object Map]';
23585
23586/**
23587 * The base implementation of `_.isMap` without Node.js optimizations.
23588 *
23589 * @private
23590 * @param {*} value The value to check.
23591 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
23592 */
23593function baseIsMap(value) {
23594 return isObjectLike(value) && getTag(value) == mapTag;
23595}
23596
23597module.exports = baseIsMap;
23598
23599},{"./_getTag":246,"./isObjectLike":330}],187:[function(require,module,exports){
23600var Stack = require('./_Stack'),
23601 baseIsEqual = require('./_baseIsEqual');
23602
23603/** Used to compose bitmasks for value comparisons. */
23604var COMPARE_PARTIAL_FLAG = 1,
23605 COMPARE_UNORDERED_FLAG = 2;
23606
23607/**
23608 * The base implementation of `_.isMatch` without support for iteratee shorthands.
23609 *
23610 * @private
23611 * @param {Object} object The object to inspect.
23612 * @param {Object} source The object of property values to match.
23613 * @param {Array} matchData The property names, values, and compare flags to match.
23614 * @param {Function} [customizer] The function to customize comparisons.
23615 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
23616 */
23617function baseIsMatch(object, source, matchData, customizer) {
23618 var index = matchData.length,
23619 length = index,
23620 noCustomizer = !customizer;
23621
23622 if (object == null) {
23623 return !length;
23624 }
23625 object = Object(object);
23626 while (index--) {
23627 var data = matchData[index];
23628 if ((noCustomizer && data[2])
23629 ? data[1] !== object[data[0]]
23630 : !(data[0] in object)
23631 ) {
23632 return false;
23633 }
23634 }
23635 while (++index < length) {
23636 data = matchData[index];
23637 var key = data[0],
23638 objValue = object[key],
23639 srcValue = data[1];
23640
23641 if (noCustomizer && data[2]) {
23642 if (objValue === undefined && !(key in object)) {
23643 return false;
23644 }
23645 } else {
23646 var stack = new Stack;
23647 if (customizer) {
23648 var result = customizer(objValue, srcValue, key, object, source, stack);
23649 }
23650 if (!(result === undefined
23651 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
23652 : result
23653 )) {
23654 return false;
23655 }
23656 }
23657 }
23658 return true;
23659}
23660
23661module.exports = baseIsMatch;
23662
23663},{"./_Stack":151,"./_baseIsEqual":184}],188:[function(require,module,exports){
23664/**
23665 * The base implementation of `_.isNaN` without support for number objects.
23666 *
23667 * @private
23668 * @param {*} value The value to check.
23669 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
23670 */
23671function baseIsNaN(value) {
23672 return value !== value;
23673}
23674
23675module.exports = baseIsNaN;
23676
23677},{}],189:[function(require,module,exports){
23678var isFunction = require('./isFunction'),
23679 isMasked = require('./_isMasked'),
23680 isObject = require('./isObject'),
23681 toSource = require('./_toSource');
23682
23683/**
23684 * Used to match `RegExp`
23685 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
23686 */
23687var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
23688
23689/** Used to detect host constructors (Safari). */
23690var reIsHostCtor = /^\[object .+?Constructor\]$/;
23691
23692/** Used for built-in method references. */
23693var funcProto = Function.prototype,
23694 objectProto = Object.prototype;
23695
23696/** Used to resolve the decompiled source of functions. */
23697var funcToString = funcProto.toString;
23698
23699/** Used to check objects for own properties. */
23700var hasOwnProperty = objectProto.hasOwnProperty;
23701
23702/** Used to detect if a method is native. */
23703var reIsNative = RegExp('^' +
23704 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
23705 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
23706);
23707
23708/**
23709 * The base implementation of `_.isNative` without bad shim checks.
23710 *
23711 * @private
23712 * @param {*} value The value to check.
23713 * @returns {boolean} Returns `true` if `value` is a native function,
23714 * else `false`.
23715 */
23716function baseIsNative(value) {
23717 if (!isObject(value) || isMasked(value)) {
23718 return false;
23719 }
23720 var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
23721 return pattern.test(toSource(value));
23722}
23723
23724module.exports = baseIsNative;
23725
23726},{"./_isMasked":263,"./_toSource":302,"./isFunction":324,"./isObject":329}],190:[function(require,module,exports){
23727var getTag = require('./_getTag'),
23728 isObjectLike = require('./isObjectLike');
23729
23730/** `Object#toString` result references. */
23731var setTag = '[object Set]';
23732
23733/**
23734 * The base implementation of `_.isSet` without Node.js optimizations.
23735 *
23736 * @private
23737 * @param {*} value The value to check.
23738 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
23739 */
23740function baseIsSet(value) {
23741 return isObjectLike(value) && getTag(value) == setTag;
23742}
23743
23744module.exports = baseIsSet;
23745
23746},{"./_getTag":246,"./isObjectLike":330}],191:[function(require,module,exports){
23747var baseGetTag = require('./_baseGetTag'),
23748 isLength = require('./isLength'),
23749 isObjectLike = require('./isObjectLike');
23750
23751/** `Object#toString` result references. */
23752var argsTag = '[object Arguments]',
23753 arrayTag = '[object Array]',
23754 boolTag = '[object Boolean]',
23755 dateTag = '[object Date]',
23756 errorTag = '[object Error]',
23757 funcTag = '[object Function]',
23758 mapTag = '[object Map]',
23759 numberTag = '[object Number]',
23760 objectTag = '[object Object]',
23761 regexpTag = '[object RegExp]',
23762 setTag = '[object Set]',
23763 stringTag = '[object String]',
23764 weakMapTag = '[object WeakMap]';
23765
23766var arrayBufferTag = '[object ArrayBuffer]',
23767 dataViewTag = '[object DataView]',
23768 float32Tag = '[object Float32Array]',
23769 float64Tag = '[object Float64Array]',
23770 int8Tag = '[object Int8Array]',
23771 int16Tag = '[object Int16Array]',
23772 int32Tag = '[object Int32Array]',
23773 uint8Tag = '[object Uint8Array]',
23774 uint8ClampedTag = '[object Uint8ClampedArray]',
23775 uint16Tag = '[object Uint16Array]',
23776 uint32Tag = '[object Uint32Array]';
23777
23778/** Used to identify `toStringTag` values of typed arrays. */
23779var typedArrayTags = {};
23780typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
23781typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
23782typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
23783typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
23784typedArrayTags[uint32Tag] = true;
23785typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
23786typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
23787typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
23788typedArrayTags[errorTag] = typedArrayTags[funcTag] =
23789typedArrayTags[mapTag] = typedArrayTags[numberTag] =
23790typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
23791typedArrayTags[setTag] = typedArrayTags[stringTag] =
23792typedArrayTags[weakMapTag] = false;
23793
23794/**
23795 * The base implementation of `_.isTypedArray` without Node.js optimizations.
23796 *
23797 * @private
23798 * @param {*} value The value to check.
23799 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
23800 */
23801function baseIsTypedArray(value) {
23802 return isObjectLike(value) &&
23803 isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
23804}
23805
23806module.exports = baseIsTypedArray;
23807
23808},{"./_baseGetTag":180,"./isLength":325,"./isObjectLike":330}],192:[function(require,module,exports){
23809var baseMatches = require('./_baseMatches'),
23810 baseMatchesProperty = require('./_baseMatchesProperty'),
23811 identity = require('./identity'),
23812 isArray = require('./isArray'),
23813 property = require('./property');
23814
23815/**
23816 * The base implementation of `_.iteratee`.
23817 *
23818 * @private
23819 * @param {*} [value=_.identity] The value to convert to an iteratee.
23820 * @returns {Function} Returns the iteratee.
23821 */
23822function baseIteratee(value) {
23823 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
23824 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
23825 if (typeof value == 'function') {
23826 return value;
23827 }
23828 if (value == null) {
23829 return identity;
23830 }
23831 if (typeof value == 'object') {
23832 return isArray(value)
23833 ? baseMatchesProperty(value[0], value[1])
23834 : baseMatches(value);
23835 }
23836 return property(value);
23837}
23838
23839module.exports = baseIteratee;
23840
23841},{"./_baseMatches":196,"./_baseMatchesProperty":197,"./identity":317,"./isArray":319,"./property":343}],193:[function(require,module,exports){
23842var isPrototype = require('./_isPrototype'),
23843 nativeKeys = require('./_nativeKeys');
23844
23845/** Used for built-in method references. */
23846var objectProto = Object.prototype;
23847
23848/** Used to check objects for own properties. */
23849var hasOwnProperty = objectProto.hasOwnProperty;
23850
23851/**
23852 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
23853 *
23854 * @private
23855 * @param {Object} object The object to query.
23856 * @returns {Array} Returns the array of property names.
23857 */
23858function baseKeys(object) {
23859 if (!isPrototype(object)) {
23860 return nativeKeys(object);
23861 }
23862 var result = [];
23863 for (var key in Object(object)) {
23864 if (hasOwnProperty.call(object, key) && key != 'constructor') {
23865 result.push(key);
23866 }
23867 }
23868 return result;
23869}
23870
23871module.exports = baseKeys;
23872
23873},{"./_isPrototype":264,"./_nativeKeys":280}],194:[function(require,module,exports){
23874var isObject = require('./isObject'),
23875 isPrototype = require('./_isPrototype'),
23876 nativeKeysIn = require('./_nativeKeysIn');
23877
23878/** Used for built-in method references. */
23879var objectProto = Object.prototype;
23880
23881/** Used to check objects for own properties. */
23882var hasOwnProperty = objectProto.hasOwnProperty;
23883
23884/**
23885 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
23886 *
23887 * @private
23888 * @param {Object} object The object to query.
23889 * @returns {Array} Returns the array of property names.
23890 */
23891function baseKeysIn(object) {
23892 if (!isObject(object)) {
23893 return nativeKeysIn(object);
23894 }
23895 var isProto = isPrototype(object),
23896 result = [];
23897
23898 for (var key in object) {
23899 if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
23900 result.push(key);
23901 }
23902 }
23903 return result;
23904}
23905
23906module.exports = baseKeysIn;
23907
23908},{"./_isPrototype":264,"./_nativeKeysIn":281,"./isObject":329}],195:[function(require,module,exports){
23909var baseEach = require('./_baseEach'),
23910 isArrayLike = require('./isArrayLike');
23911
23912/**
23913 * The base implementation of `_.map` without support for iteratee shorthands.
23914 *
23915 * @private
23916 * @param {Array|Object} collection The collection to iterate over.
23917 * @param {Function} iteratee The function invoked per iteration.
23918 * @returns {Array} Returns the new mapped array.
23919 */
23920function baseMap(collection, iteratee) {
23921 var index = -1,
23922 result = isArrayLike(collection) ? Array(collection.length) : [];
23923
23924 baseEach(collection, function(value, key, collection) {
23925 result[++index] = iteratee(value, key, collection);
23926 });
23927 return result;
23928}
23929
23930module.exports = baseMap;
23931
23932},{"./_baseEach":172,"./isArrayLike":320}],196:[function(require,module,exports){
23933var baseIsMatch = require('./_baseIsMatch'),
23934 getMatchData = require('./_getMatchData'),
23935 matchesStrictComparable = require('./_matchesStrictComparable');
23936
23937/**
23938 * The base implementation of `_.matches` which doesn't clone `source`.
23939 *
23940 * @private
23941 * @param {Object} source The object of property values to match.
23942 * @returns {Function} Returns the new spec function.
23943 */
23944function baseMatches(source) {
23945 var matchData = getMatchData(source);
23946 if (matchData.length == 1 && matchData[0][2]) {
23947 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
23948 }
23949 return function(object) {
23950 return object === source || baseIsMatch(object, source, matchData);
23951 };
23952}
23953
23954module.exports = baseMatches;
23955
23956},{"./_baseIsMatch":187,"./_getMatchData":240,"./_matchesStrictComparable":277}],197:[function(require,module,exports){
23957var baseIsEqual = require('./_baseIsEqual'),
23958 get = require('./get'),
23959 hasIn = require('./hasIn'),
23960 isKey = require('./_isKey'),
23961 isStrictComparable = require('./_isStrictComparable'),
23962 matchesStrictComparable = require('./_matchesStrictComparable'),
23963 toKey = require('./_toKey');
23964
23965/** Used to compose bitmasks for value comparisons. */
23966var COMPARE_PARTIAL_FLAG = 1,
23967 COMPARE_UNORDERED_FLAG = 2;
23968
23969/**
23970 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
23971 *
23972 * @private
23973 * @param {string} path The path of the property to get.
23974 * @param {*} srcValue The value to match.
23975 * @returns {Function} Returns the new spec function.
23976 */
23977function baseMatchesProperty(path, srcValue) {
23978 if (isKey(path) && isStrictComparable(srcValue)) {
23979 return matchesStrictComparable(toKey(path), srcValue);
23980 }
23981 return function(object) {
23982 var objValue = get(object, path);
23983 return (objValue === undefined && objValue === srcValue)
23984 ? hasIn(object, path)
23985 : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
23986 };
23987}
23988
23989module.exports = baseMatchesProperty;
23990
23991},{"./_baseIsEqual":184,"./_isKey":261,"./_isStrictComparable":265,"./_matchesStrictComparable":277,"./_toKey":301,"./get":315,"./hasIn":316}],198:[function(require,module,exports){
23992var basePickBy = require('./_basePickBy'),
23993 hasIn = require('./hasIn');
23994
23995/**
23996 * The base implementation of `_.pick` without support for individual
23997 * property identifiers.
23998 *
23999 * @private
24000 * @param {Object} object The source object.
24001 * @param {string[]} paths The property paths to pick.
24002 * @returns {Object} Returns the new object.
24003 */
24004function basePick(object, paths) {
24005 return basePickBy(object, paths, function(value, path) {
24006 return hasIn(object, path);
24007 });
24008}
24009
24010module.exports = basePick;
24011
24012},{"./_basePickBy":199,"./hasIn":316}],199:[function(require,module,exports){
24013var baseGet = require('./_baseGet'),
24014 baseSet = require('./_baseSet'),
24015 castPath = require('./_castPath');
24016
24017/**
24018 * The base implementation of `_.pickBy` without support for iteratee shorthands.
24019 *
24020 * @private
24021 * @param {Object} object The source object.
24022 * @param {string[]} paths The property paths to pick.
24023 * @param {Function} predicate The function invoked per property.
24024 * @returns {Object} Returns the new object.
24025 */
24026function basePickBy(object, paths, predicate) {
24027 var index = -1,
24028 length = paths.length,
24029 result = {};
24030
24031 while (++index < length) {
24032 var path = paths[index],
24033 value = baseGet(object, path);
24034
24035 if (predicate(value, path)) {
24036 baseSet(result, castPath(path, object), value);
24037 }
24038 }
24039 return result;
24040}
24041
24042module.exports = basePickBy;
24043
24044},{"./_baseGet":178,"./_baseSet":204,"./_castPath":213}],200:[function(require,module,exports){
24045/**
24046 * The base implementation of `_.property` without support for deep paths.
24047 *
24048 * @private
24049 * @param {string} key The key of the property to get.
24050 * @returns {Function} Returns the new accessor function.
24051 */
24052function baseProperty(key) {
24053 return function(object) {
24054 return object == null ? undefined : object[key];
24055 };
24056}
24057
24058module.exports = baseProperty;
24059
24060},{}],201:[function(require,module,exports){
24061var baseGet = require('./_baseGet');
24062
24063/**
24064 * A specialized version of `baseProperty` which supports deep paths.
24065 *
24066 * @private
24067 * @param {Array|string} path The path of the property to get.
24068 * @returns {Function} Returns the new accessor function.
24069 */
24070function basePropertyDeep(path) {
24071 return function(object) {
24072 return baseGet(object, path);
24073 };
24074}
24075
24076module.exports = basePropertyDeep;
24077
24078},{"./_baseGet":178}],202:[function(require,module,exports){
24079/** Used as references for various `Number` constants. */
24080var MAX_SAFE_INTEGER = 9007199254740991;
24081
24082/* Built-in method references for those with the same name as other `lodash` methods. */
24083var nativeFloor = Math.floor;
24084
24085/**
24086 * The base implementation of `_.repeat` which doesn't coerce arguments.
24087 *
24088 * @private
24089 * @param {string} string The string to repeat.
24090 * @param {number} n The number of times to repeat the string.
24091 * @returns {string} Returns the repeated string.
24092 */
24093function baseRepeat(string, n) {
24094 var result = '';
24095 if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
24096 return result;
24097 }
24098 // Leverage the exponentiation by squaring algorithm for a faster repeat.
24099 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
24100 do {
24101 if (n % 2) {
24102 result += string;
24103 }
24104 n = nativeFloor(n / 2);
24105 if (n) {
24106 string += string;
24107 }
24108 } while (n);
24109
24110 return result;
24111}
24112
24113module.exports = baseRepeat;
24114
24115},{}],203:[function(require,module,exports){
24116var identity = require('./identity'),
24117 overRest = require('./_overRest'),
24118 setToString = require('./_setToString');
24119
24120/**
24121 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
24122 *
24123 * @private
24124 * @param {Function} func The function to apply a rest parameter to.
24125 * @param {number} [start=func.length-1] The start position of the rest parameter.
24126 * @returns {Function} Returns the new function.
24127 */
24128function baseRest(func, start) {
24129 return setToString(overRest(func, start, identity), func + '');
24130}
24131
24132module.exports = baseRest;
24133
24134},{"./_overRest":285,"./_setToString":290,"./identity":317}],204:[function(require,module,exports){
24135var assignValue = require('./_assignValue'),
24136 castPath = require('./_castPath'),
24137 isIndex = require('./_isIndex'),
24138 isObject = require('./isObject'),
24139 toKey = require('./_toKey');
24140
24141/**
24142 * The base implementation of `_.set`.
24143 *
24144 * @private
24145 * @param {Object} object The object to modify.
24146 * @param {Array|string} path The path of the property to set.
24147 * @param {*} value The value to set.
24148 * @param {Function} [customizer] The function to customize path creation.
24149 * @returns {Object} Returns `object`.
24150 */
24151function baseSet(object, path, value, customizer) {
24152 if (!isObject(object)) {
24153 return object;
24154 }
24155 path = castPath(path, object);
24156
24157 var index = -1,
24158 length = path.length,
24159 lastIndex = length - 1,
24160 nested = object;
24161
24162 while (nested != null && ++index < length) {
24163 var key = toKey(path[index]),
24164 newValue = value;
24165
24166 if (index != lastIndex) {
24167 var objValue = nested[key];
24168 newValue = customizer ? customizer(objValue, key, nested) : undefined;
24169 if (newValue === undefined) {
24170 newValue = isObject(objValue)
24171 ? objValue
24172 : (isIndex(path[index + 1]) ? [] : {});
24173 }
24174 }
24175 assignValue(nested, key, newValue);
24176 nested = nested[key];
24177 }
24178 return object;
24179}
24180
24181module.exports = baseSet;
24182
24183},{"./_assignValue":165,"./_castPath":213,"./_isIndex":259,"./_toKey":301,"./isObject":329}],205:[function(require,module,exports){
24184var constant = require('./constant'),
24185 defineProperty = require('./_defineProperty'),
24186 identity = require('./identity');
24187
24188/**
24189 * The base implementation of `setToString` without support for hot loop shorting.
24190 *
24191 * @private
24192 * @param {Function} func The function to modify.
24193 * @param {Function} string The `toString` result.
24194 * @returns {Function} Returns `func`.
24195 */
24196var baseSetToString = !defineProperty ? identity : function(func, string) {
24197 return defineProperty(func, 'toString', {
24198 'configurable': true,
24199 'enumerable': false,
24200 'value': constant(string),
24201 'writable': true
24202 });
24203};
24204
24205module.exports = baseSetToString;
24206
24207},{"./_defineProperty":231,"./constant":307,"./identity":317}],206:[function(require,module,exports){
24208/**
24209 * The base implementation of `_.slice` without an iteratee call guard.
24210 *
24211 * @private
24212 * @param {Array} array The array to slice.
24213 * @param {number} [start=0] The start position.
24214 * @param {number} [end=array.length] The end position.
24215 * @returns {Array} Returns the slice of `array`.
24216 */
24217function baseSlice(array, start, end) {
24218 var index = -1,
24219 length = array.length;
24220
24221 if (start < 0) {
24222 start = -start > length ? 0 : (length + start);
24223 }
24224 end = end > length ? length : end;
24225 if (end < 0) {
24226 end += length;
24227 }
24228 length = start > end ? 0 : ((end - start) >>> 0);
24229 start >>>= 0;
24230
24231 var result = Array(length);
24232 while (++index < length) {
24233 result[index] = array[index + start];
24234 }
24235 return result;
24236}
24237
24238module.exports = baseSlice;
24239
24240},{}],207:[function(require,module,exports){
24241/**
24242 * The base implementation of `_.times` without support for iteratee shorthands
24243 * or max array length checks.
24244 *
24245 * @private
24246 * @param {number} n The number of times to invoke `iteratee`.
24247 * @param {Function} iteratee The function invoked per iteration.
24248 * @returns {Array} Returns the array of results.
24249 */
24250function baseTimes(n, iteratee) {
24251 var index = -1,
24252 result = Array(n);
24253
24254 while (++index < n) {
24255 result[index] = iteratee(index);
24256 }
24257 return result;
24258}
24259
24260module.exports = baseTimes;
24261
24262},{}],208:[function(require,module,exports){
24263var Symbol = require('./_Symbol'),
24264 arrayMap = require('./_arrayMap'),
24265 isArray = require('./isArray'),
24266 isSymbol = require('./isSymbol');
24267
24268/** Used as references for various `Number` constants. */
24269var INFINITY = 1 / 0;
24270
24271/** Used to convert symbols to primitives and strings. */
24272var symbolProto = Symbol ? Symbol.prototype : undefined,
24273 symbolToString = symbolProto ? symbolProto.toString : undefined;
24274
24275/**
24276 * The base implementation of `_.toString` which doesn't convert nullish
24277 * values to empty strings.
24278 *
24279 * @private
24280 * @param {*} value The value to process.
24281 * @returns {string} Returns the string.
24282 */
24283function baseToString(value) {
24284 // Exit early for strings to avoid a performance hit in some environments.
24285 if (typeof value == 'string') {
24286 return value;
24287 }
24288 if (isArray(value)) {
24289 // Recursively convert values (susceptible to call stack limits).
24290 return arrayMap(value, baseToString) + '';
24291 }
24292 if (isSymbol(value)) {
24293 return symbolToString ? symbolToString.call(value) : '';
24294 }
24295 var result = (value + '');
24296 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
24297}
24298
24299module.exports = baseToString;
24300
24301},{"./_Symbol":152,"./_arrayMap":160,"./isArray":319,"./isSymbol":334}],209:[function(require,module,exports){
24302/**
24303 * The base implementation of `_.unary` without support for storing metadata.
24304 *
24305 * @private
24306 * @param {Function} func The function to cap arguments for.
24307 * @returns {Function} Returns the new capped function.
24308 */
24309function baseUnary(func) {
24310 return function(value) {
24311 return func(value);
24312 };
24313}
24314
24315module.exports = baseUnary;
24316
24317},{}],210:[function(require,module,exports){
24318var arrayMap = require('./_arrayMap');
24319
24320/**
24321 * The base implementation of `_.values` and `_.valuesIn` which creates an
24322 * array of `object` property values corresponding to the property names
24323 * of `props`.
24324 *
24325 * @private
24326 * @param {Object} object The object to query.
24327 * @param {Array} props The property names to get values for.
24328 * @returns {Object} Returns the array of property values.
24329 */
24330function baseValues(object, props) {
24331 return arrayMap(props, function(key) {
24332 return object[key];
24333 });
24334}
24335
24336module.exports = baseValues;
24337
24338},{"./_arrayMap":160}],211:[function(require,module,exports){
24339/**
24340 * Checks if a `cache` value for `key` exists.
24341 *
24342 * @private
24343 * @param {Object} cache The cache to query.
24344 * @param {string} key The key of the entry to check.
24345 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
24346 */
24347function cacheHas(cache, key) {
24348 return cache.has(key);
24349}
24350
24351module.exports = cacheHas;
24352
24353},{}],212:[function(require,module,exports){
24354var identity = require('./identity');
24355
24356/**
24357 * Casts `value` to `identity` if it's not a function.
24358 *
24359 * @private
24360 * @param {*} value The value to inspect.
24361 * @returns {Function} Returns cast function.
24362 */
24363function castFunction(value) {
24364 return typeof value == 'function' ? value : identity;
24365}
24366
24367module.exports = castFunction;
24368
24369},{"./identity":317}],213:[function(require,module,exports){
24370var isArray = require('./isArray'),
24371 isKey = require('./_isKey'),
24372 stringToPath = require('./_stringToPath'),
24373 toString = require('./toString');
24374
24375/**
24376 * Casts `value` to a path array if it's not one.
24377 *
24378 * @private
24379 * @param {*} value The value to inspect.
24380 * @param {Object} [object] The object to query keys on.
24381 * @returns {Array} Returns the cast property path array.
24382 */
24383function castPath(value, object) {
24384 if (isArray(value)) {
24385 return value;
24386 }
24387 return isKey(value, object) ? [value] : stringToPath(toString(value));
24388}
24389
24390module.exports = castPath;
24391
24392},{"./_isKey":261,"./_stringToPath":300,"./isArray":319,"./toString":350}],214:[function(require,module,exports){
24393var baseSlice = require('./_baseSlice');
24394
24395/**
24396 * Casts `array` to a slice if it's needed.
24397 *
24398 * @private
24399 * @param {Array} array The array to inspect.
24400 * @param {number} start The start position.
24401 * @param {number} [end=array.length] The end position.
24402 * @returns {Array} Returns the cast slice.
24403 */
24404function castSlice(array, start, end) {
24405 var length = array.length;
24406 end = end === undefined ? length : end;
24407 return (!start && end >= length) ? array : baseSlice(array, start, end);
24408}
24409
24410module.exports = castSlice;
24411
24412},{"./_baseSlice":206}],215:[function(require,module,exports){
24413var baseIndexOf = require('./_baseIndexOf');
24414
24415/**
24416 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
24417 * that is not found in the character symbols.
24418 *
24419 * @private
24420 * @param {Array} strSymbols The string symbols to inspect.
24421 * @param {Array} chrSymbols The character symbols to find.
24422 * @returns {number} Returns the index of the last unmatched string symbol.
24423 */
24424function charsEndIndex(strSymbols, chrSymbols) {
24425 var index = strSymbols.length;
24426
24427 while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
24428 return index;
24429}
24430
24431module.exports = charsEndIndex;
24432
24433},{"./_baseIndexOf":182}],216:[function(require,module,exports){
24434var Uint8Array = require('./_Uint8Array');
24435
24436/**
24437 * Creates a clone of `arrayBuffer`.
24438 *
24439 * @private
24440 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
24441 * @returns {ArrayBuffer} Returns the cloned array buffer.
24442 */
24443function cloneArrayBuffer(arrayBuffer) {
24444 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
24445 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
24446 return result;
24447}
24448
24449module.exports = cloneArrayBuffer;
24450
24451},{"./_Uint8Array":153}],217:[function(require,module,exports){
24452var root = require('./_root');
24453
24454/** Detect free variable `exports`. */
24455var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
24456
24457/** Detect free variable `module`. */
24458var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
24459
24460/** Detect the popular CommonJS extension `module.exports`. */
24461var moduleExports = freeModule && freeModule.exports === freeExports;
24462
24463/** Built-in value references. */
24464var Buffer = moduleExports ? root.Buffer : undefined,
24465 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
24466
24467/**
24468 * Creates a clone of `buffer`.
24469 *
24470 * @private
24471 * @param {Buffer} buffer The buffer to clone.
24472 * @param {boolean} [isDeep] Specify a deep clone.
24473 * @returns {Buffer} Returns the cloned buffer.
24474 */
24475function cloneBuffer(buffer, isDeep) {
24476 if (isDeep) {
24477 return buffer.slice();
24478 }
24479 var length = buffer.length,
24480 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
24481
24482 buffer.copy(result);
24483 return result;
24484}
24485
24486module.exports = cloneBuffer;
24487
24488},{"./_root":286}],218:[function(require,module,exports){
24489var cloneArrayBuffer = require('./_cloneArrayBuffer');
24490
24491/**
24492 * Creates a clone of `dataView`.
24493 *
24494 * @private
24495 * @param {Object} dataView The data view to clone.
24496 * @param {boolean} [isDeep] Specify a deep clone.
24497 * @returns {Object} Returns the cloned data view.
24498 */
24499function cloneDataView(dataView, isDeep) {
24500 var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
24501 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
24502}
24503
24504module.exports = cloneDataView;
24505
24506},{"./_cloneArrayBuffer":216}],219:[function(require,module,exports){
24507/** Used to match `RegExp` flags from their coerced string values. */
24508var reFlags = /\w*$/;
24509
24510/**
24511 * Creates a clone of `regexp`.
24512 *
24513 * @private
24514 * @param {Object} regexp The regexp to clone.
24515 * @returns {Object} Returns the cloned regexp.
24516 */
24517function cloneRegExp(regexp) {
24518 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
24519 result.lastIndex = regexp.lastIndex;
24520 return result;
24521}
24522
24523module.exports = cloneRegExp;
24524
24525},{}],220:[function(require,module,exports){
24526var Symbol = require('./_Symbol');
24527
24528/** Used to convert symbols to primitives and strings. */
24529var symbolProto = Symbol ? Symbol.prototype : undefined,
24530 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
24531
24532/**
24533 * Creates a clone of the `symbol` object.
24534 *
24535 * @private
24536 * @param {Object} symbol The symbol object to clone.
24537 * @returns {Object} Returns the cloned symbol object.
24538 */
24539function cloneSymbol(symbol) {
24540 return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
24541}
24542
24543module.exports = cloneSymbol;
24544
24545},{"./_Symbol":152}],221:[function(require,module,exports){
24546var cloneArrayBuffer = require('./_cloneArrayBuffer');
24547
24548/**
24549 * Creates a clone of `typedArray`.
24550 *
24551 * @private
24552 * @param {Object} typedArray The typed array to clone.
24553 * @param {boolean} [isDeep] Specify a deep clone.
24554 * @returns {Object} Returns the cloned typed array.
24555 */
24556function cloneTypedArray(typedArray, isDeep) {
24557 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
24558 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
24559}
24560
24561module.exports = cloneTypedArray;
24562
24563},{"./_cloneArrayBuffer":216}],222:[function(require,module,exports){
24564/**
24565 * Copies the values of `source` to `array`.
24566 *
24567 * @private
24568 * @param {Array} source The array to copy values from.
24569 * @param {Array} [array=[]] The array to copy values to.
24570 * @returns {Array} Returns `array`.
24571 */
24572function copyArray(source, array) {
24573 var index = -1,
24574 length = source.length;
24575
24576 array || (array = Array(length));
24577 while (++index < length) {
24578 array[index] = source[index];
24579 }
24580 return array;
24581}
24582
24583module.exports = copyArray;
24584
24585},{}],223:[function(require,module,exports){
24586var assignValue = require('./_assignValue'),
24587 baseAssignValue = require('./_baseAssignValue');
24588
24589/**
24590 * Copies properties of `source` to `object`.
24591 *
24592 * @private
24593 * @param {Object} source The object to copy properties from.
24594 * @param {Array} props The property identifiers to copy.
24595 * @param {Object} [object={}] The object to copy properties to.
24596 * @param {Function} [customizer] The function to customize copied values.
24597 * @returns {Object} Returns `object`.
24598 */
24599function copyObject(source, props, object, customizer) {
24600 var isNew = !object;
24601 object || (object = {});
24602
24603 var index = -1,
24604 length = props.length;
24605
24606 while (++index < length) {
24607 var key = props[index];
24608
24609 var newValue = customizer
24610 ? customizer(object[key], source[key], key, object, source)
24611 : undefined;
24612
24613 if (newValue === undefined) {
24614 newValue = source[key];
24615 }
24616 if (isNew) {
24617 baseAssignValue(object, key, newValue);
24618 } else {
24619 assignValue(object, key, newValue);
24620 }
24621 }
24622 return object;
24623}
24624
24625module.exports = copyObject;
24626
24627},{"./_assignValue":165,"./_baseAssignValue":169}],224:[function(require,module,exports){
24628var copyObject = require('./_copyObject'),
24629 getSymbols = require('./_getSymbols');
24630
24631/**
24632 * Copies own symbols of `source` to `object`.
24633 *
24634 * @private
24635 * @param {Object} source The object to copy symbols from.
24636 * @param {Object} [object={}] The object to copy symbols to.
24637 * @returns {Object} Returns `object`.
24638 */
24639function copySymbols(source, object) {
24640 return copyObject(source, getSymbols(source), object);
24641}
24642
24643module.exports = copySymbols;
24644
24645},{"./_copyObject":223,"./_getSymbols":244}],225:[function(require,module,exports){
24646var copyObject = require('./_copyObject'),
24647 getSymbolsIn = require('./_getSymbolsIn');
24648
24649/**
24650 * Copies own and inherited symbols of `source` to `object`.
24651 *
24652 * @private
24653 * @param {Object} source The object to copy symbols from.
24654 * @param {Object} [object={}] The object to copy symbols to.
24655 * @returns {Object} Returns `object`.
24656 */
24657function copySymbolsIn(source, object) {
24658 return copyObject(source, getSymbolsIn(source), object);
24659}
24660
24661module.exports = copySymbolsIn;
24662
24663},{"./_copyObject":223,"./_getSymbolsIn":245}],226:[function(require,module,exports){
24664var root = require('./_root');
24665
24666/** Used to detect overreaching core-js shims. */
24667var coreJsData = root['__core-js_shared__'];
24668
24669module.exports = coreJsData;
24670
24671},{"./_root":286}],227:[function(require,module,exports){
24672var baseRest = require('./_baseRest'),
24673 isIterateeCall = require('./_isIterateeCall');
24674
24675/**
24676 * Creates a function like `_.assign`.
24677 *
24678 * @private
24679 * @param {Function} assigner The function to assign values.
24680 * @returns {Function} Returns the new assigner function.
24681 */
24682function createAssigner(assigner) {
24683 return baseRest(function(object, sources) {
24684 var index = -1,
24685 length = sources.length,
24686 customizer = length > 1 ? sources[length - 1] : undefined,
24687 guard = length > 2 ? sources[2] : undefined;
24688
24689 customizer = (assigner.length > 3 && typeof customizer == 'function')
24690 ? (length--, customizer)
24691 : undefined;
24692
24693 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
24694 customizer = length < 3 ? undefined : customizer;
24695 length = 1;
24696 }
24697 object = Object(object);
24698 while (++index < length) {
24699 var source = sources[index];
24700 if (source) {
24701 assigner(object, source, index, customizer);
24702 }
24703 }
24704 return object;
24705 });
24706}
24707
24708module.exports = createAssigner;
24709
24710},{"./_baseRest":203,"./_isIterateeCall":260}],228:[function(require,module,exports){
24711var isArrayLike = require('./isArrayLike');
24712
24713/**
24714 * Creates a `baseEach` or `baseEachRight` function.
24715 *
24716 * @private
24717 * @param {Function} eachFunc The function to iterate over a collection.
24718 * @param {boolean} [fromRight] Specify iterating from right to left.
24719 * @returns {Function} Returns the new base function.
24720 */
24721function createBaseEach(eachFunc, fromRight) {
24722 return function(collection, iteratee) {
24723 if (collection == null) {
24724 return collection;
24725 }
24726 if (!isArrayLike(collection)) {
24727 return eachFunc(collection, iteratee);
24728 }
24729 var length = collection.length,
24730 index = fromRight ? length : -1,
24731 iterable = Object(collection);
24732
24733 while ((fromRight ? index-- : ++index < length)) {
24734 if (iteratee(iterable[index], index, iterable) === false) {
24735 break;
24736 }
24737 }
24738 return collection;
24739 };
24740}
24741
24742module.exports = createBaseEach;
24743
24744},{"./isArrayLike":320}],229:[function(require,module,exports){
24745/**
24746 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
24747 *
24748 * @private
24749 * @param {boolean} [fromRight] Specify iterating from right to left.
24750 * @returns {Function} Returns the new base function.
24751 */
24752function createBaseFor(fromRight) {
24753 return function(object, iteratee, keysFunc) {
24754 var index = -1,
24755 iterable = Object(object),
24756 props = keysFunc(object),
24757 length = props.length;
24758
24759 while (length--) {
24760 var key = props[fromRight ? length : ++index];
24761 if (iteratee(iterable[key], key, iterable) === false) {
24762 break;
24763 }
24764 }
24765 return object;
24766 };
24767}
24768
24769module.exports = createBaseFor;
24770
24771},{}],230:[function(require,module,exports){
24772var baseRepeat = require('./_baseRepeat'),
24773 baseToString = require('./_baseToString'),
24774 castSlice = require('./_castSlice'),
24775 hasUnicode = require('./_hasUnicode'),
24776 stringSize = require('./_stringSize'),
24777 stringToArray = require('./_stringToArray');
24778
24779/* Built-in method references for those with the same name as other `lodash` methods. */
24780var nativeCeil = Math.ceil;
24781
24782/**
24783 * Creates the padding for `string` based on `length`. The `chars` string
24784 * is truncated if the number of characters exceeds `length`.
24785 *
24786 * @private
24787 * @param {number} length The padding length.
24788 * @param {string} [chars=' '] The string used as padding.
24789 * @returns {string} Returns the padding for `string`.
24790 */
24791function createPadding(length, chars) {
24792 chars = chars === undefined ? ' ' : baseToString(chars);
24793
24794 var charsLength = chars.length;
24795 if (charsLength < 2) {
24796 return charsLength ? baseRepeat(chars, length) : chars;
24797 }
24798 var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
24799 return hasUnicode(chars)
24800 ? castSlice(stringToArray(result), 0, length).join('')
24801 : result.slice(0, length);
24802}
24803
24804module.exports = createPadding;
24805
24806},{"./_baseRepeat":202,"./_baseToString":208,"./_castSlice":214,"./_hasUnicode":249,"./_stringSize":298,"./_stringToArray":299}],231:[function(require,module,exports){
24807var getNative = require('./_getNative');
24808
24809var defineProperty = (function() {
24810 try {
24811 var func = getNative(Object, 'defineProperty');
24812 func({}, '', {});
24813 return func;
24814 } catch (e) {}
24815}());
24816
24817module.exports = defineProperty;
24818
24819},{"./_getNative":241}],232:[function(require,module,exports){
24820var SetCache = require('./_SetCache'),
24821 arraySome = require('./_arraySome'),
24822 cacheHas = require('./_cacheHas');
24823
24824/** Used to compose bitmasks for value comparisons. */
24825var COMPARE_PARTIAL_FLAG = 1,
24826 COMPARE_UNORDERED_FLAG = 2;
24827
24828/**
24829 * A specialized version of `baseIsEqualDeep` for arrays with support for
24830 * partial deep comparisons.
24831 *
24832 * @private
24833 * @param {Array} array The array to compare.
24834 * @param {Array} other The other array to compare.
24835 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
24836 * @param {Function} customizer The function to customize comparisons.
24837 * @param {Function} equalFunc The function to determine equivalents of values.
24838 * @param {Object} stack Tracks traversed `array` and `other` objects.
24839 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
24840 */
24841function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
24842 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
24843 arrLength = array.length,
24844 othLength = other.length;
24845
24846 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
24847 return false;
24848 }
24849 // Assume cyclic values are equal.
24850 var stacked = stack.get(array);
24851 if (stacked && stack.get(other)) {
24852 return stacked == other;
24853 }
24854 var index = -1,
24855 result = true,
24856 seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
24857
24858 stack.set(array, other);
24859 stack.set(other, array);
24860
24861 // Ignore non-index properties.
24862 while (++index < arrLength) {
24863 var arrValue = array[index],
24864 othValue = other[index];
24865
24866 if (customizer) {
24867 var compared = isPartial
24868 ? customizer(othValue, arrValue, index, other, array, stack)
24869 : customizer(arrValue, othValue, index, array, other, stack);
24870 }
24871 if (compared !== undefined) {
24872 if (compared) {
24873 continue;
24874 }
24875 result = false;
24876 break;
24877 }
24878 // Recursively compare arrays (susceptible to call stack limits).
24879 if (seen) {
24880 if (!arraySome(other, function(othValue, othIndex) {
24881 if (!cacheHas(seen, othIndex) &&
24882 (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
24883 return seen.push(othIndex);
24884 }
24885 })) {
24886 result = false;
24887 break;
24888 }
24889 } else if (!(
24890 arrValue === othValue ||
24891 equalFunc(arrValue, othValue, bitmask, customizer, stack)
24892 )) {
24893 result = false;
24894 break;
24895 }
24896 }
24897 stack['delete'](array);
24898 stack['delete'](other);
24899 return result;
24900}
24901
24902module.exports = equalArrays;
24903
24904},{"./_SetCache":150,"./_arraySome":162,"./_cacheHas":211}],233:[function(require,module,exports){
24905var Symbol = require('./_Symbol'),
24906 Uint8Array = require('./_Uint8Array'),
24907 eq = require('./eq'),
24908 equalArrays = require('./_equalArrays'),
24909 mapToArray = require('./_mapToArray'),
24910 setToArray = require('./_setToArray');
24911
24912/** Used to compose bitmasks for value comparisons. */
24913var COMPARE_PARTIAL_FLAG = 1,
24914 COMPARE_UNORDERED_FLAG = 2;
24915
24916/** `Object#toString` result references. */
24917var boolTag = '[object Boolean]',
24918 dateTag = '[object Date]',
24919 errorTag = '[object Error]',
24920 mapTag = '[object Map]',
24921 numberTag = '[object Number]',
24922 regexpTag = '[object RegExp]',
24923 setTag = '[object Set]',
24924 stringTag = '[object String]',
24925 symbolTag = '[object Symbol]';
24926
24927var arrayBufferTag = '[object ArrayBuffer]',
24928 dataViewTag = '[object DataView]';
24929
24930/** Used to convert symbols to primitives and strings. */
24931var symbolProto = Symbol ? Symbol.prototype : undefined,
24932 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
24933
24934/**
24935 * A specialized version of `baseIsEqualDeep` for comparing objects of
24936 * the same `toStringTag`.
24937 *
24938 * **Note:** This function only supports comparing values with tags of
24939 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
24940 *
24941 * @private
24942 * @param {Object} object The object to compare.
24943 * @param {Object} other The other object to compare.
24944 * @param {string} tag The `toStringTag` of the objects to compare.
24945 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
24946 * @param {Function} customizer The function to customize comparisons.
24947 * @param {Function} equalFunc The function to determine equivalents of values.
24948 * @param {Object} stack Tracks traversed `object` and `other` objects.
24949 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
24950 */
24951function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
24952 switch (tag) {
24953 case dataViewTag:
24954 if ((object.byteLength != other.byteLength) ||
24955 (object.byteOffset != other.byteOffset)) {
24956 return false;
24957 }
24958 object = object.buffer;
24959 other = other.buffer;
24960
24961 case arrayBufferTag:
24962 if ((object.byteLength != other.byteLength) ||
24963 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
24964 return false;
24965 }
24966 return true;
24967
24968 case boolTag:
24969 case dateTag:
24970 case numberTag:
24971 // Coerce booleans to `1` or `0` and dates to milliseconds.
24972 // Invalid dates are coerced to `NaN`.
24973 return eq(+object, +other);
24974
24975 case errorTag:
24976 return object.name == other.name && object.message == other.message;
24977
24978 case regexpTag:
24979 case stringTag:
24980 // Coerce regexes to strings and treat strings, primitives and objects,
24981 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
24982 // for more details.
24983 return object == (other + '');
24984
24985 case mapTag:
24986 var convert = mapToArray;
24987
24988 case setTag:
24989 var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
24990 convert || (convert = setToArray);
24991
24992 if (object.size != other.size && !isPartial) {
24993 return false;
24994 }
24995 // Assume cyclic values are equal.
24996 var stacked = stack.get(object);
24997 if (stacked) {
24998 return stacked == other;
24999 }
25000 bitmask |= COMPARE_UNORDERED_FLAG;
25001
25002 // Recursively compare objects (susceptible to call stack limits).
25003 stack.set(object, other);
25004 var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
25005 stack['delete'](object);
25006 return result;
25007
25008 case symbolTag:
25009 if (symbolValueOf) {
25010 return symbolValueOf.call(object) == symbolValueOf.call(other);
25011 }
25012 }
25013 return false;
25014}
25015
25016module.exports = equalByTag;
25017
25018},{"./_Symbol":152,"./_Uint8Array":153,"./_equalArrays":232,"./_mapToArray":276,"./_setToArray":289,"./eq":309}],234:[function(require,module,exports){
25019var getAllKeys = require('./_getAllKeys');
25020
25021/** Used to compose bitmasks for value comparisons. */
25022var COMPARE_PARTIAL_FLAG = 1;
25023
25024/** Used for built-in method references. */
25025var objectProto = Object.prototype;
25026
25027/** Used to check objects for own properties. */
25028var hasOwnProperty = objectProto.hasOwnProperty;
25029
25030/**
25031 * A specialized version of `baseIsEqualDeep` for objects with support for
25032 * partial deep comparisons.
25033 *
25034 * @private
25035 * @param {Object} object The object to compare.
25036 * @param {Object} other The other object to compare.
25037 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
25038 * @param {Function} customizer The function to customize comparisons.
25039 * @param {Function} equalFunc The function to determine equivalents of values.
25040 * @param {Object} stack Tracks traversed `object` and `other` objects.
25041 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
25042 */
25043function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
25044 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
25045 objProps = getAllKeys(object),
25046 objLength = objProps.length,
25047 othProps = getAllKeys(other),
25048 othLength = othProps.length;
25049
25050 if (objLength != othLength && !isPartial) {
25051 return false;
25052 }
25053 var index = objLength;
25054 while (index--) {
25055 var key = objProps[index];
25056 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
25057 return false;
25058 }
25059 }
25060 // Assume cyclic values are equal.
25061 var stacked = stack.get(object);
25062 if (stacked && stack.get(other)) {
25063 return stacked == other;
25064 }
25065 var result = true;
25066 stack.set(object, other);
25067 stack.set(other, object);
25068
25069 var skipCtor = isPartial;
25070 while (++index < objLength) {
25071 key = objProps[index];
25072 var objValue = object[key],
25073 othValue = other[key];
25074
25075 if (customizer) {
25076 var compared = isPartial
25077 ? customizer(othValue, objValue, key, other, object, stack)
25078 : customizer(objValue, othValue, key, object, other, stack);
25079 }
25080 // Recursively compare objects (susceptible to call stack limits).
25081 if (!(compared === undefined
25082 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
25083 : compared
25084 )) {
25085 result = false;
25086 break;
25087 }
25088 skipCtor || (skipCtor = key == 'constructor');
25089 }
25090 if (result && !skipCtor) {
25091 var objCtor = object.constructor,
25092 othCtor = other.constructor;
25093
25094 // Non `Object` object instances with different constructors are not equal.
25095 if (objCtor != othCtor &&
25096 ('constructor' in object && 'constructor' in other) &&
25097 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
25098 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
25099 result = false;
25100 }
25101 }
25102 stack['delete'](object);
25103 stack['delete'](other);
25104 return result;
25105}
25106
25107module.exports = equalObjects;
25108
25109},{"./_getAllKeys":237}],235:[function(require,module,exports){
25110var flatten = require('./flatten'),
25111 overRest = require('./_overRest'),
25112 setToString = require('./_setToString');
25113
25114/**
25115 * A specialized version of `baseRest` which flattens the rest array.
25116 *
25117 * @private
25118 * @param {Function} func The function to apply a rest parameter to.
25119 * @returns {Function} Returns the new function.
25120 */
25121function flatRest(func) {
25122 return setToString(overRest(func, undefined, flatten), func + '');
25123}
25124
25125module.exports = flatRest;
25126
25127},{"./_overRest":285,"./_setToString":290,"./flatten":312}],236:[function(require,module,exports){
25128(function (global){
25129/** Detect free variable `global` from Node.js. */
25130var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
25131
25132module.exports = freeGlobal;
25133
25134}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25135},{}],237:[function(require,module,exports){
25136var baseGetAllKeys = require('./_baseGetAllKeys'),
25137 getSymbols = require('./_getSymbols'),
25138 keys = require('./keys');
25139
25140/**
25141 * Creates an array of own enumerable property names and symbols of `object`.
25142 *
25143 * @private
25144 * @param {Object} object The object to query.
25145 * @returns {Array} Returns the array of property names and symbols.
25146 */
25147function getAllKeys(object) {
25148 return baseGetAllKeys(object, keys, getSymbols);
25149}
25150
25151module.exports = getAllKeys;
25152
25153},{"./_baseGetAllKeys":179,"./_getSymbols":244,"./keys":337}],238:[function(require,module,exports){
25154var baseGetAllKeys = require('./_baseGetAllKeys'),
25155 getSymbolsIn = require('./_getSymbolsIn'),
25156 keysIn = require('./keysIn');
25157
25158/**
25159 * Creates an array of own and inherited enumerable property names and
25160 * symbols of `object`.
25161 *
25162 * @private
25163 * @param {Object} object The object to query.
25164 * @returns {Array} Returns the array of property names and symbols.
25165 */
25166function getAllKeysIn(object) {
25167 return baseGetAllKeys(object, keysIn, getSymbolsIn);
25168}
25169
25170module.exports = getAllKeysIn;
25171
25172},{"./_baseGetAllKeys":179,"./_getSymbolsIn":245,"./keysIn":338}],239:[function(require,module,exports){
25173var isKeyable = require('./_isKeyable');
25174
25175/**
25176 * Gets the data for `map`.
25177 *
25178 * @private
25179 * @param {Object} map The map to query.
25180 * @param {string} key The reference key.
25181 * @returns {*} Returns the map data.
25182 */
25183function getMapData(map, key) {
25184 var data = map.__data__;
25185 return isKeyable(key)
25186 ? data[typeof key == 'string' ? 'string' : 'hash']
25187 : data.map;
25188}
25189
25190module.exports = getMapData;
25191
25192},{"./_isKeyable":262}],240:[function(require,module,exports){
25193var isStrictComparable = require('./_isStrictComparable'),
25194 keys = require('./keys');
25195
25196/**
25197 * Gets the property names, values, and compare flags of `object`.
25198 *
25199 * @private
25200 * @param {Object} object The object to query.
25201 * @returns {Array} Returns the match data of `object`.
25202 */
25203function getMatchData(object) {
25204 var result = keys(object),
25205 length = result.length;
25206
25207 while (length--) {
25208 var key = result[length],
25209 value = object[key];
25210
25211 result[length] = [key, value, isStrictComparable(value)];
25212 }
25213 return result;
25214}
25215
25216module.exports = getMatchData;
25217
25218},{"./_isStrictComparable":265,"./keys":337}],241:[function(require,module,exports){
25219var baseIsNative = require('./_baseIsNative'),
25220 getValue = require('./_getValue');
25221
25222/**
25223 * Gets the native function at `key` of `object`.
25224 *
25225 * @private
25226 * @param {Object} object The object to query.
25227 * @param {string} key The key of the method to get.
25228 * @returns {*} Returns the function if it's native, else `undefined`.
25229 */
25230function getNative(object, key) {
25231 var value = getValue(object, key);
25232 return baseIsNative(value) ? value : undefined;
25233}
25234
25235module.exports = getNative;
25236
25237},{"./_baseIsNative":189,"./_getValue":247}],242:[function(require,module,exports){
25238var overArg = require('./_overArg');
25239
25240/** Built-in value references. */
25241var getPrototype = overArg(Object.getPrototypeOf, Object);
25242
25243module.exports = getPrototype;
25244
25245},{"./_overArg":284}],243:[function(require,module,exports){
25246var Symbol = require('./_Symbol');
25247
25248/** Used for built-in method references. */
25249var objectProto = Object.prototype;
25250
25251/** Used to check objects for own properties. */
25252var hasOwnProperty = objectProto.hasOwnProperty;
25253
25254/**
25255 * Used to resolve the
25256 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
25257 * of values.
25258 */
25259var nativeObjectToString = objectProto.toString;
25260
25261/** Built-in value references. */
25262var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
25263
25264/**
25265 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
25266 *
25267 * @private
25268 * @param {*} value The value to query.
25269 * @returns {string} Returns the raw `toStringTag`.
25270 */
25271function getRawTag(value) {
25272 var isOwn = hasOwnProperty.call(value, symToStringTag),
25273 tag = value[symToStringTag];
25274
25275 try {
25276 value[symToStringTag] = undefined;
25277 var unmasked = true;
25278 } catch (e) {}
25279
25280 var result = nativeObjectToString.call(value);
25281 if (unmasked) {
25282 if (isOwn) {
25283 value[symToStringTag] = tag;
25284 } else {
25285 delete value[symToStringTag];
25286 }
25287 }
25288 return result;
25289}
25290
25291module.exports = getRawTag;
25292
25293},{"./_Symbol":152}],244:[function(require,module,exports){
25294var arrayFilter = require('./_arrayFilter'),
25295 stubArray = require('./stubArray');
25296
25297/** Used for built-in method references. */
25298var objectProto = Object.prototype;
25299
25300/** Built-in value references. */
25301var propertyIsEnumerable = objectProto.propertyIsEnumerable;
25302
25303/* Built-in method references for those with the same name as other `lodash` methods. */
25304var nativeGetSymbols = Object.getOwnPropertySymbols;
25305
25306/**
25307 * Creates an array of the own enumerable symbols of `object`.
25308 *
25309 * @private
25310 * @param {Object} object The object to query.
25311 * @returns {Array} Returns the array of symbols.
25312 */
25313var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
25314 if (object == null) {
25315 return [];
25316 }
25317 object = Object(object);
25318 return arrayFilter(nativeGetSymbols(object), function(symbol) {
25319 return propertyIsEnumerable.call(object, symbol);
25320 });
25321};
25322
25323module.exports = getSymbols;
25324
25325},{"./_arrayFilter":158,"./stubArray":344}],245:[function(require,module,exports){
25326var arrayPush = require('./_arrayPush'),
25327 getPrototype = require('./_getPrototype'),
25328 getSymbols = require('./_getSymbols'),
25329 stubArray = require('./stubArray');
25330
25331/* Built-in method references for those with the same name as other `lodash` methods. */
25332var nativeGetSymbols = Object.getOwnPropertySymbols;
25333
25334/**
25335 * Creates an array of the own and inherited enumerable symbols of `object`.
25336 *
25337 * @private
25338 * @param {Object} object The object to query.
25339 * @returns {Array} Returns the array of symbols.
25340 */
25341var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
25342 var result = [];
25343 while (object) {
25344 arrayPush(result, getSymbols(object));
25345 object = getPrototype(object);
25346 }
25347 return result;
25348};
25349
25350module.exports = getSymbolsIn;
25351
25352},{"./_arrayPush":161,"./_getPrototype":242,"./_getSymbols":244,"./stubArray":344}],246:[function(require,module,exports){
25353var DataView = require('./_DataView'),
25354 Map = require('./_Map'),
25355 Promise = require('./_Promise'),
25356 Set = require('./_Set'),
25357 WeakMap = require('./_WeakMap'),
25358 baseGetTag = require('./_baseGetTag'),
25359 toSource = require('./_toSource');
25360
25361/** `Object#toString` result references. */
25362var mapTag = '[object Map]',
25363 objectTag = '[object Object]',
25364 promiseTag = '[object Promise]',
25365 setTag = '[object Set]',
25366 weakMapTag = '[object WeakMap]';
25367
25368var dataViewTag = '[object DataView]';
25369
25370/** Used to detect maps, sets, and weakmaps. */
25371var dataViewCtorString = toSource(DataView),
25372 mapCtorString = toSource(Map),
25373 promiseCtorString = toSource(Promise),
25374 setCtorString = toSource(Set),
25375 weakMapCtorString = toSource(WeakMap);
25376
25377/**
25378 * Gets the `toStringTag` of `value`.
25379 *
25380 * @private
25381 * @param {*} value The value to query.
25382 * @returns {string} Returns the `toStringTag`.
25383 */
25384var getTag = baseGetTag;
25385
25386// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
25387if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
25388 (Map && getTag(new Map) != mapTag) ||
25389 (Promise && getTag(Promise.resolve()) != promiseTag) ||
25390 (Set && getTag(new Set) != setTag) ||
25391 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
25392 getTag = function(value) {
25393 var result = baseGetTag(value),
25394 Ctor = result == objectTag ? value.constructor : undefined,
25395 ctorString = Ctor ? toSource(Ctor) : '';
25396
25397 if (ctorString) {
25398 switch (ctorString) {
25399 case dataViewCtorString: return dataViewTag;
25400 case mapCtorString: return mapTag;
25401 case promiseCtorString: return promiseTag;
25402 case setCtorString: return setTag;
25403 case weakMapCtorString: return weakMapTag;
25404 }
25405 }
25406 return result;
25407 };
25408}
25409
25410module.exports = getTag;
25411
25412},{"./_DataView":143,"./_Map":146,"./_Promise":148,"./_Set":149,"./_WeakMap":154,"./_baseGetTag":180,"./_toSource":302}],247:[function(require,module,exports){
25413/**
25414 * Gets the value at `key` of `object`.
25415 *
25416 * @private
25417 * @param {Object} [object] The object to query.
25418 * @param {string} key The key of the property to get.
25419 * @returns {*} Returns the property value.
25420 */
25421function getValue(object, key) {
25422 return object == null ? undefined : object[key];
25423}
25424
25425module.exports = getValue;
25426
25427},{}],248:[function(require,module,exports){
25428var castPath = require('./_castPath'),
25429 isArguments = require('./isArguments'),
25430 isArray = require('./isArray'),
25431 isIndex = require('./_isIndex'),
25432 isLength = require('./isLength'),
25433 toKey = require('./_toKey');
25434
25435/**
25436 * Checks if `path` exists on `object`.
25437 *
25438 * @private
25439 * @param {Object} object The object to query.
25440 * @param {Array|string} path The path to check.
25441 * @param {Function} hasFunc The function to check properties.
25442 * @returns {boolean} Returns `true` if `path` exists, else `false`.
25443 */
25444function hasPath(object, path, hasFunc) {
25445 path = castPath(path, object);
25446
25447 var index = -1,
25448 length = path.length,
25449 result = false;
25450
25451 while (++index < length) {
25452 var key = toKey(path[index]);
25453 if (!(result = object != null && hasFunc(object, key))) {
25454 break;
25455 }
25456 object = object[key];
25457 }
25458 if (result || ++index != length) {
25459 return result;
25460 }
25461 length = object == null ? 0 : object.length;
25462 return !!length && isLength(length) && isIndex(key, length) &&
25463 (isArray(object) || isArguments(object));
25464}
25465
25466module.exports = hasPath;
25467
25468},{"./_castPath":213,"./_isIndex":259,"./_toKey":301,"./isArguments":318,"./isArray":319,"./isLength":325}],249:[function(require,module,exports){
25469/** Used to compose unicode character classes. */
25470var rsAstralRange = '\\ud800-\\udfff',
25471 rsComboMarksRange = '\\u0300-\\u036f',
25472 reComboHalfMarksRange = '\\ufe20-\\ufe2f',
25473 rsComboSymbolsRange = '\\u20d0-\\u20ff',
25474 rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
25475 rsVarRange = '\\ufe0e\\ufe0f';
25476
25477/** Used to compose unicode capture groups. */
25478var rsZWJ = '\\u200d';
25479
25480/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
25481var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
25482
25483/**
25484 * Checks if `string` contains Unicode symbols.
25485 *
25486 * @private
25487 * @param {string} string The string to inspect.
25488 * @returns {boolean} Returns `true` if a symbol is found, else `false`.
25489 */
25490function hasUnicode(string) {
25491 return reHasUnicode.test(string);
25492}
25493
25494module.exports = hasUnicode;
25495
25496},{}],250:[function(require,module,exports){
25497var nativeCreate = require('./_nativeCreate');
25498
25499/**
25500 * Removes all key-value entries from the hash.
25501 *
25502 * @private
25503 * @name clear
25504 * @memberOf Hash
25505 */
25506function hashClear() {
25507 this.__data__ = nativeCreate ? nativeCreate(null) : {};
25508 this.size = 0;
25509}
25510
25511module.exports = hashClear;
25512
25513},{"./_nativeCreate":279}],251:[function(require,module,exports){
25514/**
25515 * Removes `key` and its value from the hash.
25516 *
25517 * @private
25518 * @name delete
25519 * @memberOf Hash
25520 * @param {Object} hash The hash to modify.
25521 * @param {string} key The key of the value to remove.
25522 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25523 */
25524function hashDelete(key) {
25525 var result = this.has(key) && delete this.__data__[key];
25526 this.size -= result ? 1 : 0;
25527 return result;
25528}
25529
25530module.exports = hashDelete;
25531
25532},{}],252:[function(require,module,exports){
25533var nativeCreate = require('./_nativeCreate');
25534
25535/** Used to stand-in for `undefined` hash values. */
25536var HASH_UNDEFINED = '__lodash_hash_undefined__';
25537
25538/** Used for built-in method references. */
25539var objectProto = Object.prototype;
25540
25541/** Used to check objects for own properties. */
25542var hasOwnProperty = objectProto.hasOwnProperty;
25543
25544/**
25545 * Gets the hash value for `key`.
25546 *
25547 * @private
25548 * @name get
25549 * @memberOf Hash
25550 * @param {string} key The key of the value to get.
25551 * @returns {*} Returns the entry value.
25552 */
25553function hashGet(key) {
25554 var data = this.__data__;
25555 if (nativeCreate) {
25556 var result = data[key];
25557 return result === HASH_UNDEFINED ? undefined : result;
25558 }
25559 return hasOwnProperty.call(data, key) ? data[key] : undefined;
25560}
25561
25562module.exports = hashGet;
25563
25564},{"./_nativeCreate":279}],253:[function(require,module,exports){
25565var nativeCreate = require('./_nativeCreate');
25566
25567/** Used for built-in method references. */
25568var objectProto = Object.prototype;
25569
25570/** Used to check objects for own properties. */
25571var hasOwnProperty = objectProto.hasOwnProperty;
25572
25573/**
25574 * Checks if a hash value for `key` exists.
25575 *
25576 * @private
25577 * @name has
25578 * @memberOf Hash
25579 * @param {string} key The key of the entry to check.
25580 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25581 */
25582function hashHas(key) {
25583 var data = this.__data__;
25584 return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
25585}
25586
25587module.exports = hashHas;
25588
25589},{"./_nativeCreate":279}],254:[function(require,module,exports){
25590var nativeCreate = require('./_nativeCreate');
25591
25592/** Used to stand-in for `undefined` hash values. */
25593var HASH_UNDEFINED = '__lodash_hash_undefined__';
25594
25595/**
25596 * Sets the hash `key` to `value`.
25597 *
25598 * @private
25599 * @name set
25600 * @memberOf Hash
25601 * @param {string} key The key of the value to set.
25602 * @param {*} value The value to set.
25603 * @returns {Object} Returns the hash instance.
25604 */
25605function hashSet(key, value) {
25606 var data = this.__data__;
25607 this.size += this.has(key) ? 0 : 1;
25608 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
25609 return this;
25610}
25611
25612module.exports = hashSet;
25613
25614},{"./_nativeCreate":279}],255:[function(require,module,exports){
25615/** Used for built-in method references. */
25616var objectProto = Object.prototype;
25617
25618/** Used to check objects for own properties. */
25619var hasOwnProperty = objectProto.hasOwnProperty;
25620
25621/**
25622 * Initializes an array clone.
25623 *
25624 * @private
25625 * @param {Array} array The array to clone.
25626 * @returns {Array} Returns the initialized clone.
25627 */
25628function initCloneArray(array) {
25629 var length = array.length,
25630 result = new array.constructor(length);
25631
25632 // Add properties assigned by `RegExp#exec`.
25633 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
25634 result.index = array.index;
25635 result.input = array.input;
25636 }
25637 return result;
25638}
25639
25640module.exports = initCloneArray;
25641
25642},{}],256:[function(require,module,exports){
25643var cloneArrayBuffer = require('./_cloneArrayBuffer'),
25644 cloneDataView = require('./_cloneDataView'),
25645 cloneRegExp = require('./_cloneRegExp'),
25646 cloneSymbol = require('./_cloneSymbol'),
25647 cloneTypedArray = require('./_cloneTypedArray');
25648
25649/** `Object#toString` result references. */
25650var boolTag = '[object Boolean]',
25651 dateTag = '[object Date]',
25652 mapTag = '[object Map]',
25653 numberTag = '[object Number]',
25654 regexpTag = '[object RegExp]',
25655 setTag = '[object Set]',
25656 stringTag = '[object String]',
25657 symbolTag = '[object Symbol]';
25658
25659var arrayBufferTag = '[object ArrayBuffer]',
25660 dataViewTag = '[object DataView]',
25661 float32Tag = '[object Float32Array]',
25662 float64Tag = '[object Float64Array]',
25663 int8Tag = '[object Int8Array]',
25664 int16Tag = '[object Int16Array]',
25665 int32Tag = '[object Int32Array]',
25666 uint8Tag = '[object Uint8Array]',
25667 uint8ClampedTag = '[object Uint8ClampedArray]',
25668 uint16Tag = '[object Uint16Array]',
25669 uint32Tag = '[object Uint32Array]';
25670
25671/**
25672 * Initializes an object clone based on its `toStringTag`.
25673 *
25674 * **Note:** This function only supports cloning values with tags of
25675 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
25676 *
25677 * @private
25678 * @param {Object} object The object to clone.
25679 * @param {string} tag The `toStringTag` of the object to clone.
25680 * @param {boolean} [isDeep] Specify a deep clone.
25681 * @returns {Object} Returns the initialized clone.
25682 */
25683function initCloneByTag(object, tag, isDeep) {
25684 var Ctor = object.constructor;
25685 switch (tag) {
25686 case arrayBufferTag:
25687 return cloneArrayBuffer(object);
25688
25689 case boolTag:
25690 case dateTag:
25691 return new Ctor(+object);
25692
25693 case dataViewTag:
25694 return cloneDataView(object, isDeep);
25695
25696 case float32Tag: case float64Tag:
25697 case int8Tag: case int16Tag: case int32Tag:
25698 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
25699 return cloneTypedArray(object, isDeep);
25700
25701 case mapTag:
25702 return new Ctor;
25703
25704 case numberTag:
25705 case stringTag:
25706 return new Ctor(object);
25707
25708 case regexpTag:
25709 return cloneRegExp(object);
25710
25711 case setTag:
25712 return new Ctor;
25713
25714 case symbolTag:
25715 return cloneSymbol(object);
25716 }
25717}
25718
25719module.exports = initCloneByTag;
25720
25721},{"./_cloneArrayBuffer":216,"./_cloneDataView":218,"./_cloneRegExp":219,"./_cloneSymbol":220,"./_cloneTypedArray":221}],257:[function(require,module,exports){
25722var baseCreate = require('./_baseCreate'),
25723 getPrototype = require('./_getPrototype'),
25724 isPrototype = require('./_isPrototype');
25725
25726/**
25727 * Initializes an object clone.
25728 *
25729 * @private
25730 * @param {Object} object The object to clone.
25731 * @returns {Object} Returns the initialized clone.
25732 */
25733function initCloneObject(object) {
25734 return (typeof object.constructor == 'function' && !isPrototype(object))
25735 ? baseCreate(getPrototype(object))
25736 : {};
25737}
25738
25739module.exports = initCloneObject;
25740
25741},{"./_baseCreate":171,"./_getPrototype":242,"./_isPrototype":264}],258:[function(require,module,exports){
25742var Symbol = require('./_Symbol'),
25743 isArguments = require('./isArguments'),
25744 isArray = require('./isArray');
25745
25746/** Built-in value references. */
25747var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
25748
25749/**
25750 * Checks if `value` is a flattenable `arguments` object or array.
25751 *
25752 * @private
25753 * @param {*} value The value to check.
25754 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
25755 */
25756function isFlattenable(value) {
25757 return isArray(value) || isArguments(value) ||
25758 !!(spreadableSymbol && value && value[spreadableSymbol]);
25759}
25760
25761module.exports = isFlattenable;
25762
25763},{"./_Symbol":152,"./isArguments":318,"./isArray":319}],259:[function(require,module,exports){
25764/** Used as references for various `Number` constants. */
25765var MAX_SAFE_INTEGER = 9007199254740991;
25766
25767/** Used to detect unsigned integer values. */
25768var reIsUint = /^(?:0|[1-9]\d*)$/;
25769
25770/**
25771 * Checks if `value` is a valid array-like index.
25772 *
25773 * @private
25774 * @param {*} value The value to check.
25775 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
25776 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
25777 */
25778function isIndex(value, length) {
25779 var type = typeof value;
25780 length = length == null ? MAX_SAFE_INTEGER : length;
25781
25782 return !!length &&
25783 (type == 'number' ||
25784 (type != 'symbol' && reIsUint.test(value))) &&
25785 (value > -1 && value % 1 == 0 && value < length);
25786}
25787
25788module.exports = isIndex;
25789
25790},{}],260:[function(require,module,exports){
25791var eq = require('./eq'),
25792 isArrayLike = require('./isArrayLike'),
25793 isIndex = require('./_isIndex'),
25794 isObject = require('./isObject');
25795
25796/**
25797 * Checks if the given arguments are from an iteratee call.
25798 *
25799 * @private
25800 * @param {*} value The potential iteratee value argument.
25801 * @param {*} index The potential iteratee index or key argument.
25802 * @param {*} object The potential iteratee object argument.
25803 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
25804 * else `false`.
25805 */
25806function isIterateeCall(value, index, object) {
25807 if (!isObject(object)) {
25808 return false;
25809 }
25810 var type = typeof index;
25811 if (type == 'number'
25812 ? (isArrayLike(object) && isIndex(index, object.length))
25813 : (type == 'string' && index in object)
25814 ) {
25815 return eq(object[index], value);
25816 }
25817 return false;
25818}
25819
25820module.exports = isIterateeCall;
25821
25822},{"./_isIndex":259,"./eq":309,"./isArrayLike":320,"./isObject":329}],261:[function(require,module,exports){
25823var isArray = require('./isArray'),
25824 isSymbol = require('./isSymbol');
25825
25826/** Used to match property names within property paths. */
25827var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
25828 reIsPlainProp = /^\w*$/;
25829
25830/**
25831 * Checks if `value` is a property name and not a property path.
25832 *
25833 * @private
25834 * @param {*} value The value to check.
25835 * @param {Object} [object] The object to query keys on.
25836 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
25837 */
25838function isKey(value, object) {
25839 if (isArray(value)) {
25840 return false;
25841 }
25842 var type = typeof value;
25843 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
25844 value == null || isSymbol(value)) {
25845 return true;
25846 }
25847 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
25848 (object != null && value in Object(object));
25849}
25850
25851module.exports = isKey;
25852
25853},{"./isArray":319,"./isSymbol":334}],262:[function(require,module,exports){
25854/**
25855 * Checks if `value` is suitable for use as unique object key.
25856 *
25857 * @private
25858 * @param {*} value The value to check.
25859 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
25860 */
25861function isKeyable(value) {
25862 var type = typeof value;
25863 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
25864 ? (value !== '__proto__')
25865 : (value === null);
25866}
25867
25868module.exports = isKeyable;
25869
25870},{}],263:[function(require,module,exports){
25871var coreJsData = require('./_coreJsData');
25872
25873/** Used to detect methods masquerading as native. */
25874var maskSrcKey = (function() {
25875 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
25876 return uid ? ('Symbol(src)_1.' + uid) : '';
25877}());
25878
25879/**
25880 * Checks if `func` has its source masked.
25881 *
25882 * @private
25883 * @param {Function} func The function to check.
25884 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
25885 */
25886function isMasked(func) {
25887 return !!maskSrcKey && (maskSrcKey in func);
25888}
25889
25890module.exports = isMasked;
25891
25892},{"./_coreJsData":226}],264:[function(require,module,exports){
25893/** Used for built-in method references. */
25894var objectProto = Object.prototype;
25895
25896/**
25897 * Checks if `value` is likely a prototype object.
25898 *
25899 * @private
25900 * @param {*} value The value to check.
25901 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
25902 */
25903function isPrototype(value) {
25904 var Ctor = value && value.constructor,
25905 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
25906
25907 return value === proto;
25908}
25909
25910module.exports = isPrototype;
25911
25912},{}],265:[function(require,module,exports){
25913var isObject = require('./isObject');
25914
25915/**
25916 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
25917 *
25918 * @private
25919 * @param {*} value The value to check.
25920 * @returns {boolean} Returns `true` if `value` if suitable for strict
25921 * equality comparisons, else `false`.
25922 */
25923function isStrictComparable(value) {
25924 return value === value && !isObject(value);
25925}
25926
25927module.exports = isStrictComparable;
25928
25929},{"./isObject":329}],266:[function(require,module,exports){
25930/**
25931 * Removes all key-value entries from the list cache.
25932 *
25933 * @private
25934 * @name clear
25935 * @memberOf ListCache
25936 */
25937function listCacheClear() {
25938 this.__data__ = [];
25939 this.size = 0;
25940}
25941
25942module.exports = listCacheClear;
25943
25944},{}],267:[function(require,module,exports){
25945var assocIndexOf = require('./_assocIndexOf');
25946
25947/** Used for built-in method references. */
25948var arrayProto = Array.prototype;
25949
25950/** Built-in value references. */
25951var splice = arrayProto.splice;
25952
25953/**
25954 * Removes `key` and its value from the list cache.
25955 *
25956 * @private
25957 * @name delete
25958 * @memberOf ListCache
25959 * @param {string} key The key of the value to remove.
25960 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25961 */
25962function listCacheDelete(key) {
25963 var data = this.__data__,
25964 index = assocIndexOf(data, key);
25965
25966 if (index < 0) {
25967 return false;
25968 }
25969 var lastIndex = data.length - 1;
25970 if (index == lastIndex) {
25971 data.pop();
25972 } else {
25973 splice.call(data, index, 1);
25974 }
25975 --this.size;
25976 return true;
25977}
25978
25979module.exports = listCacheDelete;
25980
25981},{"./_assocIndexOf":166}],268:[function(require,module,exports){
25982var assocIndexOf = require('./_assocIndexOf');
25983
25984/**
25985 * Gets the list cache value for `key`.
25986 *
25987 * @private
25988 * @name get
25989 * @memberOf ListCache
25990 * @param {string} key The key of the value to get.
25991 * @returns {*} Returns the entry value.
25992 */
25993function listCacheGet(key) {
25994 var data = this.__data__,
25995 index = assocIndexOf(data, key);
25996
25997 return index < 0 ? undefined : data[index][1];
25998}
25999
26000module.exports = listCacheGet;
26001
26002},{"./_assocIndexOf":166}],269:[function(require,module,exports){
26003var assocIndexOf = require('./_assocIndexOf');
26004
26005/**
26006 * Checks if a list cache value for `key` exists.
26007 *
26008 * @private
26009 * @name has
26010 * @memberOf ListCache
26011 * @param {string} key The key of the entry to check.
26012 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26013 */
26014function listCacheHas(key) {
26015 return assocIndexOf(this.__data__, key) > -1;
26016}
26017
26018module.exports = listCacheHas;
26019
26020},{"./_assocIndexOf":166}],270:[function(require,module,exports){
26021var assocIndexOf = require('./_assocIndexOf');
26022
26023/**
26024 * Sets the list cache `key` to `value`.
26025 *
26026 * @private
26027 * @name set
26028 * @memberOf ListCache
26029 * @param {string} key The key of the value to set.
26030 * @param {*} value The value to set.
26031 * @returns {Object} Returns the list cache instance.
26032 */
26033function listCacheSet(key, value) {
26034 var data = this.__data__,
26035 index = assocIndexOf(data, key);
26036
26037 if (index < 0) {
26038 ++this.size;
26039 data.push([key, value]);
26040 } else {
26041 data[index][1] = value;
26042 }
26043 return this;
26044}
26045
26046module.exports = listCacheSet;
26047
26048},{"./_assocIndexOf":166}],271:[function(require,module,exports){
26049var Hash = require('./_Hash'),
26050 ListCache = require('./_ListCache'),
26051 Map = require('./_Map');
26052
26053/**
26054 * Removes all key-value entries from the map.
26055 *
26056 * @private
26057 * @name clear
26058 * @memberOf MapCache
26059 */
26060function mapCacheClear() {
26061 this.size = 0;
26062 this.__data__ = {
26063 'hash': new Hash,
26064 'map': new (Map || ListCache),
26065 'string': new Hash
26066 };
26067}
26068
26069module.exports = mapCacheClear;
26070
26071},{"./_Hash":144,"./_ListCache":145,"./_Map":146}],272:[function(require,module,exports){
26072var getMapData = require('./_getMapData');
26073
26074/**
26075 * Removes `key` and its value from the map.
26076 *
26077 * @private
26078 * @name delete
26079 * @memberOf MapCache
26080 * @param {string} key The key of the value to remove.
26081 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
26082 */
26083function mapCacheDelete(key) {
26084 var result = getMapData(this, key)['delete'](key);
26085 this.size -= result ? 1 : 0;
26086 return result;
26087}
26088
26089module.exports = mapCacheDelete;
26090
26091},{"./_getMapData":239}],273:[function(require,module,exports){
26092var getMapData = require('./_getMapData');
26093
26094/**
26095 * Gets the map value for `key`.
26096 *
26097 * @private
26098 * @name get
26099 * @memberOf MapCache
26100 * @param {string} key The key of the value to get.
26101 * @returns {*} Returns the entry value.
26102 */
26103function mapCacheGet(key) {
26104 return getMapData(this, key).get(key);
26105}
26106
26107module.exports = mapCacheGet;
26108
26109},{"./_getMapData":239}],274:[function(require,module,exports){
26110var getMapData = require('./_getMapData');
26111
26112/**
26113 * Checks if a map value for `key` exists.
26114 *
26115 * @private
26116 * @name has
26117 * @memberOf MapCache
26118 * @param {string} key The key of the entry to check.
26119 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26120 */
26121function mapCacheHas(key) {
26122 return getMapData(this, key).has(key);
26123}
26124
26125module.exports = mapCacheHas;
26126
26127},{"./_getMapData":239}],275:[function(require,module,exports){
26128var getMapData = require('./_getMapData');
26129
26130/**
26131 * Sets the map `key` to `value`.
26132 *
26133 * @private
26134 * @name set
26135 * @memberOf MapCache
26136 * @param {string} key The key of the value to set.
26137 * @param {*} value The value to set.
26138 * @returns {Object} Returns the map cache instance.
26139 */
26140function mapCacheSet(key, value) {
26141 var data = getMapData(this, key),
26142 size = data.size;
26143
26144 data.set(key, value);
26145 this.size += data.size == size ? 0 : 1;
26146 return this;
26147}
26148
26149module.exports = mapCacheSet;
26150
26151},{"./_getMapData":239}],276:[function(require,module,exports){
26152/**
26153 * Converts `map` to its key-value pairs.
26154 *
26155 * @private
26156 * @param {Object} map The map to convert.
26157 * @returns {Array} Returns the key-value pairs.
26158 */
26159function mapToArray(map) {
26160 var index = -1,
26161 result = Array(map.size);
26162
26163 map.forEach(function(value, key) {
26164 result[++index] = [key, value];
26165 });
26166 return result;
26167}
26168
26169module.exports = mapToArray;
26170
26171},{}],277:[function(require,module,exports){
26172/**
26173 * A specialized version of `matchesProperty` for source values suitable
26174 * for strict equality comparisons, i.e. `===`.
26175 *
26176 * @private
26177 * @param {string} key The key of the property to get.
26178 * @param {*} srcValue The value to match.
26179 * @returns {Function} Returns the new spec function.
26180 */
26181function matchesStrictComparable(key, srcValue) {
26182 return function(object) {
26183 if (object == null) {
26184 return false;
26185 }
26186 return object[key] === srcValue &&
26187 (srcValue !== undefined || (key in Object(object)));
26188 };
26189}
26190
26191module.exports = matchesStrictComparable;
26192
26193},{}],278:[function(require,module,exports){
26194var memoize = require('./memoize');
26195
26196/** Used as the maximum memoize cache size. */
26197var MAX_MEMOIZE_SIZE = 500;
26198
26199/**
26200 * A specialized version of `_.memoize` which clears the memoized function's
26201 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
26202 *
26203 * @private
26204 * @param {Function} func The function to have its output memoized.
26205 * @returns {Function} Returns the new memoized function.
26206 */
26207function memoizeCapped(func) {
26208 var result = memoize(func, function(key) {
26209 if (cache.size === MAX_MEMOIZE_SIZE) {
26210 cache.clear();
26211 }
26212 return key;
26213 });
26214
26215 var cache = result.cache;
26216 return result;
26217}
26218
26219module.exports = memoizeCapped;
26220
26221},{"./memoize":340}],279:[function(require,module,exports){
26222var getNative = require('./_getNative');
26223
26224/* Built-in method references that are verified to be native. */
26225var nativeCreate = getNative(Object, 'create');
26226
26227module.exports = nativeCreate;
26228
26229},{"./_getNative":241}],280:[function(require,module,exports){
26230var overArg = require('./_overArg');
26231
26232/* Built-in method references for those with the same name as other `lodash` methods. */
26233var nativeKeys = overArg(Object.keys, Object);
26234
26235module.exports = nativeKeys;
26236
26237},{"./_overArg":284}],281:[function(require,module,exports){
26238/**
26239 * This function is like
26240 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
26241 * except that it includes inherited enumerable properties.
26242 *
26243 * @private
26244 * @param {Object} object The object to query.
26245 * @returns {Array} Returns the array of property names.
26246 */
26247function nativeKeysIn(object) {
26248 var result = [];
26249 if (object != null) {
26250 for (var key in Object(object)) {
26251 result.push(key);
26252 }
26253 }
26254 return result;
26255}
26256
26257module.exports = nativeKeysIn;
26258
26259},{}],282:[function(require,module,exports){
26260var freeGlobal = require('./_freeGlobal');
26261
26262/** Detect free variable `exports`. */
26263var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
26264
26265/** Detect free variable `module`. */
26266var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
26267
26268/** Detect the popular CommonJS extension `module.exports`. */
26269var moduleExports = freeModule && freeModule.exports === freeExports;
26270
26271/** Detect free variable `process` from Node.js. */
26272var freeProcess = moduleExports && freeGlobal.process;
26273
26274/** Used to access faster Node.js helpers. */
26275var nodeUtil = (function() {
26276 try {
26277 // Use `util.types` for Node.js 10+.
26278 var types = freeModule && freeModule.require && freeModule.require('util').types;
26279
26280 if (types) {
26281 return types;
26282 }
26283
26284 // Legacy `process.binding('util')` for Node.js < 10.
26285 return freeProcess && freeProcess.binding && freeProcess.binding('util');
26286 } catch (e) {}
26287}());
26288
26289module.exports = nodeUtil;
26290
26291},{"./_freeGlobal":236}],283:[function(require,module,exports){
26292/** Used for built-in method references. */
26293var objectProto = Object.prototype;
26294
26295/**
26296 * Used to resolve the
26297 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
26298 * of values.
26299 */
26300var nativeObjectToString = objectProto.toString;
26301
26302/**
26303 * Converts `value` to a string using `Object.prototype.toString`.
26304 *
26305 * @private
26306 * @param {*} value The value to convert.
26307 * @returns {string} Returns the converted string.
26308 */
26309function objectToString(value) {
26310 return nativeObjectToString.call(value);
26311}
26312
26313module.exports = objectToString;
26314
26315},{}],284:[function(require,module,exports){
26316/**
26317 * Creates a unary function that invokes `func` with its argument transformed.
26318 *
26319 * @private
26320 * @param {Function} func The function to wrap.
26321 * @param {Function} transform The argument transform.
26322 * @returns {Function} Returns the new function.
26323 */
26324function overArg(func, transform) {
26325 return function(arg) {
26326 return func(transform(arg));
26327 };
26328}
26329
26330module.exports = overArg;
26331
26332},{}],285:[function(require,module,exports){
26333var apply = require('./_apply');
26334
26335/* Built-in method references for those with the same name as other `lodash` methods. */
26336var nativeMax = Math.max;
26337
26338/**
26339 * A specialized version of `baseRest` which transforms the rest array.
26340 *
26341 * @private
26342 * @param {Function} func The function to apply a rest parameter to.
26343 * @param {number} [start=func.length-1] The start position of the rest parameter.
26344 * @param {Function} transform The rest array transform.
26345 * @returns {Function} Returns the new function.
26346 */
26347function overRest(func, start, transform) {
26348 start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
26349 return function() {
26350 var args = arguments,
26351 index = -1,
26352 length = nativeMax(args.length - start, 0),
26353 array = Array(length);
26354
26355 while (++index < length) {
26356 array[index] = args[start + index];
26357 }
26358 index = -1;
26359 var otherArgs = Array(start + 1);
26360 while (++index < start) {
26361 otherArgs[index] = args[index];
26362 }
26363 otherArgs[start] = transform(array);
26364 return apply(func, this, otherArgs);
26365 };
26366}
26367
26368module.exports = overRest;
26369
26370},{"./_apply":155}],286:[function(require,module,exports){
26371var freeGlobal = require('./_freeGlobal');
26372
26373/** Detect free variable `self`. */
26374var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
26375
26376/** Used as a reference to the global object. */
26377var root = freeGlobal || freeSelf || Function('return this')();
26378
26379module.exports = root;
26380
26381},{"./_freeGlobal":236}],287:[function(require,module,exports){
26382/** Used to stand-in for `undefined` hash values. */
26383var HASH_UNDEFINED = '__lodash_hash_undefined__';
26384
26385/**
26386 * Adds `value` to the array cache.
26387 *
26388 * @private
26389 * @name add
26390 * @memberOf SetCache
26391 * @alias push
26392 * @param {*} value The value to cache.
26393 * @returns {Object} Returns the cache instance.
26394 */
26395function setCacheAdd(value) {
26396 this.__data__.set(value, HASH_UNDEFINED);
26397 return this;
26398}
26399
26400module.exports = setCacheAdd;
26401
26402},{}],288:[function(require,module,exports){
26403/**
26404 * Checks if `value` is in the array cache.
26405 *
26406 * @private
26407 * @name has
26408 * @memberOf SetCache
26409 * @param {*} value The value to search for.
26410 * @returns {number} Returns `true` if `value` is found, else `false`.
26411 */
26412function setCacheHas(value) {
26413 return this.__data__.has(value);
26414}
26415
26416module.exports = setCacheHas;
26417
26418},{}],289:[function(require,module,exports){
26419/**
26420 * Converts `set` to an array of its values.
26421 *
26422 * @private
26423 * @param {Object} set The set to convert.
26424 * @returns {Array} Returns the values.
26425 */
26426function setToArray(set) {
26427 var index = -1,
26428 result = Array(set.size);
26429
26430 set.forEach(function(value) {
26431 result[++index] = value;
26432 });
26433 return result;
26434}
26435
26436module.exports = setToArray;
26437
26438},{}],290:[function(require,module,exports){
26439var baseSetToString = require('./_baseSetToString'),
26440 shortOut = require('./_shortOut');
26441
26442/**
26443 * Sets the `toString` method of `func` to return `string`.
26444 *
26445 * @private
26446 * @param {Function} func The function to modify.
26447 * @param {Function} string The `toString` result.
26448 * @returns {Function} Returns `func`.
26449 */
26450var setToString = shortOut(baseSetToString);
26451
26452module.exports = setToString;
26453
26454},{"./_baseSetToString":205,"./_shortOut":291}],291:[function(require,module,exports){
26455/** Used to detect hot functions by number of calls within a span of milliseconds. */
26456var HOT_COUNT = 800,
26457 HOT_SPAN = 16;
26458
26459/* Built-in method references for those with the same name as other `lodash` methods. */
26460var nativeNow = Date.now;
26461
26462/**
26463 * Creates a function that'll short out and invoke `identity` instead
26464 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
26465 * milliseconds.
26466 *
26467 * @private
26468 * @param {Function} func The function to restrict.
26469 * @returns {Function} Returns the new shortable function.
26470 */
26471function shortOut(func) {
26472 var count = 0,
26473 lastCalled = 0;
26474
26475 return function() {
26476 var stamp = nativeNow(),
26477 remaining = HOT_SPAN - (stamp - lastCalled);
26478
26479 lastCalled = stamp;
26480 if (remaining > 0) {
26481 if (++count >= HOT_COUNT) {
26482 return arguments[0];
26483 }
26484 } else {
26485 count = 0;
26486 }
26487 return func.apply(undefined, arguments);
26488 };
26489}
26490
26491module.exports = shortOut;
26492
26493},{}],292:[function(require,module,exports){
26494var ListCache = require('./_ListCache');
26495
26496/**
26497 * Removes all key-value entries from the stack.
26498 *
26499 * @private
26500 * @name clear
26501 * @memberOf Stack
26502 */
26503function stackClear() {
26504 this.__data__ = new ListCache;
26505 this.size = 0;
26506}
26507
26508module.exports = stackClear;
26509
26510},{"./_ListCache":145}],293:[function(require,module,exports){
26511/**
26512 * Removes `key` and its value from the stack.
26513 *
26514 * @private
26515 * @name delete
26516 * @memberOf Stack
26517 * @param {string} key The key of the value to remove.
26518 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
26519 */
26520function stackDelete(key) {
26521 var data = this.__data__,
26522 result = data['delete'](key);
26523
26524 this.size = data.size;
26525 return result;
26526}
26527
26528module.exports = stackDelete;
26529
26530},{}],294:[function(require,module,exports){
26531/**
26532 * Gets the stack value for `key`.
26533 *
26534 * @private
26535 * @name get
26536 * @memberOf Stack
26537 * @param {string} key The key of the value to get.
26538 * @returns {*} Returns the entry value.
26539 */
26540function stackGet(key) {
26541 return this.__data__.get(key);
26542}
26543
26544module.exports = stackGet;
26545
26546},{}],295:[function(require,module,exports){
26547/**
26548 * Checks if a stack value for `key` exists.
26549 *
26550 * @private
26551 * @name has
26552 * @memberOf Stack
26553 * @param {string} key The key of the entry to check.
26554 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26555 */
26556function stackHas(key) {
26557 return this.__data__.has(key);
26558}
26559
26560module.exports = stackHas;
26561
26562},{}],296:[function(require,module,exports){
26563var ListCache = require('./_ListCache'),
26564 Map = require('./_Map'),
26565 MapCache = require('./_MapCache');
26566
26567/** Used as the size to enable large array optimizations. */
26568var LARGE_ARRAY_SIZE = 200;
26569
26570/**
26571 * Sets the stack `key` to `value`.
26572 *
26573 * @private
26574 * @name set
26575 * @memberOf Stack
26576 * @param {string} key The key of the value to set.
26577 * @param {*} value The value to set.
26578 * @returns {Object} Returns the stack cache instance.
26579 */
26580function stackSet(key, value) {
26581 var data = this.__data__;
26582 if (data instanceof ListCache) {
26583 var pairs = data.__data__;
26584 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
26585 pairs.push([key, value]);
26586 this.size = ++data.size;
26587 return this;
26588 }
26589 data = this.__data__ = new MapCache(pairs);
26590 }
26591 data.set(key, value);
26592 this.size = data.size;
26593 return this;
26594}
26595
26596module.exports = stackSet;
26597
26598},{"./_ListCache":145,"./_Map":146,"./_MapCache":147}],297:[function(require,module,exports){
26599/**
26600 * A specialized version of `_.indexOf` which performs strict equality
26601 * comparisons of values, i.e. `===`.
26602 *
26603 * @private
26604 * @param {Array} array The array to inspect.
26605 * @param {*} value The value to search for.
26606 * @param {number} fromIndex The index to search from.
26607 * @returns {number} Returns the index of the matched value, else `-1`.
26608 */
26609function strictIndexOf(array, value, fromIndex) {
26610 var index = fromIndex - 1,
26611 length = array.length;
26612
26613 while (++index < length) {
26614 if (array[index] === value) {
26615 return index;
26616 }
26617 }
26618 return -1;
26619}
26620
26621module.exports = strictIndexOf;
26622
26623},{}],298:[function(require,module,exports){
26624var asciiSize = require('./_asciiSize'),
26625 hasUnicode = require('./_hasUnicode'),
26626 unicodeSize = require('./_unicodeSize');
26627
26628/**
26629 * Gets the number of symbols in `string`.
26630 *
26631 * @private
26632 * @param {string} string The string to inspect.
26633 * @returns {number} Returns the string size.
26634 */
26635function stringSize(string) {
26636 return hasUnicode(string)
26637 ? unicodeSize(string)
26638 : asciiSize(string);
26639}
26640
26641module.exports = stringSize;
26642
26643},{"./_asciiSize":163,"./_hasUnicode":249,"./_unicodeSize":303}],299:[function(require,module,exports){
26644var asciiToArray = require('./_asciiToArray'),
26645 hasUnicode = require('./_hasUnicode'),
26646 unicodeToArray = require('./_unicodeToArray');
26647
26648/**
26649 * Converts `string` to an array.
26650 *
26651 * @private
26652 * @param {string} string The string to convert.
26653 * @returns {Array} Returns the converted array.
26654 */
26655function stringToArray(string) {
26656 return hasUnicode(string)
26657 ? unicodeToArray(string)
26658 : asciiToArray(string);
26659}
26660
26661module.exports = stringToArray;
26662
26663},{"./_asciiToArray":164,"./_hasUnicode":249,"./_unicodeToArray":304}],300:[function(require,module,exports){
26664var memoizeCapped = require('./_memoizeCapped');
26665
26666/** Used to match property names within property paths. */
26667var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
26668
26669/** Used to match backslashes in property paths. */
26670var reEscapeChar = /\\(\\)?/g;
26671
26672/**
26673 * Converts `string` to a property path array.
26674 *
26675 * @private
26676 * @param {string} string The string to convert.
26677 * @returns {Array} Returns the property path array.
26678 */
26679var stringToPath = memoizeCapped(function(string) {
26680 var result = [];
26681 if (string.charCodeAt(0) === 46 /* . */) {
26682 result.push('');
26683 }
26684 string.replace(rePropName, function(match, number, quote, subString) {
26685 result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
26686 });
26687 return result;
26688});
26689
26690module.exports = stringToPath;
26691
26692},{"./_memoizeCapped":278}],301:[function(require,module,exports){
26693var isSymbol = require('./isSymbol');
26694
26695/** Used as references for various `Number` constants. */
26696var INFINITY = 1 / 0;
26697
26698/**
26699 * Converts `value` to a string key if it's not a string or symbol.
26700 *
26701 * @private
26702 * @param {*} value The value to inspect.
26703 * @returns {string|symbol} Returns the key.
26704 */
26705function toKey(value) {
26706 if (typeof value == 'string' || isSymbol(value)) {
26707 return value;
26708 }
26709 var result = (value + '');
26710 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
26711}
26712
26713module.exports = toKey;
26714
26715},{"./isSymbol":334}],302:[function(require,module,exports){
26716/** Used for built-in method references. */
26717var funcProto = Function.prototype;
26718
26719/** Used to resolve the decompiled source of functions. */
26720var funcToString = funcProto.toString;
26721
26722/**
26723 * Converts `func` to its source code.
26724 *
26725 * @private
26726 * @param {Function} func The function to convert.
26727 * @returns {string} Returns the source code.
26728 */
26729function toSource(func) {
26730 if (func != null) {
26731 try {
26732 return funcToString.call(func);
26733 } catch (e) {}
26734 try {
26735 return (func + '');
26736 } catch (e) {}
26737 }
26738 return '';
26739}
26740
26741module.exports = toSource;
26742
26743},{}],303:[function(require,module,exports){
26744/** Used to compose unicode character classes. */
26745var rsAstralRange = '\\ud800-\\udfff',
26746 rsComboMarksRange = '\\u0300-\\u036f',
26747 reComboHalfMarksRange = '\\ufe20-\\ufe2f',
26748 rsComboSymbolsRange = '\\u20d0-\\u20ff',
26749 rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
26750 rsVarRange = '\\ufe0e\\ufe0f';
26751
26752/** Used to compose unicode capture groups. */
26753var rsAstral = '[' + rsAstralRange + ']',
26754 rsCombo = '[' + rsComboRange + ']',
26755 rsFitz = '\\ud83c[\\udffb-\\udfff]',
26756 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
26757 rsNonAstral = '[^' + rsAstralRange + ']',
26758 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
26759 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
26760 rsZWJ = '\\u200d';
26761
26762/** Used to compose unicode regexes. */
26763var reOptMod = rsModifier + '?',
26764 rsOptVar = '[' + rsVarRange + ']?',
26765 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
26766 rsSeq = rsOptVar + reOptMod + rsOptJoin,
26767 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
26768
26769/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
26770var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
26771
26772/**
26773 * Gets the size of a Unicode `string`.
26774 *
26775 * @private
26776 * @param {string} string The string inspect.
26777 * @returns {number} Returns the string size.
26778 */
26779function unicodeSize(string) {
26780 var result = reUnicode.lastIndex = 0;
26781 while (reUnicode.test(string)) {
26782 ++result;
26783 }
26784 return result;
26785}
26786
26787module.exports = unicodeSize;
26788
26789},{}],304:[function(require,module,exports){
26790/** Used to compose unicode character classes. */
26791var rsAstralRange = '\\ud800-\\udfff',
26792 rsComboMarksRange = '\\u0300-\\u036f',
26793 reComboHalfMarksRange = '\\ufe20-\\ufe2f',
26794 rsComboSymbolsRange = '\\u20d0-\\u20ff',
26795 rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
26796 rsVarRange = '\\ufe0e\\ufe0f';
26797
26798/** Used to compose unicode capture groups. */
26799var rsAstral = '[' + rsAstralRange + ']',
26800 rsCombo = '[' + rsComboRange + ']',
26801 rsFitz = '\\ud83c[\\udffb-\\udfff]',
26802 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
26803 rsNonAstral = '[^' + rsAstralRange + ']',
26804 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
26805 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
26806 rsZWJ = '\\u200d';
26807
26808/** Used to compose unicode regexes. */
26809var reOptMod = rsModifier + '?',
26810 rsOptVar = '[' + rsVarRange + ']?',
26811 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
26812 rsSeq = rsOptVar + reOptMod + rsOptJoin,
26813 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
26814
26815/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
26816var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
26817
26818/**
26819 * Converts a Unicode `string` to an array.
26820 *
26821 * @private
26822 * @param {string} string The string to convert.
26823 * @returns {Array} Returns the converted array.
26824 */
26825function unicodeToArray(string) {
26826 return string.match(reUnicode) || [];
26827}
26828
26829module.exports = unicodeToArray;
26830
26831},{}],305:[function(require,module,exports){
26832var copyObject = require('./_copyObject'),
26833 createAssigner = require('./_createAssigner'),
26834 keysIn = require('./keysIn');
26835
26836/**
26837 * This method is like `_.assign` except that it iterates over own and
26838 * inherited source properties.
26839 *
26840 * **Note:** This method mutates `object`.
26841 *
26842 * @static
26843 * @memberOf _
26844 * @since 4.0.0
26845 * @alias extend
26846 * @category Object
26847 * @param {Object} object The destination object.
26848 * @param {...Object} [sources] The source objects.
26849 * @returns {Object} Returns `object`.
26850 * @see _.assign
26851 * @example
26852 *
26853 * function Foo() {
26854 * this.a = 1;
26855 * }
26856 *
26857 * function Bar() {
26858 * this.c = 3;
26859 * }
26860 *
26861 * Foo.prototype.b = 2;
26862 * Bar.prototype.d = 4;
26863 *
26864 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
26865 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
26866 */
26867var assignIn = createAssigner(function(object, source) {
26868 copyObject(source, keysIn(source), object);
26869});
26870
26871module.exports = assignIn;
26872
26873},{"./_copyObject":223,"./_createAssigner":227,"./keysIn":338}],306:[function(require,module,exports){
26874var baseClone = require('./_baseClone');
26875
26876/** Used to compose bitmasks for cloning. */
26877var CLONE_SYMBOLS_FLAG = 4;
26878
26879/**
26880 * Creates a shallow clone of `value`.
26881 *
26882 * **Note:** This method is loosely based on the
26883 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
26884 * and supports cloning arrays, array buffers, booleans, date objects, maps,
26885 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
26886 * arrays. The own enumerable properties of `arguments` objects are cloned
26887 * as plain objects. An empty object is returned for uncloneable values such
26888 * as error objects, functions, DOM nodes, and WeakMaps.
26889 *
26890 * @static
26891 * @memberOf _
26892 * @since 0.1.0
26893 * @category Lang
26894 * @param {*} value The value to clone.
26895 * @returns {*} Returns the cloned value.
26896 * @see _.cloneDeep
26897 * @example
26898 *
26899 * var objects = [{ 'a': 1 }, { 'b': 2 }];
26900 *
26901 * var shallow = _.clone(objects);
26902 * console.log(shallow[0] === objects[0]);
26903 * // => true
26904 */
26905function clone(value) {
26906 return baseClone(value, CLONE_SYMBOLS_FLAG);
26907}
26908
26909module.exports = clone;
26910
26911},{"./_baseClone":170}],307:[function(require,module,exports){
26912/**
26913 * Creates a function that returns `value`.
26914 *
26915 * @static
26916 * @memberOf _
26917 * @since 2.4.0
26918 * @category Util
26919 * @param {*} value The value to return from the new function.
26920 * @returns {Function} Returns the new constant function.
26921 * @example
26922 *
26923 * var objects = _.times(2, _.constant({ 'a': 1 }));
26924 *
26925 * console.log(objects);
26926 * // => [{ 'a': 1 }, { 'a': 1 }]
26927 *
26928 * console.log(objects[0] === objects[1]);
26929 * // => true
26930 */
26931function constant(value) {
26932 return function() {
26933 return value;
26934 };
26935}
26936
26937module.exports = constant;
26938
26939},{}],308:[function(require,module,exports){
26940module.exports = require('./forEach');
26941
26942},{"./forEach":313}],309:[function(require,module,exports){
26943/**
26944 * Performs a
26945 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
26946 * comparison between two values to determine if they are equivalent.
26947 *
26948 * @static
26949 * @memberOf _
26950 * @since 4.0.0
26951 * @category Lang
26952 * @param {*} value The value to compare.
26953 * @param {*} other The other value to compare.
26954 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
26955 * @example
26956 *
26957 * var object = { 'a': 1 };
26958 * var other = { 'a': 1 };
26959 *
26960 * _.eq(object, object);
26961 * // => true
26962 *
26963 * _.eq(object, other);
26964 * // => false
26965 *
26966 * _.eq('a', 'a');
26967 * // => true
26968 *
26969 * _.eq('a', Object('a'));
26970 * // => false
26971 *
26972 * _.eq(NaN, NaN);
26973 * // => true
26974 */
26975function eq(value, other) {
26976 return value === other || (value !== value && other !== other);
26977}
26978
26979module.exports = eq;
26980
26981},{}],310:[function(require,module,exports){
26982var arrayEvery = require('./_arrayEvery'),
26983 baseEvery = require('./_baseEvery'),
26984 baseIteratee = require('./_baseIteratee'),
26985 isArray = require('./isArray'),
26986 isIterateeCall = require('./_isIterateeCall');
26987
26988/**
26989 * Checks if `predicate` returns truthy for **all** elements of `collection`.
26990 * Iteration is stopped once `predicate` returns falsey. The predicate is
26991 * invoked with three arguments: (value, index|key, collection).
26992 *
26993 * **Note:** This method returns `true` for
26994 * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
26995 * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
26996 * elements of empty collections.
26997 *
26998 * @static
26999 * @memberOf _
27000 * @since 0.1.0
27001 * @category Collection
27002 * @param {Array|Object} collection The collection to iterate over.
27003 * @param {Function} [predicate=_.identity] The function invoked per iteration.
27004 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
27005 * @returns {boolean} Returns `true` if all elements pass the predicate check,
27006 * else `false`.
27007 * @example
27008 *
27009 * _.every([true, 1, null, 'yes'], Boolean);
27010 * // => false
27011 *
27012 * var users = [
27013 * { 'user': 'barney', 'age': 36, 'active': false },
27014 * { 'user': 'fred', 'age': 40, 'active': false }
27015 * ];
27016 *
27017 * // The `_.matches` iteratee shorthand.
27018 * _.every(users, { 'user': 'barney', 'active': false });
27019 * // => false
27020 *
27021 * // The `_.matchesProperty` iteratee shorthand.
27022 * _.every(users, ['active', false]);
27023 * // => true
27024 *
27025 * // The `_.property` iteratee shorthand.
27026 * _.every(users, 'active');
27027 * // => false
27028 */
27029function every(collection, predicate, guard) {
27030 var func = isArray(collection) ? arrayEvery : baseEvery;
27031 if (guard && isIterateeCall(collection, predicate, guard)) {
27032 predicate = undefined;
27033 }
27034 return func(collection, baseIteratee(predicate, 3));
27035}
27036
27037module.exports = every;
27038
27039},{"./_arrayEvery":157,"./_baseEvery":173,"./_baseIteratee":192,"./_isIterateeCall":260,"./isArray":319}],311:[function(require,module,exports){
27040module.exports = require('./assignIn');
27041
27042},{"./assignIn":305}],312:[function(require,module,exports){
27043var baseFlatten = require('./_baseFlatten');
27044
27045/**
27046 * Flattens `array` a single level deep.
27047 *
27048 * @static
27049 * @memberOf _
27050 * @since 0.1.0
27051 * @category Array
27052 * @param {Array} array The array to flatten.
27053 * @returns {Array} Returns the new flattened array.
27054 * @example
27055 *
27056 * _.flatten([1, [2, [3, [4]], 5]]);
27057 * // => [1, 2, [3, [4]], 5]
27058 */
27059function flatten(array) {
27060 var length = array == null ? 0 : array.length;
27061 return length ? baseFlatten(array, 1) : [];
27062}
27063
27064module.exports = flatten;
27065
27066},{"./_baseFlatten":175}],313:[function(require,module,exports){
27067var arrayEach = require('./_arrayEach'),
27068 baseEach = require('./_baseEach'),
27069 castFunction = require('./_castFunction'),
27070 isArray = require('./isArray');
27071
27072/**
27073 * Iterates over elements of `collection` and invokes `iteratee` for each element.
27074 * The iteratee is invoked with three arguments: (value, index|key, collection).
27075 * Iteratee functions may exit iteration early by explicitly returning `false`.
27076 *
27077 * **Note:** As with other "Collections" methods, objects with a "length"
27078 * property are iterated like arrays. To avoid this behavior use `_.forIn`
27079 * or `_.forOwn` for object iteration.
27080 *
27081 * @static
27082 * @memberOf _
27083 * @since 0.1.0
27084 * @alias each
27085 * @category Collection
27086 * @param {Array|Object} collection The collection to iterate over.
27087 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
27088 * @returns {Array|Object} Returns `collection`.
27089 * @see _.forEachRight
27090 * @example
27091 *
27092 * _.forEach([1, 2], function(value) {
27093 * console.log(value);
27094 * });
27095 * // => Logs `1` then `2`.
27096 *
27097 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
27098 * console.log(key);
27099 * });
27100 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
27101 */
27102function forEach(collection, iteratee) {
27103 var func = isArray(collection) ? arrayEach : baseEach;
27104 return func(collection, castFunction(iteratee));
27105}
27106
27107module.exports = forEach;
27108
27109},{"./_arrayEach":156,"./_baseEach":172,"./_castFunction":212,"./isArray":319}],314:[function(require,module,exports){
27110/**
27111 * The inverse of `_.toPairs`; this method returns an object composed
27112 * from key-value `pairs`.
27113 *
27114 * @static
27115 * @memberOf _
27116 * @since 4.0.0
27117 * @category Array
27118 * @param {Array} pairs The key-value pairs.
27119 * @returns {Object} Returns the new object.
27120 * @example
27121 *
27122 * _.fromPairs([['a', 1], ['b', 2]]);
27123 * // => { 'a': 1, 'b': 2 }
27124 */
27125function fromPairs(pairs) {
27126 var index = -1,
27127 length = pairs == null ? 0 : pairs.length,
27128 result = {};
27129
27130 while (++index < length) {
27131 var pair = pairs[index];
27132 result[pair[0]] = pair[1];
27133 }
27134 return result;
27135}
27136
27137module.exports = fromPairs;
27138
27139},{}],315:[function(require,module,exports){
27140var baseGet = require('./_baseGet');
27141
27142/**
27143 * Gets the value at `path` of `object`. If the resolved value is
27144 * `undefined`, the `defaultValue` is returned in its place.
27145 *
27146 * @static
27147 * @memberOf _
27148 * @since 3.7.0
27149 * @category Object
27150 * @param {Object} object The object to query.
27151 * @param {Array|string} path The path of the property to get.
27152 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
27153 * @returns {*} Returns the resolved value.
27154 * @example
27155 *
27156 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
27157 *
27158 * _.get(object, 'a[0].b.c');
27159 * // => 3
27160 *
27161 * _.get(object, ['a', '0', 'b', 'c']);
27162 * // => 3
27163 *
27164 * _.get(object, 'a.b.c', 'default');
27165 * // => 'default'
27166 */
27167function get(object, path, defaultValue) {
27168 var result = object == null ? undefined : baseGet(object, path);
27169 return result === undefined ? defaultValue : result;
27170}
27171
27172module.exports = get;
27173
27174},{"./_baseGet":178}],316:[function(require,module,exports){
27175var baseHasIn = require('./_baseHasIn'),
27176 hasPath = require('./_hasPath');
27177
27178/**
27179 * Checks if `path` is a direct or inherited property of `object`.
27180 *
27181 * @static
27182 * @memberOf _
27183 * @since 4.0.0
27184 * @category Object
27185 * @param {Object} object The object to query.
27186 * @param {Array|string} path The path to check.
27187 * @returns {boolean} Returns `true` if `path` exists, else `false`.
27188 * @example
27189 *
27190 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
27191 *
27192 * _.hasIn(object, 'a');
27193 * // => true
27194 *
27195 * _.hasIn(object, 'a.b');
27196 * // => true
27197 *
27198 * _.hasIn(object, ['a', 'b']);
27199 * // => true
27200 *
27201 * _.hasIn(object, 'b');
27202 * // => false
27203 */
27204function hasIn(object, path) {
27205 return object != null && hasPath(object, path, baseHasIn);
27206}
27207
27208module.exports = hasIn;
27209
27210},{"./_baseHasIn":181,"./_hasPath":248}],317:[function(require,module,exports){
27211/**
27212 * This method returns the first argument it receives.
27213 *
27214 * @static
27215 * @since 0.1.0
27216 * @memberOf _
27217 * @category Util
27218 * @param {*} value Any value.
27219 * @returns {*} Returns `value`.
27220 * @example
27221 *
27222 * var object = { 'a': 1 };
27223 *
27224 * console.log(_.identity(object) === object);
27225 * // => true
27226 */
27227function identity(value) {
27228 return value;
27229}
27230
27231module.exports = identity;
27232
27233},{}],318:[function(require,module,exports){
27234var baseIsArguments = require('./_baseIsArguments'),
27235 isObjectLike = require('./isObjectLike');
27236
27237/** Used for built-in method references. */
27238var objectProto = Object.prototype;
27239
27240/** Used to check objects for own properties. */
27241var hasOwnProperty = objectProto.hasOwnProperty;
27242
27243/** Built-in value references. */
27244var propertyIsEnumerable = objectProto.propertyIsEnumerable;
27245
27246/**
27247 * Checks if `value` is likely an `arguments` object.
27248 *
27249 * @static
27250 * @memberOf _
27251 * @since 0.1.0
27252 * @category Lang
27253 * @param {*} value The value to check.
27254 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
27255 * else `false`.
27256 * @example
27257 *
27258 * _.isArguments(function() { return arguments; }());
27259 * // => true
27260 *
27261 * _.isArguments([1, 2, 3]);
27262 * // => false
27263 */
27264var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
27265 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
27266 !propertyIsEnumerable.call(value, 'callee');
27267};
27268
27269module.exports = isArguments;
27270
27271},{"./_baseIsArguments":183,"./isObjectLike":330}],319:[function(require,module,exports){
27272/**
27273 * Checks if `value` is classified as an `Array` object.
27274 *
27275 * @static
27276 * @memberOf _
27277 * @since 0.1.0
27278 * @category Lang
27279 * @param {*} value The value to check.
27280 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
27281 * @example
27282 *
27283 * _.isArray([1, 2, 3]);
27284 * // => true
27285 *
27286 * _.isArray(document.body.children);
27287 * // => false
27288 *
27289 * _.isArray('abc');
27290 * // => false
27291 *
27292 * _.isArray(_.noop);
27293 * // => false
27294 */
27295var isArray = Array.isArray;
27296
27297module.exports = isArray;
27298
27299},{}],320:[function(require,module,exports){
27300var isFunction = require('./isFunction'),
27301 isLength = require('./isLength');
27302
27303/**
27304 * Checks if `value` is array-like. A value is considered array-like if it's
27305 * not a function and has a `value.length` that's an integer greater than or
27306 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
27307 *
27308 * @static
27309 * @memberOf _
27310 * @since 4.0.0
27311 * @category Lang
27312 * @param {*} value The value to check.
27313 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
27314 * @example
27315 *
27316 * _.isArrayLike([1, 2, 3]);
27317 * // => true
27318 *
27319 * _.isArrayLike(document.body.children);
27320 * // => true
27321 *
27322 * _.isArrayLike('abc');
27323 * // => true
27324 *
27325 * _.isArrayLike(_.noop);
27326 * // => false
27327 */
27328function isArrayLike(value) {
27329 return value != null && isLength(value.length) && !isFunction(value);
27330}
27331
27332module.exports = isArrayLike;
27333
27334},{"./isFunction":324,"./isLength":325}],321:[function(require,module,exports){
27335var baseGetTag = require('./_baseGetTag'),
27336 isObjectLike = require('./isObjectLike');
27337
27338/** `Object#toString` result references. */
27339var boolTag = '[object Boolean]';
27340
27341/**
27342 * Checks if `value` is classified as a boolean primitive or object.
27343 *
27344 * @static
27345 * @memberOf _
27346 * @since 0.1.0
27347 * @category Lang
27348 * @param {*} value The value to check.
27349 * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
27350 * @example
27351 *
27352 * _.isBoolean(false);
27353 * // => true
27354 *
27355 * _.isBoolean(null);
27356 * // => false
27357 */
27358function isBoolean(value) {
27359 return value === true || value === false ||
27360 (isObjectLike(value) && baseGetTag(value) == boolTag);
27361}
27362
27363module.exports = isBoolean;
27364
27365},{"./_baseGetTag":180,"./isObjectLike":330}],322:[function(require,module,exports){
27366var root = require('./_root'),
27367 stubFalse = require('./stubFalse');
27368
27369/** Detect free variable `exports`. */
27370var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
27371
27372/** Detect free variable `module`. */
27373var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
27374
27375/** Detect the popular CommonJS extension `module.exports`. */
27376var moduleExports = freeModule && freeModule.exports === freeExports;
27377
27378/** Built-in value references. */
27379var Buffer = moduleExports ? root.Buffer : undefined;
27380
27381/* Built-in method references for those with the same name as other `lodash` methods. */
27382var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
27383
27384/**
27385 * Checks if `value` is a buffer.
27386 *
27387 * @static
27388 * @memberOf _
27389 * @since 4.3.0
27390 * @category Lang
27391 * @param {*} value The value to check.
27392 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
27393 * @example
27394 *
27395 * _.isBuffer(new Buffer(2));
27396 * // => true
27397 *
27398 * _.isBuffer(new Uint8Array(2));
27399 * // => false
27400 */
27401var isBuffer = nativeIsBuffer || stubFalse;
27402
27403module.exports = isBuffer;
27404
27405},{"./_root":286,"./stubFalse":345}],323:[function(require,module,exports){
27406var root = require('./_root');
27407
27408/* Built-in method references for those with the same name as other `lodash` methods. */
27409var nativeIsFinite = root.isFinite;
27410
27411/**
27412 * Checks if `value` is a finite primitive number.
27413 *
27414 * **Note:** This method is based on
27415 * [`Number.isFinite`](https://mdn.io/Number/isFinite).
27416 *
27417 * @static
27418 * @memberOf _
27419 * @since 0.1.0
27420 * @category Lang
27421 * @param {*} value The value to check.
27422 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
27423 * @example
27424 *
27425 * _.isFinite(3);
27426 * // => true
27427 *
27428 * _.isFinite(Number.MIN_VALUE);
27429 * // => true
27430 *
27431 * _.isFinite(Infinity);
27432 * // => false
27433 *
27434 * _.isFinite('3');
27435 * // => false
27436 */
27437function isFinite(value) {
27438 return typeof value == 'number' && nativeIsFinite(value);
27439}
27440
27441module.exports = isFinite;
27442
27443},{"./_root":286}],324:[function(require,module,exports){
27444var baseGetTag = require('./_baseGetTag'),
27445 isObject = require('./isObject');
27446
27447/** `Object#toString` result references. */
27448var asyncTag = '[object AsyncFunction]',
27449 funcTag = '[object Function]',
27450 genTag = '[object GeneratorFunction]',
27451 proxyTag = '[object Proxy]';
27452
27453/**
27454 * Checks if `value` is classified as a `Function` object.
27455 *
27456 * @static
27457 * @memberOf _
27458 * @since 0.1.0
27459 * @category Lang
27460 * @param {*} value The value to check.
27461 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
27462 * @example
27463 *
27464 * _.isFunction(_);
27465 * // => true
27466 *
27467 * _.isFunction(/abc/);
27468 * // => false
27469 */
27470function isFunction(value) {
27471 if (!isObject(value)) {
27472 return false;
27473 }
27474 // The use of `Object#toString` avoids issues with the `typeof` operator
27475 // in Safari 9 which returns 'object' for typed arrays and other constructors.
27476 var tag = baseGetTag(value);
27477 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
27478}
27479
27480module.exports = isFunction;
27481
27482},{"./_baseGetTag":180,"./isObject":329}],325:[function(require,module,exports){
27483/** Used as references for various `Number` constants. */
27484var MAX_SAFE_INTEGER = 9007199254740991;
27485
27486/**
27487 * Checks if `value` is a valid array-like length.
27488 *
27489 * **Note:** This method is loosely based on
27490 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
27491 *
27492 * @static
27493 * @memberOf _
27494 * @since 4.0.0
27495 * @category Lang
27496 * @param {*} value The value to check.
27497 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
27498 * @example
27499 *
27500 * _.isLength(3);
27501 * // => true
27502 *
27503 * _.isLength(Number.MIN_VALUE);
27504 * // => false
27505 *
27506 * _.isLength(Infinity);
27507 * // => false
27508 *
27509 * _.isLength('3');
27510 * // => false
27511 */
27512function isLength(value) {
27513 return typeof value == 'number' &&
27514 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
27515}
27516
27517module.exports = isLength;
27518
27519},{}],326:[function(require,module,exports){
27520var baseIsMap = require('./_baseIsMap'),
27521 baseUnary = require('./_baseUnary'),
27522 nodeUtil = require('./_nodeUtil');
27523
27524/* Node.js helper references. */
27525var nodeIsMap = nodeUtil && nodeUtil.isMap;
27526
27527/**
27528 * Checks if `value` is classified as a `Map` object.
27529 *
27530 * @static
27531 * @memberOf _
27532 * @since 4.3.0
27533 * @category Lang
27534 * @param {*} value The value to check.
27535 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
27536 * @example
27537 *
27538 * _.isMap(new Map);
27539 * // => true
27540 *
27541 * _.isMap(new WeakMap);
27542 * // => false
27543 */
27544var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
27545
27546module.exports = isMap;
27547
27548},{"./_baseIsMap":186,"./_baseUnary":209,"./_nodeUtil":282}],327:[function(require,module,exports){
27549/**
27550 * Checks if `value` is `null`.
27551 *
27552 * @static
27553 * @memberOf _
27554 * @since 0.1.0
27555 * @category Lang
27556 * @param {*} value The value to check.
27557 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
27558 * @example
27559 *
27560 * _.isNull(null);
27561 * // => true
27562 *
27563 * _.isNull(void 0);
27564 * // => false
27565 */
27566function isNull(value) {
27567 return value === null;
27568}
27569
27570module.exports = isNull;
27571
27572},{}],328:[function(require,module,exports){
27573var baseGetTag = require('./_baseGetTag'),
27574 isObjectLike = require('./isObjectLike');
27575
27576/** `Object#toString` result references. */
27577var numberTag = '[object Number]';
27578
27579/**
27580 * Checks if `value` is classified as a `Number` primitive or object.
27581 *
27582 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
27583 * classified as numbers, use the `_.isFinite` method.
27584 *
27585 * @static
27586 * @memberOf _
27587 * @since 0.1.0
27588 * @category Lang
27589 * @param {*} value The value to check.
27590 * @returns {boolean} Returns `true` if `value` is a number, else `false`.
27591 * @example
27592 *
27593 * _.isNumber(3);
27594 * // => true
27595 *
27596 * _.isNumber(Number.MIN_VALUE);
27597 * // => true
27598 *
27599 * _.isNumber(Infinity);
27600 * // => true
27601 *
27602 * _.isNumber('3');
27603 * // => false
27604 */
27605function isNumber(value) {
27606 return typeof value == 'number' ||
27607 (isObjectLike(value) && baseGetTag(value) == numberTag);
27608}
27609
27610module.exports = isNumber;
27611
27612},{"./_baseGetTag":180,"./isObjectLike":330}],329:[function(require,module,exports){
27613/**
27614 * Checks if `value` is the
27615 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
27616 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
27617 *
27618 * @static
27619 * @memberOf _
27620 * @since 0.1.0
27621 * @category Lang
27622 * @param {*} value The value to check.
27623 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
27624 * @example
27625 *
27626 * _.isObject({});
27627 * // => true
27628 *
27629 * _.isObject([1, 2, 3]);
27630 * // => true
27631 *
27632 * _.isObject(_.noop);
27633 * // => true
27634 *
27635 * _.isObject(null);
27636 * // => false
27637 */
27638function isObject(value) {
27639 var type = typeof value;
27640 return value != null && (type == 'object' || type == 'function');
27641}
27642
27643module.exports = isObject;
27644
27645},{}],330:[function(require,module,exports){
27646/**
27647 * Checks if `value` is object-like. A value is object-like if it's not `null`
27648 * and has a `typeof` result of "object".
27649 *
27650 * @static
27651 * @memberOf _
27652 * @since 4.0.0
27653 * @category Lang
27654 * @param {*} value The value to check.
27655 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
27656 * @example
27657 *
27658 * _.isObjectLike({});
27659 * // => true
27660 *
27661 * _.isObjectLike([1, 2, 3]);
27662 * // => true
27663 *
27664 * _.isObjectLike(_.noop);
27665 * // => false
27666 *
27667 * _.isObjectLike(null);
27668 * // => false
27669 */
27670function isObjectLike(value) {
27671 return value != null && typeof value == 'object';
27672}
27673
27674module.exports = isObjectLike;
27675
27676},{}],331:[function(require,module,exports){
27677var baseGetTag = require('./_baseGetTag'),
27678 getPrototype = require('./_getPrototype'),
27679 isObjectLike = require('./isObjectLike');
27680
27681/** `Object#toString` result references. */
27682var objectTag = '[object Object]';
27683
27684/** Used for built-in method references. */
27685var funcProto = Function.prototype,
27686 objectProto = Object.prototype;
27687
27688/** Used to resolve the decompiled source of functions. */
27689var funcToString = funcProto.toString;
27690
27691/** Used to check objects for own properties. */
27692var hasOwnProperty = objectProto.hasOwnProperty;
27693
27694/** Used to infer the `Object` constructor. */
27695var objectCtorString = funcToString.call(Object);
27696
27697/**
27698 * Checks if `value` is a plain object, that is, an object created by the
27699 * `Object` constructor or one with a `[[Prototype]]` of `null`.
27700 *
27701 * @static
27702 * @memberOf _
27703 * @since 0.8.0
27704 * @category Lang
27705 * @param {*} value The value to check.
27706 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
27707 * @example
27708 *
27709 * function Foo() {
27710 * this.a = 1;
27711 * }
27712 *
27713 * _.isPlainObject(new Foo);
27714 * // => false
27715 *
27716 * _.isPlainObject([1, 2, 3]);
27717 * // => false
27718 *
27719 * _.isPlainObject({ 'x': 0, 'y': 0 });
27720 * // => true
27721 *
27722 * _.isPlainObject(Object.create(null));
27723 * // => true
27724 */
27725function isPlainObject(value) {
27726 if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
27727 return false;
27728 }
27729 var proto = getPrototype(value);
27730 if (proto === null) {
27731 return true;
27732 }
27733 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
27734 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
27735 funcToString.call(Ctor) == objectCtorString;
27736}
27737
27738module.exports = isPlainObject;
27739
27740},{"./_baseGetTag":180,"./_getPrototype":242,"./isObjectLike":330}],332:[function(require,module,exports){
27741var baseIsSet = require('./_baseIsSet'),
27742 baseUnary = require('./_baseUnary'),
27743 nodeUtil = require('./_nodeUtil');
27744
27745/* Node.js helper references. */
27746var nodeIsSet = nodeUtil && nodeUtil.isSet;
27747
27748/**
27749 * Checks if `value` is classified as a `Set` object.
27750 *
27751 * @static
27752 * @memberOf _
27753 * @since 4.3.0
27754 * @category Lang
27755 * @param {*} value The value to check.
27756 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
27757 * @example
27758 *
27759 * _.isSet(new Set);
27760 * // => true
27761 *
27762 * _.isSet(new WeakSet);
27763 * // => false
27764 */
27765var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
27766
27767module.exports = isSet;
27768
27769},{"./_baseIsSet":190,"./_baseUnary":209,"./_nodeUtil":282}],333:[function(require,module,exports){
27770var baseGetTag = require('./_baseGetTag'),
27771 isArray = require('./isArray'),
27772 isObjectLike = require('./isObjectLike');
27773
27774/** `Object#toString` result references. */
27775var stringTag = '[object String]';
27776
27777/**
27778 * Checks if `value` is classified as a `String` primitive or object.
27779 *
27780 * @static
27781 * @since 0.1.0
27782 * @memberOf _
27783 * @category Lang
27784 * @param {*} value The value to check.
27785 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
27786 * @example
27787 *
27788 * _.isString('abc');
27789 * // => true
27790 *
27791 * _.isString(1);
27792 * // => false
27793 */
27794function isString(value) {
27795 return typeof value == 'string' ||
27796 (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
27797}
27798
27799module.exports = isString;
27800
27801},{"./_baseGetTag":180,"./isArray":319,"./isObjectLike":330}],334:[function(require,module,exports){
27802var baseGetTag = require('./_baseGetTag'),
27803 isObjectLike = require('./isObjectLike');
27804
27805/** `Object#toString` result references. */
27806var symbolTag = '[object Symbol]';
27807
27808/**
27809 * Checks if `value` is classified as a `Symbol` primitive or object.
27810 *
27811 * @static
27812 * @memberOf _
27813 * @since 4.0.0
27814 * @category Lang
27815 * @param {*} value The value to check.
27816 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
27817 * @example
27818 *
27819 * _.isSymbol(Symbol.iterator);
27820 * // => true
27821 *
27822 * _.isSymbol('abc');
27823 * // => false
27824 */
27825function isSymbol(value) {
27826 return typeof value == 'symbol' ||
27827 (isObjectLike(value) && baseGetTag(value) == symbolTag);
27828}
27829
27830module.exports = isSymbol;
27831
27832},{"./_baseGetTag":180,"./isObjectLike":330}],335:[function(require,module,exports){
27833var baseIsTypedArray = require('./_baseIsTypedArray'),
27834 baseUnary = require('./_baseUnary'),
27835 nodeUtil = require('./_nodeUtil');
27836
27837/* Node.js helper references. */
27838var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
27839
27840/**
27841 * Checks if `value` is classified as a typed array.
27842 *
27843 * @static
27844 * @memberOf _
27845 * @since 3.0.0
27846 * @category Lang
27847 * @param {*} value The value to check.
27848 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
27849 * @example
27850 *
27851 * _.isTypedArray(new Uint8Array);
27852 * // => true
27853 *
27854 * _.isTypedArray([]);
27855 * // => false
27856 */
27857var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
27858
27859module.exports = isTypedArray;
27860
27861},{"./_baseIsTypedArray":191,"./_baseUnary":209,"./_nodeUtil":282}],336:[function(require,module,exports){
27862/**
27863 * Checks if `value` is `undefined`.
27864 *
27865 * @static
27866 * @since 0.1.0
27867 * @memberOf _
27868 * @category Lang
27869 * @param {*} value The value to check.
27870 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
27871 * @example
27872 *
27873 * _.isUndefined(void 0);
27874 * // => true
27875 *
27876 * _.isUndefined(null);
27877 * // => false
27878 */
27879function isUndefined(value) {
27880 return value === undefined;
27881}
27882
27883module.exports = isUndefined;
27884
27885},{}],337:[function(require,module,exports){
27886var arrayLikeKeys = require('./_arrayLikeKeys'),
27887 baseKeys = require('./_baseKeys'),
27888 isArrayLike = require('./isArrayLike');
27889
27890/**
27891 * Creates an array of the own enumerable property names of `object`.
27892 *
27893 * **Note:** Non-object values are coerced to objects. See the
27894 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
27895 * for more details.
27896 *
27897 * @static
27898 * @since 0.1.0
27899 * @memberOf _
27900 * @category Object
27901 * @param {Object} object The object to query.
27902 * @returns {Array} Returns the array of property names.
27903 * @example
27904 *
27905 * function Foo() {
27906 * this.a = 1;
27907 * this.b = 2;
27908 * }
27909 *
27910 * Foo.prototype.c = 3;
27911 *
27912 * _.keys(new Foo);
27913 * // => ['a', 'b'] (iteration order is not guaranteed)
27914 *
27915 * _.keys('hi');
27916 * // => ['0', '1']
27917 */
27918function keys(object) {
27919 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
27920}
27921
27922module.exports = keys;
27923
27924},{"./_arrayLikeKeys":159,"./_baseKeys":193,"./isArrayLike":320}],338:[function(require,module,exports){
27925var arrayLikeKeys = require('./_arrayLikeKeys'),
27926 baseKeysIn = require('./_baseKeysIn'),
27927 isArrayLike = require('./isArrayLike');
27928
27929/**
27930 * Creates an array of the own and inherited enumerable property names of `object`.
27931 *
27932 * **Note:** Non-object values are coerced to objects.
27933 *
27934 * @static
27935 * @memberOf _
27936 * @since 3.0.0
27937 * @category Object
27938 * @param {Object} object The object to query.
27939 * @returns {Array} Returns the array of property names.
27940 * @example
27941 *
27942 * function Foo() {
27943 * this.a = 1;
27944 * this.b = 2;
27945 * }
27946 *
27947 * Foo.prototype.c = 3;
27948 *
27949 * _.keysIn(new Foo);
27950 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
27951 */
27952function keysIn(object) {
27953 return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
27954}
27955
27956module.exports = keysIn;
27957
27958},{"./_arrayLikeKeys":159,"./_baseKeysIn":194,"./isArrayLike":320}],339:[function(require,module,exports){
27959var arrayMap = require('./_arrayMap'),
27960 baseIteratee = require('./_baseIteratee'),
27961 baseMap = require('./_baseMap'),
27962 isArray = require('./isArray');
27963
27964/**
27965 * Creates an array of values by running each element in `collection` thru
27966 * `iteratee`. The iteratee is invoked with three arguments:
27967 * (value, index|key, collection).
27968 *
27969 * Many lodash methods are guarded to work as iteratees for methods like
27970 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
27971 *
27972 * The guarded methods are:
27973 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
27974 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
27975 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
27976 * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
27977 *
27978 * @static
27979 * @memberOf _
27980 * @since 0.1.0
27981 * @category Collection
27982 * @param {Array|Object} collection The collection to iterate over.
27983 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
27984 * @returns {Array} Returns the new mapped array.
27985 * @example
27986 *
27987 * function square(n) {
27988 * return n * n;
27989 * }
27990 *
27991 * _.map([4, 8], square);
27992 * // => [16, 64]
27993 *
27994 * _.map({ 'a': 4, 'b': 8 }, square);
27995 * // => [16, 64] (iteration order is not guaranteed)
27996 *
27997 * var users = [
27998 * { 'user': 'barney' },
27999 * { 'user': 'fred' }
28000 * ];
28001 *
28002 * // The `_.property` iteratee shorthand.
28003 * _.map(users, 'user');
28004 * // => ['barney', 'fred']
28005 */
28006function map(collection, iteratee) {
28007 var func = isArray(collection) ? arrayMap : baseMap;
28008 return func(collection, baseIteratee(iteratee, 3));
28009}
28010
28011module.exports = map;
28012
28013},{"./_arrayMap":160,"./_baseIteratee":192,"./_baseMap":195,"./isArray":319}],340:[function(require,module,exports){
28014var MapCache = require('./_MapCache');
28015
28016/** Error message constants. */
28017var FUNC_ERROR_TEXT = 'Expected a function';
28018
28019/**
28020 * Creates a function that memoizes the result of `func`. If `resolver` is
28021 * provided, it determines the cache key for storing the result based on the
28022 * arguments provided to the memoized function. By default, the first argument
28023 * provided to the memoized function is used as the map cache key. The `func`
28024 * is invoked with the `this` binding of the memoized function.
28025 *
28026 * **Note:** The cache is exposed as the `cache` property on the memoized
28027 * function. Its creation may be customized by replacing the `_.memoize.Cache`
28028 * constructor with one whose instances implement the
28029 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
28030 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
28031 *
28032 * @static
28033 * @memberOf _
28034 * @since 0.1.0
28035 * @category Function
28036 * @param {Function} func The function to have its output memoized.
28037 * @param {Function} [resolver] The function to resolve the cache key.
28038 * @returns {Function} Returns the new memoized function.
28039 * @example
28040 *
28041 * var object = { 'a': 1, 'b': 2 };
28042 * var other = { 'c': 3, 'd': 4 };
28043 *
28044 * var values = _.memoize(_.values);
28045 * values(object);
28046 * // => [1, 2]
28047 *
28048 * values(other);
28049 * // => [3, 4]
28050 *
28051 * object.a = 2;
28052 * values(object);
28053 * // => [1, 2]
28054 *
28055 * // Modify the result cache.
28056 * values.cache.set(object, ['a', 'b']);
28057 * values(object);
28058 * // => ['a', 'b']
28059 *
28060 * // Replace `_.memoize.Cache`.
28061 * _.memoize.Cache = WeakMap;
28062 */
28063function memoize(func, resolver) {
28064 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
28065 throw new TypeError(FUNC_ERROR_TEXT);
28066 }
28067 var memoized = function() {
28068 var args = arguments,
28069 key = resolver ? resolver.apply(this, args) : args[0],
28070 cache = memoized.cache;
28071
28072 if (cache.has(key)) {
28073 return cache.get(key);
28074 }
28075 var result = func.apply(this, args);
28076 memoized.cache = cache.set(key, result) || cache;
28077 return result;
28078 };
28079 memoized.cache = new (memoize.Cache || MapCache);
28080 return memoized;
28081}
28082
28083// Expose `MapCache`.
28084memoize.Cache = MapCache;
28085
28086module.exports = memoize;
28087
28088},{"./_MapCache":147}],341:[function(require,module,exports){
28089var createPadding = require('./_createPadding'),
28090 stringSize = require('./_stringSize'),
28091 toInteger = require('./toInteger'),
28092 toString = require('./toString');
28093
28094/**
28095 * Pads `string` on the right side if it's shorter than `length`. Padding
28096 * characters are truncated if they exceed `length`.
28097 *
28098 * @static
28099 * @memberOf _
28100 * @since 4.0.0
28101 * @category String
28102 * @param {string} [string=''] The string to pad.
28103 * @param {number} [length=0] The padding length.
28104 * @param {string} [chars=' '] The string used as padding.
28105 * @returns {string} Returns the padded string.
28106 * @example
28107 *
28108 * _.padEnd('abc', 6);
28109 * // => 'abc '
28110 *
28111 * _.padEnd('abc', 6, '_-');
28112 * // => 'abc_-_'
28113 *
28114 * _.padEnd('abc', 3);
28115 * // => 'abc'
28116 */
28117function padEnd(string, length, chars) {
28118 string = toString(string);
28119 length = toInteger(length);
28120
28121 var strLength = length ? stringSize(string) : 0;
28122 return (length && strLength < length)
28123 ? (string + createPadding(length - strLength, chars))
28124 : string;
28125}
28126
28127module.exports = padEnd;
28128
28129},{"./_createPadding":230,"./_stringSize":298,"./toInteger":348,"./toString":350}],342:[function(require,module,exports){
28130var basePick = require('./_basePick'),
28131 flatRest = require('./_flatRest');
28132
28133/**
28134 * Creates an object composed of the picked `object` properties.
28135 *
28136 * @static
28137 * @since 0.1.0
28138 * @memberOf _
28139 * @category Object
28140 * @param {Object} object The source object.
28141 * @param {...(string|string[])} [paths] The property paths to pick.
28142 * @returns {Object} Returns the new object.
28143 * @example
28144 *
28145 * var object = { 'a': 1, 'b': '2', 'c': 3 };
28146 *
28147 * _.pick(object, ['a', 'c']);
28148 * // => { 'a': 1, 'c': 3 }
28149 */
28150var pick = flatRest(function(object, paths) {
28151 return object == null ? {} : basePick(object, paths);
28152});
28153
28154module.exports = pick;
28155
28156},{"./_basePick":198,"./_flatRest":235}],343:[function(require,module,exports){
28157var baseProperty = require('./_baseProperty'),
28158 basePropertyDeep = require('./_basePropertyDeep'),
28159 isKey = require('./_isKey'),
28160 toKey = require('./_toKey');
28161
28162/**
28163 * Creates a function that returns the value at `path` of a given object.
28164 *
28165 * @static
28166 * @memberOf _
28167 * @since 2.4.0
28168 * @category Util
28169 * @param {Array|string} path The path of the property to get.
28170 * @returns {Function} Returns the new accessor function.
28171 * @example
28172 *
28173 * var objects = [
28174 * { 'a': { 'b': 2 } },
28175 * { 'a': { 'b': 1 } }
28176 * ];
28177 *
28178 * _.map(objects, _.property('a.b'));
28179 * // => [2, 1]
28180 *
28181 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
28182 * // => [1, 2]
28183 */
28184function property(path) {
28185 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
28186}
28187
28188module.exports = property;
28189
28190},{"./_baseProperty":200,"./_basePropertyDeep":201,"./_isKey":261,"./_toKey":301}],344:[function(require,module,exports){
28191/**
28192 * This method returns a new empty array.
28193 *
28194 * @static
28195 * @memberOf _
28196 * @since 4.13.0
28197 * @category Util
28198 * @returns {Array} Returns the new empty array.
28199 * @example
28200 *
28201 * var arrays = _.times(2, _.stubArray);
28202 *
28203 * console.log(arrays);
28204 * // => [[], []]
28205 *
28206 * console.log(arrays[0] === arrays[1]);
28207 * // => false
28208 */
28209function stubArray() {
28210 return [];
28211}
28212
28213module.exports = stubArray;
28214
28215},{}],345:[function(require,module,exports){
28216/**
28217 * This method returns `false`.
28218 *
28219 * @static
28220 * @memberOf _
28221 * @since 4.13.0
28222 * @category Util
28223 * @returns {boolean} Returns `false`.
28224 * @example
28225 *
28226 * _.times(2, _.stubFalse);
28227 * // => [false, false]
28228 */
28229function stubFalse() {
28230 return false;
28231}
28232
28233module.exports = stubFalse;
28234
28235},{}],346:[function(require,module,exports){
28236var baseTimes = require('./_baseTimes'),
28237 castFunction = require('./_castFunction'),
28238 toInteger = require('./toInteger');
28239
28240/** Used as references for various `Number` constants. */
28241var MAX_SAFE_INTEGER = 9007199254740991;
28242
28243/** Used as references for the maximum length and index of an array. */
28244var MAX_ARRAY_LENGTH = 4294967295;
28245
28246/* Built-in method references for those with the same name as other `lodash` methods. */
28247var nativeMin = Math.min;
28248
28249/**
28250 * Invokes the iteratee `n` times, returning an array of the results of
28251 * each invocation. The iteratee is invoked with one argument; (index).
28252 *
28253 * @static
28254 * @since 0.1.0
28255 * @memberOf _
28256 * @category Util
28257 * @param {number} n The number of times to invoke `iteratee`.
28258 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
28259 * @returns {Array} Returns the array of results.
28260 * @example
28261 *
28262 * _.times(3, String);
28263 * // => ['0', '1', '2']
28264 *
28265 * _.times(4, _.constant(0));
28266 * // => [0, 0, 0, 0]
28267 */
28268function times(n, iteratee) {
28269 n = toInteger(n);
28270 if (n < 1 || n > MAX_SAFE_INTEGER) {
28271 return [];
28272 }
28273 var index = MAX_ARRAY_LENGTH,
28274 length = nativeMin(n, MAX_ARRAY_LENGTH);
28275
28276 iteratee = castFunction(iteratee);
28277 n -= MAX_ARRAY_LENGTH;
28278
28279 var result = baseTimes(length, iteratee);
28280 while (++index < n) {
28281 iteratee(index);
28282 }
28283 return result;
28284}
28285
28286module.exports = times;
28287
28288},{"./_baseTimes":207,"./_castFunction":212,"./toInteger":348}],347:[function(require,module,exports){
28289var toNumber = require('./toNumber');
28290
28291/** Used as references for various `Number` constants. */
28292var INFINITY = 1 / 0,
28293 MAX_INTEGER = 1.7976931348623157e+308;
28294
28295/**
28296 * Converts `value` to a finite number.
28297 *
28298 * @static
28299 * @memberOf _
28300 * @since 4.12.0
28301 * @category Lang
28302 * @param {*} value The value to convert.
28303 * @returns {number} Returns the converted number.
28304 * @example
28305 *
28306 * _.toFinite(3.2);
28307 * // => 3.2
28308 *
28309 * _.toFinite(Number.MIN_VALUE);
28310 * // => 5e-324
28311 *
28312 * _.toFinite(Infinity);
28313 * // => 1.7976931348623157e+308
28314 *
28315 * _.toFinite('3.2');
28316 * // => 3.2
28317 */
28318function toFinite(value) {
28319 if (!value) {
28320 return value === 0 ? value : 0;
28321 }
28322 value = toNumber(value);
28323 if (value === INFINITY || value === -INFINITY) {
28324 var sign = (value < 0 ? -1 : 1);
28325 return sign * MAX_INTEGER;
28326 }
28327 return value === value ? value : 0;
28328}
28329
28330module.exports = toFinite;
28331
28332},{"./toNumber":349}],348:[function(require,module,exports){
28333var toFinite = require('./toFinite');
28334
28335/**
28336 * Converts `value` to an integer.
28337 *
28338 * **Note:** This method is loosely based on
28339 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
28340 *
28341 * @static
28342 * @memberOf _
28343 * @since 4.0.0
28344 * @category Lang
28345 * @param {*} value The value to convert.
28346 * @returns {number} Returns the converted integer.
28347 * @example
28348 *
28349 * _.toInteger(3.2);
28350 * // => 3
28351 *
28352 * _.toInteger(Number.MIN_VALUE);
28353 * // => 0
28354 *
28355 * _.toInteger(Infinity);
28356 * // => 1.7976931348623157e+308
28357 *
28358 * _.toInteger('3.2');
28359 * // => 3
28360 */
28361function toInteger(value) {
28362 var result = toFinite(value),
28363 remainder = result % 1;
28364
28365 return result === result ? (remainder ? result - remainder : result) : 0;
28366}
28367
28368module.exports = toInteger;
28369
28370},{"./toFinite":347}],349:[function(require,module,exports){
28371var isObject = require('./isObject'),
28372 isSymbol = require('./isSymbol');
28373
28374/** Used as references for various `Number` constants. */
28375var NAN = 0 / 0;
28376
28377/** Used to match leading and trailing whitespace. */
28378var reTrim = /^\s+|\s+$/g;
28379
28380/** Used to detect bad signed hexadecimal string values. */
28381var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
28382
28383/** Used to detect binary string values. */
28384var reIsBinary = /^0b[01]+$/i;
28385
28386/** Used to detect octal string values. */
28387var reIsOctal = /^0o[0-7]+$/i;
28388
28389/** Built-in method references without a dependency on `root`. */
28390var freeParseInt = parseInt;
28391
28392/**
28393 * Converts `value` to a number.
28394 *
28395 * @static
28396 * @memberOf _
28397 * @since 4.0.0
28398 * @category Lang
28399 * @param {*} value The value to process.
28400 * @returns {number} Returns the number.
28401 * @example
28402 *
28403 * _.toNumber(3.2);
28404 * // => 3.2
28405 *
28406 * _.toNumber(Number.MIN_VALUE);
28407 * // => 5e-324
28408 *
28409 * _.toNumber(Infinity);
28410 * // => Infinity
28411 *
28412 * _.toNumber('3.2');
28413 * // => 3.2
28414 */
28415function toNumber(value) {
28416 if (typeof value == 'number') {
28417 return value;
28418 }
28419 if (isSymbol(value)) {
28420 return NAN;
28421 }
28422 if (isObject(value)) {
28423 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
28424 value = isObject(other) ? (other + '') : other;
28425 }
28426 if (typeof value != 'string') {
28427 return value === 0 ? value : +value;
28428 }
28429 value = value.replace(reTrim, '');
28430 var isBinary = reIsBinary.test(value);
28431 return (isBinary || reIsOctal.test(value))
28432 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
28433 : (reIsBadHex.test(value) ? NAN : +value);
28434}
28435
28436module.exports = toNumber;
28437
28438},{"./isObject":329,"./isSymbol":334}],350:[function(require,module,exports){
28439var baseToString = require('./_baseToString');
28440
28441/**
28442 * Converts `value` to a string. An empty string is returned for `null`
28443 * and `undefined` values. The sign of `-0` is preserved.
28444 *
28445 * @static
28446 * @memberOf _
28447 * @since 4.0.0
28448 * @category Lang
28449 * @param {*} value The value to convert.
28450 * @returns {string} Returns the converted string.
28451 * @example
28452 *
28453 * _.toString(null);
28454 * // => ''
28455 *
28456 * _.toString(-0);
28457 * // => '-0'
28458 *
28459 * _.toString([1, 2, 3]);
28460 * // => '1,2,3'
28461 */
28462function toString(value) {
28463 return value == null ? '' : baseToString(value);
28464}
28465
28466module.exports = toString;
28467
28468},{"./_baseToString":208}],351:[function(require,module,exports){
28469var baseToString = require('./_baseToString'),
28470 castSlice = require('./_castSlice'),
28471 charsEndIndex = require('./_charsEndIndex'),
28472 stringToArray = require('./_stringToArray'),
28473 toString = require('./toString');
28474
28475/** Used to match leading and trailing whitespace. */
28476var reTrimEnd = /\s+$/;
28477
28478/**
28479 * Removes trailing whitespace or specified characters from `string`.
28480 *
28481 * @static
28482 * @memberOf _
28483 * @since 4.0.0
28484 * @category String
28485 * @param {string} [string=''] The string to trim.
28486 * @param {string} [chars=whitespace] The characters to trim.
28487 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
28488 * @returns {string} Returns the trimmed string.
28489 * @example
28490 *
28491 * _.trimEnd(' abc ');
28492 * // => ' abc'
28493 *
28494 * _.trimEnd('-_-abc-_-', '_-');
28495 * // => '-_-abc'
28496 */
28497function trimEnd(string, chars, guard) {
28498 string = toString(string);
28499 if (string && (guard || chars === undefined)) {
28500 return string.replace(reTrimEnd, '');
28501 }
28502 if (!string || !(chars = baseToString(chars))) {
28503 return string;
28504 }
28505 var strSymbols = stringToArray(string),
28506 end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
28507
28508 return castSlice(strSymbols, 0, end).join('');
28509}
28510
28511module.exports = trimEnd;
28512
28513},{"./_baseToString":208,"./_castSlice":214,"./_charsEndIndex":215,"./_stringToArray":299,"./toString":350}],352:[function(require,module,exports){
28514var baseValues = require('./_baseValues'),
28515 keys = require('./keys');
28516
28517/**
28518 * Creates an array of the own enumerable string keyed property values of `object`.
28519 *
28520 * **Note:** Non-object values are coerced to objects.
28521 *
28522 * @static
28523 * @since 0.1.0
28524 * @memberOf _
28525 * @category Object
28526 * @param {Object} object The object to query.
28527 * @returns {Array} Returns the array of property values.
28528 * @example
28529 *
28530 * function Foo() {
28531 * this.a = 1;
28532 * this.b = 2;
28533 * }
28534 *
28535 * Foo.prototype.c = 3;
28536 *
28537 * _.values(new Foo);
28538 * // => [1, 2] (iteration order is not guaranteed)
28539 *
28540 * _.values('hi');
28541 * // => ['h', 'i']
28542 */
28543function values(object) {
28544 return object == null ? [] : baseValues(object, keys(object));
28545}
28546
28547module.exports = values;
28548
28549},{"./_baseValues":210,"./keys":337}],353:[function(require,module,exports){
28550/*
28551 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
28552 Copyright 2009 The Closure Library Authors. All Rights Reserved.
28553
28554 Licensed under the Apache License, Version 2.0 (the "License");
28555 you may not use this file except in compliance with the License.
28556 You may obtain a copy of the License at
28557
28558 http://www.apache.org/licenses/LICENSE-2.0
28559
28560 Unless required by applicable law or agreed to in writing, software
28561 distributed under the License is distributed on an "AS-IS" BASIS,
28562 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28563 See the License for the specific language governing permissions and
28564 limitations under the License.
28565 */
28566
28567/**
28568 * @license Long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
28569 * Released under the Apache License, Version 2.0
28570 * see: https://github.com/dcodeIO/Long.js for details
28571 */
28572(function(global, factory) {
28573
28574 /* AMD */ if (typeof define === 'function' && define["amd"])
28575 define([], factory);
28576 /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
28577 module["exports"] = factory();
28578 /* Global */ else
28579 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
28580
28581})(this, function() {
28582 "use strict";
28583
28584 /**
28585 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
28586 * See the from* functions below for more convenient ways of constructing Longs.
28587 * @exports Long
28588 * @class A Long class for representing a 64 bit two's-complement integer value.
28589 * @param {number} low The low (signed) 32 bits of the long
28590 * @param {number} high The high (signed) 32 bits of the long
28591 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
28592 * @constructor
28593 */
28594 function Long(low, high, unsigned) {
28595
28596 /**
28597 * The low 32 bits as a signed value.
28598 * @type {number}
28599 * @expose
28600 */
28601 this.low = low|0;
28602
28603 /**
28604 * The high 32 bits as a signed value.
28605 * @type {number}
28606 * @expose
28607 */
28608 this.high = high|0;
28609
28610 /**
28611 * Whether unsigned or not.
28612 * @type {boolean}
28613 * @expose
28614 */
28615 this.unsigned = !!unsigned;
28616 }
28617
28618 // The internal representation of a long is the two given signed, 32-bit values.
28619 // We use 32-bit pieces because these are the size of integers on which
28620 // Javascript performs bit-operations. For operations like addition and
28621 // multiplication, we split each number into 16 bit pieces, which can easily be
28622 // multiplied within Javascript's floating-point representation without overflow
28623 // or change in sign.
28624 //
28625 // In the algorithms below, we frequently reduce the negative case to the
28626 // positive case by negating the input(s) and then post-processing the result.
28627 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
28628 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
28629 // a positive number, it overflows back into a negative). Not handling this
28630 // case would often result in infinite recursion.
28631 //
28632 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
28633 // methods on which they depend.
28634
28635 /**
28636 * An indicator used to reliably determine if an object is a Long or not.
28637 * @type {boolean}
28638 * @const
28639 * @expose
28640 * @private
28641 */
28642 Long.__isLong__;
28643
28644 Object.defineProperty(Long.prototype, "__isLong__", {
28645 value: true,
28646 enumerable: false,
28647 configurable: false
28648 });
28649
28650 /**
28651 * Tests if the specified object is a Long.
28652 * @param {*} obj Object
28653 * @returns {boolean}
28654 * @expose
28655 */
28656 Long.isLong = function isLong(obj) {
28657 return (obj && obj["__isLong__"]) === true;
28658 };
28659
28660 /**
28661 * A cache of the Long representations of small integer values.
28662 * @type {!Object}
28663 * @inner
28664 */
28665 var INT_CACHE = {};
28666
28667 /**
28668 * A cache of the Long representations of small unsigned integer values.
28669 * @type {!Object}
28670 * @inner
28671 */
28672 var UINT_CACHE = {};
28673
28674 /**
28675 * Returns a Long representing the given 32 bit integer value.
28676 * @param {number} value The 32 bit integer in question
28677 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
28678 * @returns {!Long} The corresponding Long value
28679 * @expose
28680 */
28681 Long.fromInt = function fromInt(value, unsigned) {
28682 var obj, cachedObj;
28683 if (!unsigned) {
28684 value = value | 0;
28685 if (-128 <= value && value < 128) {
28686 cachedObj = INT_CACHE[value];
28687 if (cachedObj)
28688 return cachedObj;
28689 }
28690 obj = new Long(value, value < 0 ? -1 : 0, false);
28691 if (-128 <= value && value < 128)
28692 INT_CACHE[value] = obj;
28693 return obj;
28694 } else {
28695 value = value >>> 0;
28696 if (0 <= value && value < 256) {
28697 cachedObj = UINT_CACHE[value];
28698 if (cachedObj)
28699 return cachedObj;
28700 }
28701 obj = new Long(value, (value | 0) < 0 ? -1 : 0, true);
28702 if (0 <= value && value < 256)
28703 UINT_CACHE[value] = obj;
28704 return obj;
28705 }
28706 };
28707
28708 /**
28709 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
28710 * @param {number} value The number in question
28711 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
28712 * @returns {!Long} The corresponding Long value
28713 * @expose
28714 */
28715 Long.fromNumber = function fromNumber(value, unsigned) {
28716 unsigned = !!unsigned;
28717 if (isNaN(value) || !isFinite(value))
28718 return Long.ZERO;
28719 if (!unsigned && value <= -TWO_PWR_63_DBL)
28720 return Long.MIN_VALUE;
28721 if (!unsigned && value + 1 >= TWO_PWR_63_DBL)
28722 return Long.MAX_VALUE;
28723 if (unsigned && value >= TWO_PWR_64_DBL)
28724 return Long.MAX_UNSIGNED_VALUE;
28725 if (value < 0)
28726 return Long.fromNumber(-value, unsigned).negate();
28727 return new Long((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
28728 };
28729
28730 /**
28731 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
28732 * assumed to use 32 bits.
28733 * @param {number} lowBits The low 32 bits
28734 * @param {number} highBits The high 32 bits
28735 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
28736 * @returns {!Long} The corresponding Long value
28737 * @expose
28738 */
28739 Long.fromBits = function fromBits(lowBits, highBits, unsigned) {
28740 return new Long(lowBits, highBits, unsigned);
28741 };
28742
28743 /**
28744 * Returns a Long representation of the given string, written using the specified radix.
28745 * @param {string} str The textual representation of the Long
28746 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
28747 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
28748 * @returns {!Long} The corresponding Long value
28749 * @expose
28750 */
28751 Long.fromString = function fromString(str, unsigned, radix) {
28752 if (str.length === 0)
28753 throw Error('number format error: empty string');
28754 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
28755 return Long.ZERO;
28756 if (typeof unsigned === 'number') // For goog.math.long compatibility
28757 radix = unsigned,
28758 unsigned = false;
28759 radix = radix || 10;
28760 if (radix < 2 || 36 < radix)
28761 throw Error('radix out of range: ' + radix);
28762
28763 var p;
28764 if ((p = str.indexOf('-')) > 0)
28765 throw Error('number format error: interior "-" character: ' + str);
28766 else if (p === 0)
28767 return Long.fromString(str.substring(1), unsigned, radix).negate();
28768
28769 // Do several (8) digits each time through the loop, so as to
28770 // minimize the calls to the very expensive emulated div.
28771 var radixToPower = Long.fromNumber(Math.pow(radix, 8));
28772
28773 var result = Long.ZERO;
28774 for (var i = 0; i < str.length; i += 8) {
28775 var size = Math.min(8, str.length - i);
28776 var value = parseInt(str.substring(i, i + size), radix);
28777 if (size < 8) {
28778 var power = Long.fromNumber(Math.pow(radix, size));
28779 result = result.multiply(power).add(Long.fromNumber(value));
28780 } else {
28781 result = result.multiply(radixToPower);
28782 result = result.add(Long.fromNumber(value));
28783 }
28784 }
28785 result.unsigned = unsigned;
28786 return result;
28787 };
28788
28789 /**
28790 * Converts the specified value to a Long.
28791 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
28792 * @returns {!Long}
28793 * @expose
28794 */
28795 Long.fromValue = function fromValue(val) {
28796 if (val /* is compatible */ instanceof Long)
28797 return val;
28798 if (typeof val === 'number')
28799 return Long.fromNumber(val);
28800 if (typeof val === 'string')
28801 return Long.fromString(val);
28802 // Throws for non-objects, converts non-instanceof Long:
28803 return new Long(val.low, val.high, val.unsigned);
28804 };
28805
28806 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
28807 // no runtime penalty for these.
28808
28809 /**
28810 * @type {number}
28811 * @const
28812 * @inner
28813 */
28814 var TWO_PWR_16_DBL = 1 << 16;
28815
28816 /**
28817 * @type {number}
28818 * @const
28819 * @inner
28820 */
28821 var TWO_PWR_24_DBL = 1 << 24;
28822
28823 /**
28824 * @type {number}
28825 * @const
28826 * @inner
28827 */
28828 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
28829
28830 /**
28831 * @type {number}
28832 * @const
28833 * @inner
28834 */
28835 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
28836
28837 /**
28838 * @type {number}
28839 * @const
28840 * @inner
28841 */
28842 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
28843
28844 /**
28845 * @type {!Long}
28846 * @const
28847 * @inner
28848 */
28849 var TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
28850
28851 /**
28852 * Signed zero.
28853 * @type {!Long}
28854 * @expose
28855 */
28856 Long.ZERO = Long.fromInt(0);
28857
28858 /**
28859 * Unsigned zero.
28860 * @type {!Long}
28861 * @expose
28862 */
28863 Long.UZERO = Long.fromInt(0, true);
28864
28865 /**
28866 * Signed one.
28867 * @type {!Long}
28868 * @expose
28869 */
28870 Long.ONE = Long.fromInt(1);
28871
28872 /**
28873 * Unsigned one.
28874 * @type {!Long}
28875 * @expose
28876 */
28877 Long.UONE = Long.fromInt(1, true);
28878
28879 /**
28880 * Signed negative one.
28881 * @type {!Long}
28882 * @expose
28883 */
28884 Long.NEG_ONE = Long.fromInt(-1);
28885
28886 /**
28887 * Maximum signed value.
28888 * @type {!Long}
28889 * @expose
28890 */
28891 Long.MAX_VALUE = Long.fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
28892
28893 /**
28894 * Maximum unsigned value.
28895 * @type {!Long}
28896 * @expose
28897 */
28898 Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
28899
28900 /**
28901 * Minimum signed value.
28902 * @type {!Long}
28903 * @expose
28904 */
28905 Long.MIN_VALUE = Long.fromBits(0, 0x80000000|0, false);
28906
28907 /**
28908 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
28909 * @returns {number}
28910 * @expose
28911 */
28912 Long.prototype.toInt = function toInt() {
28913 return this.unsigned ? this.low >>> 0 : this.low;
28914 };
28915
28916 /**
28917 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
28918 * @returns {number}
28919 * @expose
28920 */
28921 Long.prototype.toNumber = function toNumber() {
28922 if (this.unsigned) {
28923 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
28924 }
28925 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
28926 };
28927
28928 /**
28929 * Converts the Long to a string written in the specified radix.
28930 * @param {number=} radix Radix (2-36), defaults to 10
28931 * @returns {string}
28932 * @override
28933 * @throws {RangeError} If `radix` is out of range
28934 * @expose
28935 */
28936 Long.prototype.toString = function toString(radix) {
28937 radix = radix || 10;
28938 if (radix < 2 || 36 < radix)
28939 throw RangeError('radix out of range: ' + radix);
28940 if (this.isZero())
28941 return '0';
28942 var rem;
28943 if (this.isNegative()) { // Unsigned Longs are never negative
28944 if (this.equals(Long.MIN_VALUE)) {
28945 // We need to change the Long value before it can be negated, so we remove
28946 // the bottom-most digit in this base and then recurse to do the rest.
28947 var radixLong = Long.fromNumber(radix);
28948 var div = this.divide(radixLong);
28949 rem = div.multiply(radixLong).subtract(this);
28950 return div.toString(radix) + rem.toInt().toString(radix);
28951 } else
28952 return '-' + this.negate().toString(radix);
28953 }
28954
28955 // Do several (6) digits each time through the loop, so as to
28956 // minimize the calls to the very expensive emulated div.
28957 var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
28958 rem = this;
28959 var result = '';
28960 while (true) {
28961 var remDiv = rem.divide(radixToPower),
28962 intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0,
28963 digits = intval.toString(radix);
28964 rem = remDiv;
28965 if (rem.isZero())
28966 return digits + result;
28967 else {
28968 while (digits.length < 6)
28969 digits = '0' + digits;
28970 result = '' + digits + result;
28971 }
28972 }
28973 };
28974
28975 /**
28976 * Gets the high 32 bits as a signed integer.
28977 * @returns {number} Signed high bits
28978 * @expose
28979 */
28980 Long.prototype.getHighBits = function getHighBits() {
28981 return this.high;
28982 };
28983
28984 /**
28985 * Gets the high 32 bits as an unsigned integer.
28986 * @returns {number} Unsigned high bits
28987 * @expose
28988 */
28989 Long.prototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
28990 return this.high >>> 0;
28991 };
28992
28993 /**
28994 * Gets the low 32 bits as a signed integer.
28995 * @returns {number} Signed low bits
28996 * @expose
28997 */
28998 Long.prototype.getLowBits = function getLowBits() {
28999 return this.low;
29000 };
29001
29002 /**
29003 * Gets the low 32 bits as an unsigned integer.
29004 * @returns {number} Unsigned low bits
29005 * @expose
29006 */
29007 Long.prototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
29008 return this.low >>> 0;
29009 };
29010
29011 /**
29012 * Gets the number of bits needed to represent the absolute value of this Long.
29013 * @returns {number}
29014 * @expose
29015 */
29016 Long.prototype.getNumBitsAbs = function getNumBitsAbs() {
29017 if (this.isNegative()) // Unsigned Longs are never negative
29018 return this.equals(Long.MIN_VALUE) ? 64 : this.negate().getNumBitsAbs();
29019 var val = this.high != 0 ? this.high : this.low;
29020 for (var bit = 31; bit > 0; bit--)
29021 if ((val & (1 << bit)) != 0)
29022 break;
29023 return this.high != 0 ? bit + 33 : bit + 1;
29024 };
29025
29026 /**
29027 * Tests if this Long's value equals zero.
29028 * @returns {boolean}
29029 * @expose
29030 */
29031 Long.prototype.isZero = function isZero() {
29032 return this.high === 0 && this.low === 0;
29033 };
29034
29035 /**
29036 * Tests if this Long's value is negative.
29037 * @returns {boolean}
29038 * @expose
29039 */
29040 Long.prototype.isNegative = function isNegative() {
29041 return !this.unsigned && this.high < 0;
29042 };
29043
29044 /**
29045 * Tests if this Long's value is positive.
29046 * @returns {boolean}
29047 * @expose
29048 */
29049 Long.prototype.isPositive = function isPositive() {
29050 return this.unsigned || this.high >= 0;
29051 };
29052
29053 /**
29054 * Tests if this Long's value is odd.
29055 * @returns {boolean}
29056 * @expose
29057 */
29058 Long.prototype.isOdd = function isOdd() {
29059 return (this.low & 1) === 1;
29060 };
29061
29062 /**
29063 * Tests if this Long's value is even.
29064 * @returns {boolean}
29065 * @expose
29066 */
29067 Long.prototype.isEven = function isEven() {
29068 return (this.low & 1) === 0;
29069 };
29070
29071 /**
29072 * Tests if this Long's value equals the specified's.
29073 * @param {!Long|number|string} other Other value
29074 * @returns {boolean}
29075 * @expose
29076 */
29077 Long.prototype.equals = function equals(other) {
29078 if (!Long.isLong(other))
29079 other = Long.fromValue(other);
29080 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
29081 return false;
29082 return this.high === other.high && this.low === other.low;
29083 };
29084
29085 /**
29086 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
29087 * @function
29088 * @param {!Long|number|string} other Other value
29089 * @returns {boolean}
29090 * @expose
29091 */
29092 Long.eq = Long.prototype.equals;
29093
29094 /**
29095 * Tests if this Long's value differs from the specified's.
29096 * @param {!Long|number|string} other Other value
29097 * @returns {boolean}
29098 * @expose
29099 */
29100 Long.prototype.notEquals = function notEquals(other) {
29101 return !this.equals(/* validates */ other);
29102 };
29103
29104 /**
29105 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
29106 * @function
29107 * @param {!Long|number|string} other Other value
29108 * @returns {boolean}
29109 * @expose
29110 */
29111 Long.neq = Long.prototype.notEquals;
29112
29113 /**
29114 * Tests if this Long's value is less than the specified's.
29115 * @param {!Long|number|string} other Other value
29116 * @returns {boolean}
29117 * @expose
29118 */
29119 Long.prototype.lessThan = function lessThan(other) {
29120 return this.compare(/* validates */ other) < 0;
29121 };
29122
29123 /**
29124 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
29125 * @function
29126 * @param {!Long|number|string} other Other value
29127 * @returns {boolean}
29128 * @expose
29129 */
29130 Long.prototype.lt = Long.prototype.lessThan;
29131
29132 /**
29133 * Tests if this Long's value is less than or equal the specified's.
29134 * @param {!Long|number|string} other Other value
29135 * @returns {boolean}
29136 * @expose
29137 */
29138 Long.prototype.lessThanOrEqual = function lessThanOrEqual(other) {
29139 return this.compare(/* validates */ other) <= 0;
29140 };
29141
29142 /**
29143 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
29144 * @function
29145 * @param {!Long|number|string} other Other value
29146 * @returns {boolean}
29147 * @expose
29148 */
29149 Long.prototype.lte = Long.prototype.lessThanOrEqual;
29150
29151 /**
29152 * Tests if this Long's value is greater than the specified's.
29153 * @param {!Long|number|string} other Other value
29154 * @returns {boolean}
29155 * @expose
29156 */
29157 Long.prototype.greaterThan = function greaterThan(other) {
29158 return this.compare(/* validates */ other) > 0;
29159 };
29160
29161 /**
29162 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
29163 * @function
29164 * @param {!Long|number|string} other Other value
29165 * @returns {boolean}
29166 * @expose
29167 */
29168 Long.prototype.gt = Long.prototype.greaterThan;
29169
29170 /**
29171 * Tests if this Long's value is greater than or equal the specified's.
29172 * @param {!Long|number|string} other Other value
29173 * @returns {boolean}
29174 * @expose
29175 */
29176 Long.prototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
29177 return this.compare(/* validates */ other) >= 0;
29178 };
29179
29180 /**
29181 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
29182 * @function
29183 * @param {!Long|number|string} other Other value
29184 * @returns {boolean}
29185 * @expose
29186 */
29187 Long.prototype.gte = Long.prototype.greaterThanOrEqual;
29188
29189 /**
29190 * Compares this Long's value with the specified's.
29191 * @param {!Long|number|string} other Other value
29192 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
29193 * if the given one is greater
29194 * @expose
29195 */
29196 Long.prototype.compare = function compare(other) {
29197 if (!Long.isLong(other))
29198 other = Long.fromValue(other);
29199 if (this.equals(other))
29200 return 0;
29201 var thisNeg = this.isNegative(),
29202 otherNeg = other.isNegative();
29203 if (thisNeg && !otherNeg)
29204 return -1;
29205 if (!thisNeg && otherNeg)
29206 return 1;
29207 // At this point the sign bits are the same
29208 if (!this.unsigned)
29209 return this.subtract(other).isNegative() ? -1 : 1;
29210 // Both are positive if at least one is unsigned
29211 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
29212 };
29213
29214 /**
29215 * Negates this Long's value.
29216 * @returns {!Long} Negated Long
29217 * @expose
29218 */
29219 Long.prototype.negate = function negate() {
29220 if (!this.unsigned && this.equals(Long.MIN_VALUE))
29221 return Long.MIN_VALUE;
29222 return this.not().add(Long.ONE);
29223 };
29224
29225 /**
29226 * Negates this Long's value. This is an alias of {@link Long#negate}.
29227 * @function
29228 * @returns {!Long} Negated Long
29229 * @expose
29230 */
29231 Long.prototype.neg = Long.prototype.negate;
29232
29233 /**
29234 * Returns the sum of this and the specified Long.
29235 * @param {!Long|number|string} addend Addend
29236 * @returns {!Long} Sum
29237 * @expose
29238 */
29239 Long.prototype.add = function add(addend) {
29240 if (!Long.isLong(addend))
29241 addend = Long.fromValue(addend);
29242
29243 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
29244
29245 var a48 = this.high >>> 16;
29246 var a32 = this.high & 0xFFFF;
29247 var a16 = this.low >>> 16;
29248 var a00 = this.low & 0xFFFF;
29249
29250 var b48 = addend.high >>> 16;
29251 var b32 = addend.high & 0xFFFF;
29252 var b16 = addend.low >>> 16;
29253 var b00 = addend.low & 0xFFFF;
29254
29255 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
29256 c00 += a00 + b00;
29257 c16 += c00 >>> 16;
29258 c00 &= 0xFFFF;
29259 c16 += a16 + b16;
29260 c32 += c16 >>> 16;
29261 c16 &= 0xFFFF;
29262 c32 += a32 + b32;
29263 c48 += c32 >>> 16;
29264 c32 &= 0xFFFF;
29265 c48 += a48 + b48;
29266 c48 &= 0xFFFF;
29267 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
29268 };
29269
29270 /**
29271 * Returns the difference of this and the specified Long.
29272 * @param {!Long|number|string} subtrahend Subtrahend
29273 * @returns {!Long} Difference
29274 * @expose
29275 */
29276 Long.prototype.subtract = function subtract(subtrahend) {
29277 if (!Long.isLong(subtrahend))
29278 subtrahend = Long.fromValue(subtrahend);
29279 return this.add(subtrahend.negate());
29280 };
29281
29282 /**
29283 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
29284 * @function
29285 * @param {!Long|number|string} subtrahend Subtrahend
29286 * @returns {!Long} Difference
29287 * @expose
29288 */
29289 Long.prototype.sub = Long.prototype.subtract;
29290
29291 /**
29292 * Returns the product of this and the specified Long.
29293 * @param {!Long|number|string} multiplier Multiplier
29294 * @returns {!Long} Product
29295 * @expose
29296 */
29297 Long.prototype.multiply = function multiply(multiplier) {
29298 if (this.isZero())
29299 return Long.ZERO;
29300 if (!Long.isLong(multiplier))
29301 multiplier = Long.fromValue(multiplier);
29302 if (multiplier.isZero())
29303 return Long.ZERO;
29304 if (this.equals(Long.MIN_VALUE))
29305 return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
29306 if (multiplier.equals(Long.MIN_VALUE))
29307 return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
29308
29309 if (this.isNegative()) {
29310 if (multiplier.isNegative())
29311 return this.negate().multiply(multiplier.negate());
29312 else
29313 return this.negate().multiply(multiplier).negate();
29314 } else if (multiplier.isNegative())
29315 return this.multiply(multiplier.negate()).negate();
29316
29317 // If both longs are small, use float multiplication
29318 if (this.lessThan(TWO_PWR_24) && multiplier.lessThan(TWO_PWR_24))
29319 return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
29320
29321 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
29322 // We can skip products that would overflow.
29323
29324 var a48 = this.high >>> 16;
29325 var a32 = this.high & 0xFFFF;
29326 var a16 = this.low >>> 16;
29327 var a00 = this.low & 0xFFFF;
29328
29329 var b48 = multiplier.high >>> 16;
29330 var b32 = multiplier.high & 0xFFFF;
29331 var b16 = multiplier.low >>> 16;
29332 var b00 = multiplier.low & 0xFFFF;
29333
29334 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
29335 c00 += a00 * b00;
29336 c16 += c00 >>> 16;
29337 c00 &= 0xFFFF;
29338 c16 += a16 * b00;
29339 c32 += c16 >>> 16;
29340 c16 &= 0xFFFF;
29341 c16 += a00 * b16;
29342 c32 += c16 >>> 16;
29343 c16 &= 0xFFFF;
29344 c32 += a32 * b00;
29345 c48 += c32 >>> 16;
29346 c32 &= 0xFFFF;
29347 c32 += a16 * b16;
29348 c48 += c32 >>> 16;
29349 c32 &= 0xFFFF;
29350 c32 += a00 * b32;
29351 c48 += c32 >>> 16;
29352 c32 &= 0xFFFF;
29353 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
29354 c48 &= 0xFFFF;
29355 return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
29356 };
29357
29358 /**
29359 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
29360 * @function
29361 * @param {!Long|number|string} multiplier Multiplier
29362 * @returns {!Long} Product
29363 * @expose
29364 */
29365 Long.prototype.mul = Long.prototype.multiply;
29366
29367 /**
29368 * Returns this Long divided by the specified.
29369 * @param {!Long|number|string} divisor Divisor
29370 * @returns {!Long} Quotient
29371 * @expose
29372 */
29373 Long.prototype.divide = function divide(divisor) {
29374 if (!Long.isLong(divisor))
29375 divisor = Long.fromValue(divisor);
29376 if (divisor.isZero())
29377 throw(new Error('division by zero'));
29378 if (this.isZero())
29379 return this.unsigned ? Long.UZERO : Long.ZERO;
29380 var approx, rem, res;
29381 if (this.equals(Long.MIN_VALUE)) {
29382 if (divisor.equals(Long.ONE) || divisor.equals(Long.NEG_ONE))
29383 return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
29384 else if (divisor.equals(Long.MIN_VALUE))
29385 return Long.ONE;
29386 else {
29387 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
29388 var halfThis = this.shiftRight(1);
29389 approx = halfThis.divide(divisor).shiftLeft(1);
29390 if (approx.equals(Long.ZERO)) {
29391 return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
29392 } else {
29393 rem = this.subtract(divisor.multiply(approx));
29394 res = approx.add(rem.divide(divisor));
29395 return res;
29396 }
29397 }
29398 } else if (divisor.equals(Long.MIN_VALUE))
29399 return this.unsigned ? Long.UZERO : Long.ZERO;
29400 if (this.isNegative()) {
29401 if (divisor.isNegative())
29402 return this.negate().divide(divisor.negate());
29403 return this.negate().divide(divisor).negate();
29404 } else if (divisor.isNegative())
29405 return this.divide(divisor.negate()).negate();
29406
29407 // Repeat the following until the remainder is less than other: find a
29408 // floating-point that approximates remainder / other *from below*, add this
29409 // into the result, and subtract it from the remainder. It is critical that
29410 // the approximate value is less than or equal to the real value so that the
29411 // remainder never becomes negative.
29412 res = Long.ZERO;
29413 rem = this;
29414 while (rem.greaterThanOrEqual(divisor)) {
29415 // Approximate the result of division. This may be a little greater or
29416 // smaller than the actual value.
29417 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
29418
29419 // We will tweak the approximate result by changing it in the 48-th digit or
29420 // the smallest non-fractional digit, whichever is larger.
29421 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
29422 delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48),
29423
29424 // Decrease the approximation until it is smaller than the remainder. Note
29425 // that if it is too large, the product overflows and is negative.
29426 approxRes = Long.fromNumber(approx),
29427 approxRem = approxRes.multiply(divisor);
29428 while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
29429 approx -= delta;
29430 approxRes = Long.fromNumber(approx, this.unsigned);
29431 approxRem = approxRes.multiply(divisor);
29432 }
29433
29434 // We know the answer can't be zero... and actually, zero would cause
29435 // infinite recursion since we would make no progress.
29436 if (approxRes.isZero())
29437 approxRes = Long.ONE;
29438
29439 res = res.add(approxRes);
29440 rem = rem.subtract(approxRem);
29441 }
29442 return res;
29443 };
29444
29445 /**
29446 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
29447 * @function
29448 * @param {!Long|number|string} divisor Divisor
29449 * @returns {!Long} Quotient
29450 * @expose
29451 */
29452 Long.prototype.div = Long.prototype.divide;
29453
29454 /**
29455 * Returns this Long modulo the specified.
29456 * @param {!Long|number|string} divisor Divisor
29457 * @returns {!Long} Remainder
29458 * @expose
29459 */
29460 Long.prototype.modulo = function modulo(divisor) {
29461 if (!Long.isLong(divisor))
29462 divisor = Long.fromValue(divisor);
29463 return this.subtract(this.divide(divisor).multiply(divisor));
29464 };
29465
29466 /**
29467 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
29468 * @function
29469 * @param {!Long|number|string} divisor Divisor
29470 * @returns {!Long} Remainder
29471 * @expose
29472 */
29473 Long.prototype.mod = Long.prototype.modulo;
29474
29475 /**
29476 * Returns the bitwise NOT of this Long.
29477 * @returns {!Long}
29478 * @expose
29479 */
29480 Long.prototype.not = function not() {
29481 return Long.fromBits(~this.low, ~this.high, this.unsigned);
29482 };
29483
29484 /**
29485 * Returns the bitwise AND of this Long and the specified.
29486 * @param {!Long|number|string} other Other Long
29487 * @returns {!Long}
29488 * @expose
29489 */
29490 Long.prototype.and = function and(other) {
29491 if (!Long.isLong(other))
29492 other = Long.fromValue(other);
29493 return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
29494 };
29495
29496 /**
29497 * Returns the bitwise OR of this Long and the specified.
29498 * @param {!Long|number|string} other Other Long
29499 * @returns {!Long}
29500 * @expose
29501 */
29502 Long.prototype.or = function or(other) {
29503 if (!Long.isLong(other))
29504 other = Long.fromValue(other);
29505 return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
29506 };
29507
29508 /**
29509 * Returns the bitwise XOR of this Long and the given one.
29510 * @param {!Long|number|string} other Other Long
29511 * @returns {!Long}
29512 * @expose
29513 */
29514 Long.prototype.xor = function xor(other) {
29515 if (!Long.isLong(other))
29516 other = Long.fromValue(other);
29517 return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
29518 };
29519
29520 /**
29521 * Returns this Long with bits shifted to the left by the given amount.
29522 * @param {number|!Long} numBits Number of bits
29523 * @returns {!Long} Shifted Long
29524 * @expose
29525 */
29526 Long.prototype.shiftLeft = function shiftLeft(numBits) {
29527 if (Long.isLong(numBits))
29528 numBits = numBits.toInt();
29529 if ((numBits &= 63) === 0)
29530 return this;
29531 else if (numBits < 32)
29532 return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
29533 else
29534 return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
29535 };
29536
29537 /**
29538 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
29539 * @function
29540 * @param {number|!Long} numBits Number of bits
29541 * @returns {!Long} Shifted Long
29542 * @expose
29543 */
29544 Long.prototype.shl = Long.prototype.shiftLeft;
29545
29546 /**
29547 * Returns this Long with bits arithmetically shifted to the right by the given amount.
29548 * @param {number|!Long} numBits Number of bits
29549 * @returns {!Long} Shifted Long
29550 * @expose
29551 */
29552 Long.prototype.shiftRight = function shiftRight(numBits) {
29553 if (Long.isLong(numBits))
29554 numBits = numBits.toInt();
29555 if ((numBits &= 63) === 0)
29556 return this;
29557 else if (numBits < 32)
29558 return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
29559 else
29560 return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
29561 };
29562
29563 /**
29564 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
29565 * @function
29566 * @param {number|!Long} numBits Number of bits
29567 * @returns {!Long} Shifted Long
29568 * @expose
29569 */
29570 Long.prototype.shr = Long.prototype.shiftRight;
29571
29572 /**
29573 * Returns this Long with bits logically shifted to the right by the given amount.
29574 * @param {number|!Long} numBits Number of bits
29575 * @returns {!Long} Shifted Long
29576 * @expose
29577 */
29578 Long.prototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
29579 if (Long.isLong(numBits))
29580 numBits = numBits.toInt();
29581 numBits &= 63;
29582 if (numBits === 0)
29583 return this;
29584 else {
29585 var high = this.high;
29586 if (numBits < 32) {
29587 var low = this.low;
29588 return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
29589 } else if (numBits === 32)
29590 return Long.fromBits(high, 0, this.unsigned);
29591 else
29592 return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
29593 }
29594 };
29595
29596 /**
29597 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
29598 * @function
29599 * @param {number|!Long} numBits Number of bits
29600 * @returns {!Long} Shifted Long
29601 * @expose
29602 */
29603 Long.prototype.shru = Long.prototype.shiftRightUnsigned;
29604
29605 /**
29606 * Converts this Long to signed.
29607 * @returns {!Long} Signed long
29608 * @expose
29609 */
29610 Long.prototype.toSigned = function toSigned() {
29611 if (!this.unsigned)
29612 return this;
29613 return new Long(this.low, this.high, false);
29614 };
29615
29616 /**
29617 * Converts this Long to unsigned.
29618 * @returns {!Long} Unsigned long
29619 * @expose
29620 */
29621 Long.prototype.toUnsigned = function toUnsigned() {
29622 if (this.unsigned)
29623 return this;
29624 return new Long(this.low, this.high, true);
29625 };
29626
29627 return Long;
29628});
29629
29630},{}],354:[function(require,module,exports){
29631'use strict'
29632var inherits = require('inherits')
29633var HashBase = require('hash-base')
29634var Buffer = require('safe-buffer').Buffer
29635
29636var ARRAY16 = new Array(16)
29637
29638function MD5 () {
29639 HashBase.call(this, 64)
29640
29641 // state
29642 this._a = 0x67452301
29643 this._b = 0xefcdab89
29644 this._c = 0x98badcfe
29645 this._d = 0x10325476
29646}
29647
29648inherits(MD5, HashBase)
29649
29650MD5.prototype._update = function () {
29651 var M = ARRAY16
29652 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
29653
29654 var a = this._a
29655 var b = this._b
29656 var c = this._c
29657 var d = this._d
29658
29659 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
29660 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
29661 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
29662 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
29663 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
29664 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
29665 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
29666 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
29667 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
29668 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
29669 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
29670 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
29671 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
29672 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
29673 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
29674 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
29675
29676 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
29677 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
29678 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
29679 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
29680 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
29681 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
29682 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
29683 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
29684 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
29685 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
29686 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
29687 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
29688 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
29689 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
29690 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
29691 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
29692
29693 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
29694 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
29695 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
29696 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
29697 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
29698 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
29699 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
29700 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
29701 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
29702 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
29703 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
29704 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
29705 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
29706 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
29707 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
29708 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
29709
29710 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
29711 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
29712 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
29713 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
29714 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
29715 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
29716 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
29717 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
29718 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
29719 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
29720 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
29721 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
29722 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
29723 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
29724 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
29725 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
29726
29727 this._a = (this._a + a) | 0
29728 this._b = (this._b + b) | 0
29729 this._c = (this._c + c) | 0
29730 this._d = (this._d + d) | 0
29731}
29732
29733MD5.prototype._digest = function () {
29734 // create padding and handle blocks
29735 this._block[this._blockOffset++] = 0x80
29736 if (this._blockOffset > 56) {
29737 this._block.fill(0, this._blockOffset, 64)
29738 this._update()
29739 this._blockOffset = 0
29740 }
29741
29742 this._block.fill(0, this._blockOffset, 56)
29743 this._block.writeUInt32LE(this._length[0], 56)
29744 this._block.writeUInt32LE(this._length[1], 60)
29745 this._update()
29746
29747 // produce result
29748 var buffer = Buffer.allocUnsafe(16)
29749 buffer.writeInt32LE(this._a, 0)
29750 buffer.writeInt32LE(this._b, 4)
29751 buffer.writeInt32LE(this._c, 8)
29752 buffer.writeInt32LE(this._d, 12)
29753 return buffer
29754}
29755
29756function rotl (x, n) {
29757 return (x << n) | (x >>> (32 - n))
29758}
29759
29760function fnF (a, b, c, d, m, k, s) {
29761 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
29762}
29763
29764function fnG (a, b, c, d, m, k, s) {
29765 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
29766}
29767
29768function fnH (a, b, c, d, m, k, s) {
29769 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
29770}
29771
29772function fnI (a, b, c, d, m, k, s) {
29773 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
29774}
29775
29776module.exports = MD5
29777
29778},{"hash-base":101,"inherits":116,"safe-buffer":393}],355:[function(require,module,exports){
29779var bn = require('bn.js');
29780var brorand = require('brorand');
29781
29782function MillerRabin(rand) {
29783 this.rand = rand || new brorand.Rand();
29784}
29785module.exports = MillerRabin;
29786
29787MillerRabin.create = function create(rand) {
29788 return new MillerRabin(rand);
29789};
29790
29791MillerRabin.prototype._randbelow = function _randbelow(n) {
29792 var len = n.bitLength();
29793 var min_bytes = Math.ceil(len / 8);
29794
29795 // Generage random bytes until a number less than n is found.
29796 // This ensures that 0..n-1 have an equal probability of being selected.
29797 do
29798 var a = new bn(this.rand.generate(min_bytes));
29799 while (a.cmp(n) >= 0);
29800
29801 return a;
29802};
29803
29804MillerRabin.prototype._randrange = function _randrange(start, stop) {
29805 // Generate a random number greater than or equal to start and less than stop.
29806 var size = stop.sub(start);
29807 return start.add(this._randbelow(size));
29808};
29809
29810MillerRabin.prototype.test = function test(n, k, cb) {
29811 var len = n.bitLength();
29812 var red = bn.mont(n);
29813 var rone = new bn(1).toRed(red);
29814
29815 if (!k)
29816 k = Math.max(1, (len / 48) | 0);
29817
29818 // Find d and s, (n - 1) = (2 ^ s) * d;
29819 var n1 = n.subn(1);
29820 for (var s = 0; !n1.testn(s); s++) {}
29821 var d = n.shrn(s);
29822
29823 var rn1 = n1.toRed(red);
29824
29825 var prime = true;
29826 for (; k > 0; k--) {
29827 var a = this._randrange(new bn(2), n1);
29828 if (cb)
29829 cb(a);
29830
29831 var x = a.toRed(red).redPow(d);
29832 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
29833 continue;
29834
29835 for (var i = 1; i < s; i++) {
29836 x = x.redSqr();
29837
29838 if (x.cmp(rone) === 0)
29839 return false;
29840 if (x.cmp(rn1) === 0)
29841 break;
29842 }
29843
29844 if (i === s)
29845 return false;
29846 }
29847
29848 return prime;
29849};
29850
29851MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
29852 var len = n.bitLength();
29853 var red = bn.mont(n);
29854 var rone = new bn(1).toRed(red);
29855
29856 if (!k)
29857 k = Math.max(1, (len / 48) | 0);
29858
29859 // Find d and s, (n - 1) = (2 ^ s) * d;
29860 var n1 = n.subn(1);
29861 for (var s = 0; !n1.testn(s); s++) {}
29862 var d = n.shrn(s);
29863
29864 var rn1 = n1.toRed(red);
29865
29866 for (; k > 0; k--) {
29867 var a = this._randrange(new bn(2), n1);
29868
29869 var g = n.gcd(a);
29870 if (g.cmpn(1) !== 0)
29871 return g;
29872
29873 var x = a.toRed(red).redPow(d);
29874 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
29875 continue;
29876
29877 for (var i = 1; i < s; i++) {
29878 x = x.redSqr();
29879
29880 if (x.cmp(rone) === 0)
29881 return x.fromRed().subn(1).gcd(n);
29882 if (x.cmp(rn1) === 0)
29883 break;
29884 }
29885
29886 if (i === s) {
29887 x = x.redSqr();
29888 return x.fromRed().subn(1).gcd(n);
29889 }
29890 }
29891
29892 return false;
29893};
29894
29895},{"bn.js":18,"brorand":19}],356:[function(require,module,exports){
29896module.exports = assert;
29897
29898function assert(val, msg) {
29899 if (!val)
29900 throw new Error(msg || 'Assertion failed');
29901}
29902
29903assert.equal = function assertEqual(l, r, msg) {
29904 if (l != r)
29905 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
29906};
29907
29908},{}],357:[function(require,module,exports){
29909'use strict';
29910
29911var utils = exports;
29912
29913function toArray(msg, enc) {
29914 if (Array.isArray(msg))
29915 return msg.slice();
29916 if (!msg)
29917 return [];
29918 var res = [];
29919 if (typeof msg !== 'string') {
29920 for (var i = 0; i < msg.length; i++)
29921 res[i] = msg[i] | 0;
29922 return res;
29923 }
29924 if (enc === 'hex') {
29925 msg = msg.replace(/[^a-z0-9]+/ig, '');
29926 if (msg.length % 2 !== 0)
29927 msg = '0' + msg;
29928 for (var i = 0; i < msg.length; i += 2)
29929 res.push(parseInt(msg[i] + msg[i + 1], 16));
29930 } else {
29931 for (var i = 0; i < msg.length; i++) {
29932 var c = msg.charCodeAt(i);
29933 var hi = c >> 8;
29934 var lo = c & 0xff;
29935 if (hi)
29936 res.push(hi, lo);
29937 else
29938 res.push(lo);
29939 }
29940 }
29941 return res;
29942}
29943utils.toArray = toArray;
29944
29945function zero2(word) {
29946 if (word.length === 1)
29947 return '0' + word;
29948 else
29949 return word;
29950}
29951utils.zero2 = zero2;
29952
29953function toHex(msg) {
29954 var res = '';
29955 for (var i = 0; i < msg.length; i++)
29956 res += zero2(msg[i].toString(16));
29957 return res;
29958}
29959utils.toHex = toHex;
29960
29961utils.encode = function encode(arr, enc) {
29962 if (enc === 'hex')
29963 return toHex(arr);
29964 else
29965 return arr;
29966};
29967
29968},{}],358:[function(require,module,exports){
29969module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
29970"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
29971"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
29972"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
29973"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
29974"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
29975"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
29976"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
29977"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
29978"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
29979"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
29980"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
29981}
29982},{}],359:[function(require,module,exports){
29983// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
29984// Fedor, you are amazing.
29985'use strict'
29986
29987var asn1 = require('asn1.js')
29988
29989exports.certificate = require('./certificate')
29990
29991var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
29992 this.seq().obj(
29993 this.key('version').int(),
29994 this.key('modulus').int(),
29995 this.key('publicExponent').int(),
29996 this.key('privateExponent').int(),
29997 this.key('prime1').int(),
29998 this.key('prime2').int(),
29999 this.key('exponent1').int(),
30000 this.key('exponent2').int(),
30001 this.key('coefficient').int()
30002 )
30003})
30004exports.RSAPrivateKey = RSAPrivateKey
30005
30006var RSAPublicKey = asn1.define('RSAPublicKey', function () {
30007 this.seq().obj(
30008 this.key('modulus').int(),
30009 this.key('publicExponent').int()
30010 )
30011})
30012exports.RSAPublicKey = RSAPublicKey
30013
30014var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
30015 this.seq().obj(
30016 this.key('algorithm').use(AlgorithmIdentifier),
30017 this.key('subjectPublicKey').bitstr()
30018 )
30019})
30020exports.PublicKey = PublicKey
30021
30022var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
30023 this.seq().obj(
30024 this.key('algorithm').objid(),
30025 this.key('none').null_().optional(),
30026 this.key('curve').objid().optional(),
30027 this.key('params').seq().obj(
30028 this.key('p').int(),
30029 this.key('q').int(),
30030 this.key('g').int()
30031 ).optional()
30032 )
30033})
30034
30035var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
30036 this.seq().obj(
30037 this.key('version').int(),
30038 this.key('algorithm').use(AlgorithmIdentifier),
30039 this.key('subjectPrivateKey').octstr()
30040 )
30041})
30042exports.PrivateKey = PrivateKeyInfo
30043var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
30044 this.seq().obj(
30045 this.key('algorithm').seq().obj(
30046 this.key('id').objid(),
30047 this.key('decrypt').seq().obj(
30048 this.key('kde').seq().obj(
30049 this.key('id').objid(),
30050 this.key('kdeparams').seq().obj(
30051 this.key('salt').octstr(),
30052 this.key('iters').int()
30053 )
30054 ),
30055 this.key('cipher').seq().obj(
30056 this.key('algo').objid(),
30057 this.key('iv').octstr()
30058 )
30059 )
30060 ),
30061 this.key('subjectPrivateKey').octstr()
30062 )
30063})
30064
30065exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
30066
30067var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
30068 this.seq().obj(
30069 this.key('version').int(),
30070 this.key('p').int(),
30071 this.key('q').int(),
30072 this.key('g').int(),
30073 this.key('pub_key').int(),
30074 this.key('priv_key').int()
30075 )
30076})
30077exports.DSAPrivateKey = DSAPrivateKey
30078
30079exports.DSAparam = asn1.define('DSAparam', function () {
30080 this.int()
30081})
30082
30083var ECPrivateKey = asn1.define('ECPrivateKey', function () {
30084 this.seq().obj(
30085 this.key('version').int(),
30086 this.key('privateKey').octstr(),
30087 this.key('parameters').optional().explicit(0).use(ECParameters),
30088 this.key('publicKey').optional().explicit(1).bitstr()
30089 )
30090})
30091exports.ECPrivateKey = ECPrivateKey
30092
30093var ECParameters = asn1.define('ECParameters', function () {
30094 this.choice({
30095 namedCurve: this.objid()
30096 })
30097})
30098
30099exports.signature = asn1.define('signature', function () {
30100 this.seq().obj(
30101 this.key('r').int(),
30102 this.key('s').int()
30103 )
30104})
30105
30106},{"./certificate":360,"asn1.js":1}],360:[function(require,module,exports){
30107// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
30108// thanks to @Rantanen
30109
30110'use strict'
30111
30112var asn = require('asn1.js')
30113
30114var Time = asn.define('Time', function () {
30115 this.choice({
30116 utcTime: this.utctime(),
30117 generalTime: this.gentime()
30118 })
30119})
30120
30121var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
30122 this.seq().obj(
30123 this.key('type').objid(),
30124 this.key('value').any()
30125 )
30126})
30127
30128var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
30129 this.seq().obj(
30130 this.key('algorithm').objid(),
30131 this.key('parameters').optional()
30132 )
30133})
30134
30135var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
30136 this.seq().obj(
30137 this.key('algorithm').use(AlgorithmIdentifier),
30138 this.key('subjectPublicKey').bitstr()
30139 )
30140})
30141
30142var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
30143 this.setof(AttributeTypeValue)
30144})
30145
30146var RDNSequence = asn.define('RDNSequence', function () {
30147 this.seqof(RelativeDistinguishedName)
30148})
30149
30150var Name = asn.define('Name', function () {
30151 this.choice({
30152 rdnSequence: this.use(RDNSequence)
30153 })
30154})
30155
30156var Validity = asn.define('Validity', function () {
30157 this.seq().obj(
30158 this.key('notBefore').use(Time),
30159 this.key('notAfter').use(Time)
30160 )
30161})
30162
30163var Extension = asn.define('Extension', function () {
30164 this.seq().obj(
30165 this.key('extnID').objid(),
30166 this.key('critical').bool().def(false),
30167 this.key('extnValue').octstr()
30168 )
30169})
30170
30171var TBSCertificate = asn.define('TBSCertificate', function () {
30172 this.seq().obj(
30173 this.key('version').explicit(0).int(),
30174 this.key('serialNumber').int(),
30175 this.key('signature').use(AlgorithmIdentifier),
30176 this.key('issuer').use(Name),
30177 this.key('validity').use(Validity),
30178 this.key('subject').use(Name),
30179 this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
30180 this.key('issuerUniqueID').implicit(1).bitstr().optional(),
30181 this.key('subjectUniqueID').implicit(2).bitstr().optional(),
30182 this.key('extensions').explicit(3).seqof(Extension).optional()
30183 )
30184})
30185
30186var X509Certificate = asn.define('X509Certificate', function () {
30187 this.seq().obj(
30188 this.key('tbsCertificate').use(TBSCertificate),
30189 this.key('signatureAlgorithm').use(AlgorithmIdentifier),
30190 this.key('signatureValue').bitstr()
30191 )
30192})
30193
30194module.exports = X509Certificate
30195
30196},{"asn1.js":1}],361:[function(require,module,exports){
30197(function (Buffer){
30198// adapted from https://github.com/apatil/pemstrip
30199var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r\+\/\=]+)[\n\r]+/m
30200var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----/m
30201var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----([0-9A-z\n\r\+\/\=]+)-----END \1-----$/m
30202var evp = require('evp_bytestokey')
30203var ciphers = require('browserify-aes')
30204module.exports = function (okey, password) {
30205 var key = okey.toString()
30206 var match = key.match(findProc)
30207 var decrypted
30208 if (!match) {
30209 var match2 = key.match(fullRegex)
30210 decrypted = new Buffer(match2[2].replace(/[\r\n]/g, ''), 'base64')
30211 } else {
30212 var suite = 'aes' + match[1]
30213 var iv = new Buffer(match[2], 'hex')
30214 var cipherText = new Buffer(match[3].replace(/[\r\n]/g, ''), 'base64')
30215 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
30216 var out = []
30217 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
30218 out.push(cipher.update(cipherText))
30219 out.push(cipher.final())
30220 decrypted = Buffer.concat(out)
30221 }
30222 var tag = key.match(startRegex)[1]
30223 return {
30224 tag: tag,
30225 data: decrypted
30226 }
30227}
30228
30229}).call(this,require("buffer").Buffer)
30230},{"browserify-aes":23,"buffer":49,"evp_bytestokey":100}],362:[function(require,module,exports){
30231(function (Buffer){
30232var asn1 = require('./asn1')
30233var aesid = require('./aesid.json')
30234var fixProc = require('./fixProc')
30235var ciphers = require('browserify-aes')
30236var compat = require('pbkdf2')
30237module.exports = parseKeys
30238
30239function parseKeys (buffer) {
30240 var password
30241 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
30242 password = buffer.passphrase
30243 buffer = buffer.key
30244 }
30245 if (typeof buffer === 'string') {
30246 buffer = new Buffer(buffer)
30247 }
30248
30249 var stripped = fixProc(buffer, password)
30250
30251 var type = stripped.tag
30252 var data = stripped.data
30253 var subtype, ndata
30254 switch (type) {
30255 case 'CERTIFICATE':
30256 ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
30257 // falls through
30258 case 'PUBLIC KEY':
30259 if (!ndata) {
30260 ndata = asn1.PublicKey.decode(data, 'der')
30261 }
30262 subtype = ndata.algorithm.algorithm.join('.')
30263 switch (subtype) {
30264 case '1.2.840.113549.1.1.1':
30265 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
30266 case '1.2.840.10045.2.1':
30267 ndata.subjectPrivateKey = ndata.subjectPublicKey
30268 return {
30269 type: 'ec',
30270 data: ndata
30271 }
30272 case '1.2.840.10040.4.1':
30273 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
30274 return {
30275 type: 'dsa',
30276 data: ndata.algorithm.params
30277 }
30278 default: throw new Error('unknown key id ' + subtype)
30279 }
30280 throw new Error('unknown key type ' + type)
30281 case 'ENCRYPTED PRIVATE KEY':
30282 data = asn1.EncryptedPrivateKey.decode(data, 'der')
30283 data = decrypt(data, password)
30284 // falls through
30285 case 'PRIVATE KEY':
30286 ndata = asn1.PrivateKey.decode(data, 'der')
30287 subtype = ndata.algorithm.algorithm.join('.')
30288 switch (subtype) {
30289 case '1.2.840.113549.1.1.1':
30290 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
30291 case '1.2.840.10045.2.1':
30292 return {
30293 curve: ndata.algorithm.curve,
30294 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
30295 }
30296 case '1.2.840.10040.4.1':
30297 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
30298 return {
30299 type: 'dsa',
30300 params: ndata.algorithm.params
30301 }
30302 default: throw new Error('unknown key id ' + subtype)
30303 }
30304 throw new Error('unknown key type ' + type)
30305 case 'RSA PUBLIC KEY':
30306 return asn1.RSAPublicKey.decode(data, 'der')
30307 case 'RSA PRIVATE KEY':
30308 return asn1.RSAPrivateKey.decode(data, 'der')
30309 case 'DSA PRIVATE KEY':
30310 return {
30311 type: 'dsa',
30312 params: asn1.DSAPrivateKey.decode(data, 'der')
30313 }
30314 case 'EC PRIVATE KEY':
30315 data = asn1.ECPrivateKey.decode(data, 'der')
30316 return {
30317 curve: data.parameters.value,
30318 privateKey: data.privateKey
30319 }
30320 default: throw new Error('unknown key type ' + type)
30321 }
30322}
30323parseKeys.signature = asn1.signature
30324function decrypt (data, password) {
30325 var salt = data.algorithm.decrypt.kde.kdeparams.salt
30326 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
30327 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
30328 var iv = data.algorithm.decrypt.cipher.iv
30329 var cipherText = data.subjectPrivateKey
30330 var keylen = parseInt(algo.split('-')[1], 10) / 8
30331 var key = compat.pbkdf2Sync(password, salt, iters, keylen)
30332 var cipher = ciphers.createDecipheriv(algo, key, iv)
30333 var out = []
30334 out.push(cipher.update(cipherText))
30335 out.push(cipher.final())
30336 return Buffer.concat(out)
30337}
30338
30339}).call(this,require("buffer").Buffer)
30340},{"./aesid.json":358,"./asn1":359,"./fixProc":361,"browserify-aes":23,"buffer":49,"pbkdf2":363}],363:[function(require,module,exports){
30341exports.pbkdf2 = require('./lib/async')
30342exports.pbkdf2Sync = require('./lib/sync')
30343
30344},{"./lib/async":364,"./lib/sync":367}],364:[function(require,module,exports){
30345(function (process,global){
30346var checkParameters = require('./precondition')
30347var defaultEncoding = require('./default-encoding')
30348var sync = require('./sync')
30349var Buffer = require('safe-buffer').Buffer
30350
30351var ZERO_BUF
30352var subtle = global.crypto && global.crypto.subtle
30353var toBrowser = {
30354 'sha': 'SHA-1',
30355 'sha-1': 'SHA-1',
30356 'sha1': 'SHA-1',
30357 'sha256': 'SHA-256',
30358 'sha-256': 'SHA-256',
30359 'sha384': 'SHA-384',
30360 'sha-384': 'SHA-384',
30361 'sha-512': 'SHA-512',
30362 'sha512': 'SHA-512'
30363}
30364var checks = []
30365function checkNative (algo) {
30366 if (global.process && !global.process.browser) {
30367 return Promise.resolve(false)
30368 }
30369 if (!subtle || !subtle.importKey || !subtle.deriveBits) {
30370 return Promise.resolve(false)
30371 }
30372 if (checks[algo] !== undefined) {
30373 return checks[algo]
30374 }
30375 ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
30376 var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
30377 .then(function () {
30378 return true
30379 }).catch(function () {
30380 return false
30381 })
30382 checks[algo] = prom
30383 return prom
30384}
30385
30386function browserPbkdf2 (password, salt, iterations, length, algo) {
30387 return subtle.importKey(
30388 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits']
30389 ).then(function (key) {
30390 return subtle.deriveBits({
30391 name: 'PBKDF2',
30392 salt: salt,
30393 iterations: iterations,
30394 hash: {
30395 name: algo
30396 }
30397 }, key, length << 3)
30398 }).then(function (res) {
30399 return Buffer.from(res)
30400 })
30401}
30402
30403function resolvePromise (promise, callback) {
30404 promise.then(function (out) {
30405 process.nextTick(function () {
30406 callback(null, out)
30407 })
30408 }, function (e) {
30409 process.nextTick(function () {
30410 callback(e)
30411 })
30412 })
30413}
30414module.exports = function (password, salt, iterations, keylen, digest, callback) {
30415 if (typeof digest === 'function') {
30416 callback = digest
30417 digest = undefined
30418 }
30419
30420 digest = digest || 'sha1'
30421 var algo = toBrowser[digest.toLowerCase()]
30422
30423 if (!algo || typeof global.Promise !== 'function') {
30424 return process.nextTick(function () {
30425 var out
30426 try {
30427 out = sync(password, salt, iterations, keylen, digest)
30428 } catch (e) {
30429 return callback(e)
30430 }
30431 callback(null, out)
30432 })
30433 }
30434
30435 checkParameters(password, salt, iterations, keylen)
30436 if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
30437 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
30438 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
30439
30440 resolvePromise(checkNative(algo).then(function (resp) {
30441 if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)
30442
30443 return sync(password, salt, iterations, keylen, digest)
30444 }), callback)
30445}
30446
30447}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
30448},{"./default-encoding":365,"./precondition":366,"./sync":367,"_process":369,"safe-buffer":393}],365:[function(require,module,exports){
30449(function (process){
30450var defaultEncoding
30451/* istanbul ignore next */
30452if (process.browser) {
30453 defaultEncoding = 'utf-8'
30454} else {
30455 var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
30456
30457 defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
30458}
30459module.exports = defaultEncoding
30460
30461}).call(this,require('_process'))
30462},{"_process":369}],366:[function(require,module,exports){
30463(function (Buffer){
30464var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
30465
30466function checkBuffer (buf, name) {
30467 if (typeof buf !== 'string' && !Buffer.isBuffer(buf)) {
30468 throw new TypeError(name + ' must be a buffer or string')
30469 }
30470}
30471
30472module.exports = function (password, salt, iterations, keylen) {
30473 checkBuffer(password, 'Password')
30474 checkBuffer(salt, 'Salt')
30475
30476 if (typeof iterations !== 'number') {
30477 throw new TypeError('Iterations not a number')
30478 }
30479
30480 if (iterations < 0) {
30481 throw new TypeError('Bad iterations')
30482 }
30483
30484 if (typeof keylen !== 'number') {
30485 throw new TypeError('Key length not a number')
30486 }
30487
30488 if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
30489 throw new TypeError('Bad key length')
30490 }
30491}
30492
30493}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
30494},{"../../is-buffer/index.js":117}],367:[function(require,module,exports){
30495var md5 = require('create-hash/md5')
30496var RIPEMD160 = require('ripemd160')
30497var sha = require('sha.js')
30498
30499var checkParameters = require('./precondition')
30500var defaultEncoding = require('./default-encoding')
30501var Buffer = require('safe-buffer').Buffer
30502var ZEROS = Buffer.alloc(128)
30503var sizes = {
30504 md5: 16,
30505 sha1: 20,
30506 sha224: 28,
30507 sha256: 32,
30508 sha384: 48,
30509 sha512: 64,
30510 rmd160: 20,
30511 ripemd160: 20
30512}
30513
30514function Hmac (alg, key, saltLen) {
30515 var hash = getDigest(alg)
30516 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
30517
30518 if (key.length > blocksize) {
30519 key = hash(key)
30520 } else if (key.length < blocksize) {
30521 key = Buffer.concat([key, ZEROS], blocksize)
30522 }
30523
30524 var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
30525 var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
30526 for (var i = 0; i < blocksize; i++) {
30527 ipad[i] = key[i] ^ 0x36
30528 opad[i] = key[i] ^ 0x5C
30529 }
30530
30531 var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
30532 ipad.copy(ipad1, 0, 0, blocksize)
30533 this.ipad1 = ipad1
30534 this.ipad2 = ipad
30535 this.opad = opad
30536 this.alg = alg
30537 this.blocksize = blocksize
30538 this.hash = hash
30539 this.size = sizes[alg]
30540}
30541
30542Hmac.prototype.run = function (data, ipad) {
30543 data.copy(ipad, this.blocksize)
30544 var h = this.hash(ipad)
30545 h.copy(this.opad, this.blocksize)
30546 return this.hash(this.opad)
30547}
30548
30549function getDigest (alg) {
30550 function shaFunc (data) {
30551 return sha(alg).update(data).digest()
30552 }
30553 function rmd160Func (data) {
30554 return new RIPEMD160().update(data).digest()
30555 }
30556
30557 if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
30558 if (alg === 'md5') return md5
30559 return shaFunc
30560}
30561
30562function pbkdf2 (password, salt, iterations, keylen, digest) {
30563 checkParameters(password, salt, iterations, keylen)
30564
30565 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
30566 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
30567
30568 digest = digest || 'sha1'
30569
30570 var hmac = new Hmac(digest, password, salt.length)
30571
30572 var DK = Buffer.allocUnsafe(keylen)
30573 var block1 = Buffer.allocUnsafe(salt.length + 4)
30574 salt.copy(block1, 0, 0, salt.length)
30575
30576 var destPos = 0
30577 var hLen = sizes[digest]
30578 var l = Math.ceil(keylen / hLen)
30579
30580 for (var i = 1; i <= l; i++) {
30581 block1.writeUInt32BE(i, salt.length)
30582
30583 var T = hmac.run(block1, hmac.ipad1)
30584 var U = T
30585
30586 for (var j = 1; j < iterations; j++) {
30587 U = hmac.run(U, hmac.ipad2)
30588 for (var k = 0; k < hLen; k++) T[k] ^= U[k]
30589 }
30590
30591 T.copy(DK, destPos)
30592 destPos += hLen
30593 }
30594
30595 return DK
30596}
30597
30598module.exports = pbkdf2
30599
30600},{"./default-encoding":365,"./precondition":366,"create-hash/md5":68,"ripemd160":392,"safe-buffer":393,"sha.js":395}],368:[function(require,module,exports){
30601(function (process){
30602'use strict';
30603
30604if (!process.version ||
30605 process.version.indexOf('v0.') === 0 ||
30606 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
30607 module.exports = { nextTick: nextTick };
30608} else {
30609 module.exports = process
30610}
30611
30612function nextTick(fn, arg1, arg2, arg3) {
30613 if (typeof fn !== 'function') {
30614 throw new TypeError('"callback" argument must be a function');
30615 }
30616 var len = arguments.length;
30617 var args, i;
30618 switch (len) {
30619 case 0:
30620 case 1:
30621 return process.nextTick(fn);
30622 case 2:
30623 return process.nextTick(function afterTickOne() {
30624 fn.call(null, arg1);
30625 });
30626 case 3:
30627 return process.nextTick(function afterTickTwo() {
30628 fn.call(null, arg1, arg2);
30629 });
30630 case 4:
30631 return process.nextTick(function afterTickThree() {
30632 fn.call(null, arg1, arg2, arg3);
30633 });
30634 default:
30635 args = new Array(len - 1);
30636 i = 0;
30637 while (i < args.length) {
30638 args[i++] = arguments[i];
30639 }
30640 return process.nextTick(function afterTick() {
30641 fn.apply(null, args);
30642 });
30643 }
30644}
30645
30646
30647}).call(this,require('_process'))
30648},{"_process":369}],369:[function(require,module,exports){
30649// shim for using process in browser
30650var process = module.exports = {};
30651
30652// cached from whatever global is present so that test runners that stub it
30653// don't break things. But we need to wrap it in a try catch in case it is
30654// wrapped in strict mode code which doesn't define any globals. It's inside a
30655// function because try/catches deoptimize in certain engines.
30656
30657var cachedSetTimeout;
30658var cachedClearTimeout;
30659
30660function defaultSetTimout() {
30661 throw new Error('setTimeout has not been defined');
30662}
30663function defaultClearTimeout () {
30664 throw new Error('clearTimeout has not been defined');
30665}
30666(function () {
30667 try {
30668 if (typeof setTimeout === 'function') {
30669 cachedSetTimeout = setTimeout;
30670 } else {
30671 cachedSetTimeout = defaultSetTimout;
30672 }
30673 } catch (e) {
30674 cachedSetTimeout = defaultSetTimout;
30675 }
30676 try {
30677 if (typeof clearTimeout === 'function') {
30678 cachedClearTimeout = clearTimeout;
30679 } else {
30680 cachedClearTimeout = defaultClearTimeout;
30681 }
30682 } catch (e) {
30683 cachedClearTimeout = defaultClearTimeout;
30684 }
30685} ())
30686function runTimeout(fun) {
30687 if (cachedSetTimeout === setTimeout) {
30688 //normal enviroments in sane situations
30689 return setTimeout(fun, 0);
30690 }
30691 // if setTimeout wasn't available but was latter defined
30692 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
30693 cachedSetTimeout = setTimeout;
30694 return setTimeout(fun, 0);
30695 }
30696 try {
30697 // when when somebody has screwed with setTimeout but no I.E. maddness
30698 return cachedSetTimeout(fun, 0);
30699 } catch(e){
30700 try {
30701 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
30702 return cachedSetTimeout.call(null, fun, 0);
30703 } catch(e){
30704 // 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
30705 return cachedSetTimeout.call(this, fun, 0);
30706 }
30707 }
30708
30709
30710}
30711function runClearTimeout(marker) {
30712 if (cachedClearTimeout === clearTimeout) {
30713 //normal enviroments in sane situations
30714 return clearTimeout(marker);
30715 }
30716 // if clearTimeout wasn't available but was latter defined
30717 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
30718 cachedClearTimeout = clearTimeout;
30719 return clearTimeout(marker);
30720 }
30721 try {
30722 // when when somebody has screwed with setTimeout but no I.E. maddness
30723 return cachedClearTimeout(marker);
30724 } catch (e){
30725 try {
30726 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
30727 return cachedClearTimeout.call(null, marker);
30728 } catch (e){
30729 // 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.
30730 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
30731 return cachedClearTimeout.call(this, marker);
30732 }
30733 }
30734
30735
30736
30737}
30738var queue = [];
30739var draining = false;
30740var currentQueue;
30741var queueIndex = -1;
30742
30743function cleanUpNextTick() {
30744 if (!draining || !currentQueue) {
30745 return;
30746 }
30747 draining = false;
30748 if (currentQueue.length) {
30749 queue = currentQueue.concat(queue);
30750 } else {
30751 queueIndex = -1;
30752 }
30753 if (queue.length) {
30754 drainQueue();
30755 }
30756}
30757
30758function drainQueue() {
30759 if (draining) {
30760 return;
30761 }
30762 var timeout = runTimeout(cleanUpNextTick);
30763 draining = true;
30764
30765 var len = queue.length;
30766 while(len) {
30767 currentQueue = queue;
30768 queue = [];
30769 while (++queueIndex < len) {
30770 if (currentQueue) {
30771 currentQueue[queueIndex].run();
30772 }
30773 }
30774 queueIndex = -1;
30775 len = queue.length;
30776 }
30777 currentQueue = null;
30778 draining = false;
30779 runClearTimeout(timeout);
30780}
30781
30782process.nextTick = function (fun) {
30783 var args = new Array(arguments.length - 1);
30784 if (arguments.length > 1) {
30785 for (var i = 1; i < arguments.length; i++) {
30786 args[i - 1] = arguments[i];
30787 }
30788 }
30789 queue.push(new Item(fun, args));
30790 if (queue.length === 1 && !draining) {
30791 runTimeout(drainQueue);
30792 }
30793};
30794
30795// v8 likes predictible objects
30796function Item(fun, array) {
30797 this.fun = fun;
30798 this.array = array;
30799}
30800Item.prototype.run = function () {
30801 this.fun.apply(null, this.array);
30802};
30803process.title = 'browser';
30804process.browser = true;
30805process.env = {};
30806process.argv = [];
30807process.version = ''; // empty string to avoid regexp issues
30808process.versions = {};
30809
30810function noop() {}
30811
30812process.on = noop;
30813process.addListener = noop;
30814process.once = noop;
30815process.off = noop;
30816process.removeListener = noop;
30817process.removeAllListeners = noop;
30818process.emit = noop;
30819process.prependListener = noop;
30820process.prependOnceListener = noop;
30821
30822process.listeners = function (name) { return [] }
30823
30824process.binding = function (name) {
30825 throw new Error('process.binding is not supported');
30826};
30827
30828process.cwd = function () { return '/' };
30829process.chdir = function (dir) {
30830 throw new Error('process.chdir is not supported');
30831};
30832process.umask = function() { return 0; };
30833
30834},{}],370:[function(require,module,exports){
30835exports.publicEncrypt = require('./publicEncrypt')
30836exports.privateDecrypt = require('./privateDecrypt')
30837
30838exports.privateEncrypt = function privateEncrypt (key, buf) {
30839 return exports.publicEncrypt(key, buf, true)
30840}
30841
30842exports.publicDecrypt = function publicDecrypt (key, buf) {
30843 return exports.privateDecrypt(key, buf, true)
30844}
30845
30846},{"./privateDecrypt":372,"./publicEncrypt":373}],371:[function(require,module,exports){
30847var createHash = require('create-hash')
30848var Buffer = require('safe-buffer').Buffer
30849
30850module.exports = function (seed, len) {
30851 var t = Buffer.alloc(0)
30852 var i = 0
30853 var c
30854 while (t.length < len) {
30855 c = i2ops(i++)
30856 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
30857 }
30858 return t.slice(0, len)
30859}
30860
30861function i2ops (c) {
30862 var out = Buffer.allocUnsafe(4)
30863 out.writeUInt32BE(c, 0)
30864 return out
30865}
30866
30867},{"create-hash":67,"safe-buffer":393}],372:[function(require,module,exports){
30868var parseKeys = require('parse-asn1')
30869var mgf = require('./mgf')
30870var xor = require('./xor')
30871var BN = require('bn.js')
30872var crt = require('browserify-rsa')
30873var createHash = require('create-hash')
30874var withPublic = require('./withPublic')
30875var Buffer = require('safe-buffer').Buffer
30876
30877module.exports = function privateDecrypt (privateKey, enc, reverse) {
30878 var padding
30879 if (privateKey.padding) {
30880 padding = privateKey.padding
30881 } else if (reverse) {
30882 padding = 1
30883 } else {
30884 padding = 4
30885 }
30886
30887 var key = parseKeys(privateKey)
30888 var k = key.modulus.byteLength()
30889 if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
30890 throw new Error('decryption error')
30891 }
30892 var msg
30893 if (reverse) {
30894 msg = withPublic(new BN(enc), key)
30895 } else {
30896 msg = crt(enc, key)
30897 }
30898 var zBuffer = Buffer.alloc(k - msg.length)
30899 msg = Buffer.concat([zBuffer, msg], k)
30900 if (padding === 4) {
30901 return oaep(key, msg)
30902 } else if (padding === 1) {
30903 return pkcs1(key, msg, reverse)
30904 } else if (padding === 3) {
30905 return msg
30906 } else {
30907 throw new Error('unknown padding')
30908 }
30909}
30910
30911function oaep (key, msg) {
30912 var k = key.modulus.byteLength()
30913 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
30914 var hLen = iHash.length
30915 if (msg[0] !== 0) {
30916 throw new Error('decryption error')
30917 }
30918 var maskedSeed = msg.slice(1, hLen + 1)
30919 var maskedDb = msg.slice(hLen + 1)
30920 var seed = xor(maskedSeed, mgf(maskedDb, hLen))
30921 var db = xor(maskedDb, mgf(seed, k - hLen - 1))
30922 if (compare(iHash, db.slice(0, hLen))) {
30923 throw new Error('decryption error')
30924 }
30925 var i = hLen
30926 while (db[i] === 0) {
30927 i++
30928 }
30929 if (db[i++] !== 1) {
30930 throw new Error('decryption error')
30931 }
30932 return db.slice(i)
30933}
30934
30935function pkcs1 (key, msg, reverse) {
30936 var p1 = msg.slice(0, 2)
30937 var i = 2
30938 var status = 0
30939 while (msg[i++] !== 0) {
30940 if (i >= msg.length) {
30941 status++
30942 break
30943 }
30944 }
30945 var ps = msg.slice(2, i - 1)
30946
30947 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
30948 status++
30949 }
30950 if (ps.length < 8) {
30951 status++
30952 }
30953 if (status) {
30954 throw new Error('decryption error')
30955 }
30956 return msg.slice(i)
30957}
30958function compare (a, b) {
30959 a = Buffer.from(a)
30960 b = Buffer.from(b)
30961 var dif = 0
30962 var len = a.length
30963 if (a.length !== b.length) {
30964 dif++
30965 len = Math.min(a.length, b.length)
30966 }
30967 var i = -1
30968 while (++i < len) {
30969 dif += (a[i] ^ b[i])
30970 }
30971 return dif
30972}
30973
30974},{"./mgf":371,"./withPublic":374,"./xor":375,"bn.js":18,"browserify-rsa":41,"create-hash":67,"parse-asn1":362,"safe-buffer":393}],373:[function(require,module,exports){
30975var parseKeys = require('parse-asn1')
30976var randomBytes = require('randombytes')
30977var createHash = require('create-hash')
30978var mgf = require('./mgf')
30979var xor = require('./xor')
30980var BN = require('bn.js')
30981var withPublic = require('./withPublic')
30982var crt = require('browserify-rsa')
30983var Buffer = require('safe-buffer').Buffer
30984
30985module.exports = function publicEncrypt (publicKey, msg, reverse) {
30986 var padding
30987 if (publicKey.padding) {
30988 padding = publicKey.padding
30989 } else if (reverse) {
30990 padding = 1
30991 } else {
30992 padding = 4
30993 }
30994 var key = parseKeys(publicKey)
30995 var paddedMsg
30996 if (padding === 4) {
30997 paddedMsg = oaep(key, msg)
30998 } else if (padding === 1) {
30999 paddedMsg = pkcs1(key, msg, reverse)
31000 } else if (padding === 3) {
31001 paddedMsg = new BN(msg)
31002 if (paddedMsg.cmp(key.modulus) >= 0) {
31003 throw new Error('data too long for modulus')
31004 }
31005 } else {
31006 throw new Error('unknown padding')
31007 }
31008 if (reverse) {
31009 return crt(paddedMsg, key)
31010 } else {
31011 return withPublic(paddedMsg, key)
31012 }
31013}
31014
31015function oaep (key, msg) {
31016 var k = key.modulus.byteLength()
31017 var mLen = msg.length
31018 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
31019 var hLen = iHash.length
31020 var hLen2 = 2 * hLen
31021 if (mLen > k - hLen2 - 2) {
31022 throw new Error('message too long')
31023 }
31024 var ps = Buffer.alloc(k - mLen - hLen2 - 2)
31025 var dblen = k - hLen - 1
31026 var seed = randomBytes(hLen)
31027 var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
31028 var maskedSeed = xor(seed, mgf(maskedDb, hLen))
31029 return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
31030}
31031function pkcs1 (key, msg, reverse) {
31032 var mLen = msg.length
31033 var k = key.modulus.byteLength()
31034 if (mLen > k - 11) {
31035 throw new Error('message too long')
31036 }
31037 var ps
31038 if (reverse) {
31039 ps = Buffer.alloc(k - mLen - 3, 0xff)
31040 } else {
31041 ps = nonZero(k - mLen - 3)
31042 }
31043 return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
31044}
31045function nonZero (len) {
31046 var out = Buffer.allocUnsafe(len)
31047 var i = 0
31048 var cache = randomBytes(len * 2)
31049 var cur = 0
31050 var num
31051 while (i < len) {
31052 if (cur === cache.length) {
31053 cache = randomBytes(len * 2)
31054 cur = 0
31055 }
31056 num = cache[cur++]
31057 if (num) {
31058 out[i++] = num
31059 }
31060 }
31061 return out
31062}
31063
31064},{"./mgf":371,"./withPublic":374,"./xor":375,"bn.js":18,"browserify-rsa":41,"create-hash":67,"parse-asn1":362,"randombytes":376,"safe-buffer":393}],374:[function(require,module,exports){
31065var BN = require('bn.js')
31066var Buffer = require('safe-buffer').Buffer
31067
31068function withPublic (paddedMsg, key) {
31069 return Buffer.from(paddedMsg
31070 .toRed(BN.mont(key.modulus))
31071 .redPow(new BN(key.publicExponent))
31072 .fromRed()
31073 .toArray())
31074}
31075
31076module.exports = withPublic
31077
31078},{"bn.js":18,"safe-buffer":393}],375:[function(require,module,exports){
31079module.exports = function xor (a, b) {
31080 var len = a.length
31081 var i = -1
31082 while (++i < len) {
31083 a[i] ^= b[i]
31084 }
31085 return a
31086}
31087
31088},{}],376:[function(require,module,exports){
31089(function (process,global){
31090'use strict'
31091
31092function oldBrowser () {
31093 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
31094}
31095
31096var Buffer = require('safe-buffer').Buffer
31097var crypto = global.crypto || global.msCrypto
31098
31099if (crypto && crypto.getRandomValues) {
31100 module.exports = randomBytes
31101} else {
31102 module.exports = oldBrowser
31103}
31104
31105function randomBytes (size, cb) {
31106 // phantomjs needs to throw
31107 if (size > 65536) throw new Error('requested too many random bytes')
31108 // in case browserify isn't using the Uint8Array version
31109 var rawBytes = new global.Uint8Array(size)
31110
31111 // This will not work in older browsers.
31112 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
31113 if (size > 0) { // getRandomValues fails on IE if size == 0
31114 crypto.getRandomValues(rawBytes)
31115 }
31116
31117 // XXX: phantomjs doesn't like a buffer being passed here
31118 var bytes = Buffer.from(rawBytes.buffer)
31119
31120 if (typeof cb === 'function') {
31121 return process.nextTick(function () {
31122 cb(null, bytes)
31123 })
31124 }
31125
31126 return bytes
31127}
31128
31129}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
31130},{"_process":369,"safe-buffer":393}],377:[function(require,module,exports){
31131(function (process,global){
31132'use strict'
31133
31134function oldBrowser () {
31135 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
31136}
31137var safeBuffer = require('safe-buffer')
31138var randombytes = require('randombytes')
31139var Buffer = safeBuffer.Buffer
31140var kBufferMaxLength = safeBuffer.kMaxLength
31141var crypto = global.crypto || global.msCrypto
31142var kMaxUint32 = Math.pow(2, 32) - 1
31143function assertOffset (offset, length) {
31144 if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
31145 throw new TypeError('offset must be a number')
31146 }
31147
31148 if (offset > kMaxUint32 || offset < 0) {
31149 throw new TypeError('offset must be a uint32')
31150 }
31151
31152 if (offset > kBufferMaxLength || offset > length) {
31153 throw new RangeError('offset out of range')
31154 }
31155}
31156
31157function assertSize (size, offset, length) {
31158 if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
31159 throw new TypeError('size must be a number')
31160 }
31161
31162 if (size > kMaxUint32 || size < 0) {
31163 throw new TypeError('size must be a uint32')
31164 }
31165
31166 if (size + offset > length || size > kBufferMaxLength) {
31167 throw new RangeError('buffer too small')
31168 }
31169}
31170if ((crypto && crypto.getRandomValues) || !process.browser) {
31171 exports.randomFill = randomFill
31172 exports.randomFillSync = randomFillSync
31173} else {
31174 exports.randomFill = oldBrowser
31175 exports.randomFillSync = oldBrowser
31176}
31177function randomFill (buf, offset, size, cb) {
31178 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
31179 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
31180 }
31181
31182 if (typeof offset === 'function') {
31183 cb = offset
31184 offset = 0
31185 size = buf.length
31186 } else if (typeof size === 'function') {
31187 cb = size
31188 size = buf.length - offset
31189 } else if (typeof cb !== 'function') {
31190 throw new TypeError('"cb" argument must be a function')
31191 }
31192 assertOffset(offset, buf.length)
31193 assertSize(size, offset, buf.length)
31194 return actualFill(buf, offset, size, cb)
31195}
31196
31197function actualFill (buf, offset, size, cb) {
31198 if (process.browser) {
31199 var ourBuf = buf.buffer
31200 var uint = new Uint8Array(ourBuf, offset, size)
31201 crypto.getRandomValues(uint)
31202 if (cb) {
31203 process.nextTick(function () {
31204 cb(null, buf)
31205 })
31206 return
31207 }
31208 return buf
31209 }
31210 if (cb) {
31211 randombytes(size, function (err, bytes) {
31212 if (err) {
31213 return cb(err)
31214 }
31215 bytes.copy(buf, offset)
31216 cb(null, buf)
31217 })
31218 return
31219 }
31220 var bytes = randombytes(size)
31221 bytes.copy(buf, offset)
31222 return buf
31223}
31224function randomFillSync (buf, offset, size) {
31225 if (typeof offset === 'undefined') {
31226 offset = 0
31227 }
31228 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
31229 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
31230 }
31231
31232 assertOffset(offset, buf.length)
31233
31234 if (size === undefined) size = buf.length - offset
31235
31236 assertSize(size, offset, buf.length)
31237
31238 return actualFill(buf, offset, size)
31239}
31240
31241}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
31242},{"_process":369,"randombytes":376,"safe-buffer":393}],378:[function(require,module,exports){
31243module.exports = require('./lib/_stream_duplex.js');
31244
31245},{"./lib/_stream_duplex.js":379}],379:[function(require,module,exports){
31246// Copyright Joyent, Inc. and other Node contributors.
31247//
31248// Permission is hereby granted, free of charge, to any person obtaining a
31249// copy of this software and associated documentation files (the
31250// "Software"), to deal in the Software without restriction, including
31251// without limitation the rights to use, copy, modify, merge, publish,
31252// distribute, sublicense, and/or sell copies of the Software, and to permit
31253// persons to whom the Software is furnished to do so, subject to the
31254// following conditions:
31255//
31256// The above copyright notice and this permission notice shall be included
31257// in all copies or substantial portions of the Software.
31258//
31259// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
31260// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31261// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
31262// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
31263// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
31264// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
31265// USE OR OTHER DEALINGS IN THE SOFTWARE.
31266
31267// a duplex stream is just a stream that is both readable and writable.
31268// Since JS doesn't have multiple prototypal inheritance, this class
31269// prototypally inherits from Readable, and then parasitically from
31270// Writable.
31271
31272'use strict';
31273
31274/*<replacement>*/
31275
31276var pna = require('process-nextick-args');
31277/*</replacement>*/
31278
31279/*<replacement>*/
31280var objectKeys = Object.keys || function (obj) {
31281 var keys = [];
31282 for (var key in obj) {
31283 keys.push(key);
31284 }return keys;
31285};
31286/*</replacement>*/
31287
31288module.exports = Duplex;
31289
31290/*<replacement>*/
31291var util = require('core-util-is');
31292util.inherits = require('inherits');
31293/*</replacement>*/
31294
31295var Readable = require('./_stream_readable');
31296var Writable = require('./_stream_writable');
31297
31298util.inherits(Duplex, Readable);
31299
31300{
31301 // avoid scope creep, the keys array can then be collected
31302 var keys = objectKeys(Writable.prototype);
31303 for (var v = 0; v < keys.length; v++) {
31304 var method = keys[v];
31305 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
31306 }
31307}
31308
31309function Duplex(options) {
31310 if (!(this instanceof Duplex)) return new Duplex(options);
31311
31312 Readable.call(this, options);
31313 Writable.call(this, options);
31314
31315 if (options && options.readable === false) this.readable = false;
31316
31317 if (options && options.writable === false) this.writable = false;
31318
31319 this.allowHalfOpen = true;
31320 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
31321
31322 this.once('end', onend);
31323}
31324
31325Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
31326 // making it explicit this property is not enumerable
31327 // because otherwise some prototype manipulation in
31328 // userland will fail
31329 enumerable: false,
31330 get: function () {
31331 return this._writableState.highWaterMark;
31332 }
31333});
31334
31335// the no-half-open enforcer
31336function onend() {
31337 // if we allow half-open state, or if the writable side ended,
31338 // then we're ok.
31339 if (this.allowHalfOpen || this._writableState.ended) return;
31340
31341 // no more data can be written.
31342 // But allow more writes to happen in this tick.
31343 pna.nextTick(onEndNT, this);
31344}
31345
31346function onEndNT(self) {
31347 self.end();
31348}
31349
31350Object.defineProperty(Duplex.prototype, 'destroyed', {
31351 get: function () {
31352 if (this._readableState === undefined || this._writableState === undefined) {
31353 return false;
31354 }
31355 return this._readableState.destroyed && this._writableState.destroyed;
31356 },
31357 set: function (value) {
31358 // we ignore the value if the stream
31359 // has not been initialized yet
31360 if (this._readableState === undefined || this._writableState === undefined) {
31361 return;
31362 }
31363
31364 // backward compatibility, the user is explicitly
31365 // managing destroyed
31366 this._readableState.destroyed = value;
31367 this._writableState.destroyed = value;
31368 }
31369});
31370
31371Duplex.prototype._destroy = function (err, cb) {
31372 this.push(null);
31373 this.end();
31374
31375 pna.nextTick(cb, err);
31376};
31377},{"./_stream_readable":381,"./_stream_writable":383,"core-util-is":51,"inherits":116,"process-nextick-args":368}],380:[function(require,module,exports){
31378// Copyright Joyent, Inc. and other Node contributors.
31379//
31380// Permission is hereby granted, free of charge, to any person obtaining a
31381// copy of this software and associated documentation files (the
31382// "Software"), to deal in the Software without restriction, including
31383// without limitation the rights to use, copy, modify, merge, publish,
31384// distribute, sublicense, and/or sell copies of the Software, and to permit
31385// persons to whom the Software is furnished to do so, subject to the
31386// following conditions:
31387//
31388// The above copyright notice and this permission notice shall be included
31389// in all copies or substantial portions of the Software.
31390//
31391// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
31392// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31393// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
31394// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
31395// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
31396// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
31397// USE OR OTHER DEALINGS IN THE SOFTWARE.
31398
31399// a passthrough stream.
31400// basically just the most minimal sort of Transform stream.
31401// Every written chunk gets output as-is.
31402
31403'use strict';
31404
31405module.exports = PassThrough;
31406
31407var Transform = require('./_stream_transform');
31408
31409/*<replacement>*/
31410var util = require('core-util-is');
31411util.inherits = require('inherits');
31412/*</replacement>*/
31413
31414util.inherits(PassThrough, Transform);
31415
31416function PassThrough(options) {
31417 if (!(this instanceof PassThrough)) return new PassThrough(options);
31418
31419 Transform.call(this, options);
31420}
31421
31422PassThrough.prototype._transform = function (chunk, encoding, cb) {
31423 cb(null, chunk);
31424};
31425},{"./_stream_transform":382,"core-util-is":51,"inherits":116}],381:[function(require,module,exports){
31426(function (process,global){
31427// Copyright Joyent, Inc. and other Node contributors.
31428//
31429// Permission is hereby granted, free of charge, to any person obtaining a
31430// copy of this software and associated documentation files (the
31431// "Software"), to deal in the Software without restriction, including
31432// without limitation the rights to use, copy, modify, merge, publish,
31433// distribute, sublicense, and/or sell copies of the Software, and to permit
31434// persons to whom the Software is furnished to do so, subject to the
31435// following conditions:
31436//
31437// The above copyright notice and this permission notice shall be included
31438// in all copies or substantial portions of the Software.
31439//
31440// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
31441// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31442// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
31443// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
31444// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
31445// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
31446// USE OR OTHER DEALINGS IN THE SOFTWARE.
31447
31448'use strict';
31449
31450/*<replacement>*/
31451
31452var pna = require('process-nextick-args');
31453/*</replacement>*/
31454
31455module.exports = Readable;
31456
31457/*<replacement>*/
31458var isArray = require('isarray');
31459/*</replacement>*/
31460
31461/*<replacement>*/
31462var Duplex;
31463/*</replacement>*/
31464
31465Readable.ReadableState = ReadableState;
31466
31467/*<replacement>*/
31468var EE = require('events').EventEmitter;
31469
31470var EElistenerCount = function (emitter, type) {
31471 return emitter.listeners(type).length;
31472};
31473/*</replacement>*/
31474
31475/*<replacement>*/
31476var Stream = require('./internal/streams/stream');
31477/*</replacement>*/
31478
31479/*<replacement>*/
31480
31481var Buffer = require('safe-buffer').Buffer;
31482var OurUint8Array = global.Uint8Array || function () {};
31483function _uint8ArrayToBuffer(chunk) {
31484 return Buffer.from(chunk);
31485}
31486function _isUint8Array(obj) {
31487 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
31488}
31489
31490/*</replacement>*/
31491
31492/*<replacement>*/
31493var util = require('core-util-is');
31494util.inherits = require('inherits');
31495/*</replacement>*/
31496
31497/*<replacement>*/
31498var debugUtil = require('util');
31499var debug = void 0;
31500if (debugUtil && debugUtil.debuglog) {
31501 debug = debugUtil.debuglog('stream');
31502} else {
31503 debug = function () {};
31504}
31505/*</replacement>*/
31506
31507var BufferList = require('./internal/streams/BufferList');
31508var destroyImpl = require('./internal/streams/destroy');
31509var StringDecoder;
31510
31511util.inherits(Readable, Stream);
31512
31513var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
31514
31515function prependListener(emitter, event, fn) {
31516 // Sadly this is not cacheable as some libraries bundle their own
31517 // event emitter implementation with them.
31518 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
31519
31520 // This is a hack to make sure that our error handler is attached before any
31521 // userland ones. NEVER DO THIS. This is here only because this code needs
31522 // to continue to work with older versions of Node.js that do not include
31523 // the prependListener() method. The goal is to eventually remove this hack.
31524 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]];
31525}
31526
31527function ReadableState(options, stream) {
31528 Duplex = Duplex || require('./_stream_duplex');
31529
31530 options = options || {};
31531
31532 // Duplex streams are both readable and writable, but share
31533 // the same options object.
31534 // However, some cases require setting options to different
31535 // values for the readable and the writable sides of the duplex stream.
31536 // These options can be provided separately as readableXXX and writableXXX.
31537 var isDuplex = stream instanceof Duplex;
31538
31539 // object stream flag. Used to make read(n) ignore n and to
31540 // make all the buffer merging and length checks go away
31541 this.objectMode = !!options.objectMode;
31542
31543 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
31544
31545 // the point at which it stops calling _read() to fill the buffer
31546 // Note: 0 is a valid value, means "don't call _read preemptively ever"
31547 var hwm = options.highWaterMark;
31548 var readableHwm = options.readableHighWaterMark;
31549 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
31550
31551 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
31552
31553 // cast to ints.
31554 this.highWaterMark = Math.floor(this.highWaterMark);
31555
31556 // A linked list is used to store data chunks instead of an array because the
31557 // linked list can remove elements from the beginning faster than
31558 // array.shift()
31559 this.buffer = new BufferList();
31560 this.length = 0;
31561 this.pipes = null;
31562 this.pipesCount = 0;
31563 this.flowing = null;
31564 this.ended = false;
31565 this.endEmitted = false;
31566 this.reading = false;
31567
31568 // a flag to be able to tell if the event 'readable'/'data' is emitted
31569 // immediately, or on a later tick. We set this to true at first, because
31570 // any actions that shouldn't happen until "later" should generally also
31571 // not happen before the first read call.
31572 this.sync = true;
31573
31574 // whenever we return null, then we set a flag to say
31575 // that we're awaiting a 'readable' event emission.
31576 this.needReadable = false;
31577 this.emittedReadable = false;
31578 this.readableListening = false;
31579 this.resumeScheduled = false;
31580
31581 // has it been destroyed
31582 this.destroyed = false;
31583
31584 // Crypto is kind of old and crusty. Historically, its default string
31585 // encoding is 'binary' so we have to make this configurable.
31586 // Everything else in the universe uses 'utf8', though.
31587 this.defaultEncoding = options.defaultEncoding || 'utf8';
31588
31589 // the number of writers that are awaiting a drain event in .pipe()s
31590 this.awaitDrain = 0;
31591
31592 // if true, a maybeReadMore has been scheduled
31593 this.readingMore = false;
31594
31595 this.decoder = null;
31596 this.encoding = null;
31597 if (options.encoding) {
31598 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
31599 this.decoder = new StringDecoder(options.encoding);
31600 this.encoding = options.encoding;
31601 }
31602}
31603
31604function Readable(options) {
31605 Duplex = Duplex || require('./_stream_duplex');
31606
31607 if (!(this instanceof Readable)) return new Readable(options);
31608
31609 this._readableState = new ReadableState(options, this);
31610
31611 // legacy
31612 this.readable = true;
31613
31614 if (options) {
31615 if (typeof options.read === 'function') this._read = options.read;
31616
31617 if (typeof options.destroy === 'function') this._destroy = options.destroy;
31618 }
31619
31620 Stream.call(this);
31621}
31622
31623Object.defineProperty(Readable.prototype, 'destroyed', {
31624 get: function () {
31625 if (this._readableState === undefined) {
31626 return false;
31627 }
31628 return this._readableState.destroyed;
31629 },
31630 set: function (value) {
31631 // we ignore the value if the stream
31632 // has not been initialized yet
31633 if (!this._readableState) {
31634 return;
31635 }
31636
31637 // backward compatibility, the user is explicitly
31638 // managing destroyed
31639 this._readableState.destroyed = value;
31640 }
31641});
31642
31643Readable.prototype.destroy = destroyImpl.destroy;
31644Readable.prototype._undestroy = destroyImpl.undestroy;
31645Readable.prototype._destroy = function (err, cb) {
31646 this.push(null);
31647 cb(err);
31648};
31649
31650// Manually shove something into the read() buffer.
31651// This returns true if the highWaterMark has not been hit yet,
31652// similar to how Writable.write() returns true if you should
31653// write() some more.
31654Readable.prototype.push = function (chunk, encoding) {
31655 var state = this._readableState;
31656 var skipChunkCheck;
31657
31658 if (!state.objectMode) {
31659 if (typeof chunk === 'string') {
31660 encoding = encoding || state.defaultEncoding;
31661 if (encoding !== state.encoding) {
31662 chunk = Buffer.from(chunk, encoding);
31663 encoding = '';
31664 }
31665 skipChunkCheck = true;
31666 }
31667 } else {
31668 skipChunkCheck = true;
31669 }
31670
31671 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
31672};
31673
31674// Unshift should *always* be something directly out of read()
31675Readable.prototype.unshift = function (chunk) {
31676 return readableAddChunk(this, chunk, null, true, false);
31677};
31678
31679function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
31680 var state = stream._readableState;
31681 if (chunk === null) {
31682 state.reading = false;
31683 onEofChunk(stream, state);
31684 } else {
31685 var er;
31686 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
31687 if (er) {
31688 stream.emit('error', er);
31689 } else if (state.objectMode || chunk && chunk.length > 0) {
31690 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
31691 chunk = _uint8ArrayToBuffer(chunk);
31692 }
31693
31694 if (addToFront) {
31695 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
31696 } else if (state.ended) {
31697 stream.emit('error', new Error('stream.push() after EOF'));
31698 } else {
31699 state.reading = false;
31700 if (state.decoder && !encoding) {
31701 chunk = state.decoder.write(chunk);
31702 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
31703 } else {
31704 addChunk(stream, state, chunk, false);
31705 }
31706 }
31707 } else if (!addToFront) {
31708 state.reading = false;
31709 }
31710 }
31711
31712 return needMoreData(state);
31713}
31714
31715function addChunk(stream, state, chunk, addToFront) {
31716 if (state.flowing && state.length === 0 && !state.sync) {
31717 stream.emit('data', chunk);
31718 stream.read(0);
31719 } else {
31720 // update the buffer info.
31721 state.length += state.objectMode ? 1 : chunk.length;
31722 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
31723
31724 if (state.needReadable) emitReadable(stream);
31725 }
31726 maybeReadMore(stream, state);
31727}
31728
31729function chunkInvalid(state, chunk) {
31730 var er;
31731 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
31732 er = new TypeError('Invalid non-string/buffer chunk');
31733 }
31734 return er;
31735}
31736
31737// if it's past the high water mark, we can push in some more.
31738// Also, if we have no data yet, we can stand some
31739// more bytes. This is to work around cases where hwm=0,
31740// such as the repl. Also, if the push() triggered a
31741// readable event, and the user called read(largeNumber) such that
31742// needReadable was set, then we ought to push more, so that another
31743// 'readable' event will be triggered.
31744function needMoreData(state) {
31745 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
31746}
31747
31748Readable.prototype.isPaused = function () {
31749 return this._readableState.flowing === false;
31750};
31751
31752// backwards compatibility.
31753Readable.prototype.setEncoding = function (enc) {
31754 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
31755 this._readableState.decoder = new StringDecoder(enc);
31756 this._readableState.encoding = enc;
31757 return this;
31758};
31759
31760// Don't raise the hwm > 8MB
31761var MAX_HWM = 0x800000;
31762function computeNewHighWaterMark(n) {
31763 if (n >= MAX_HWM) {
31764 n = MAX_HWM;
31765 } else {
31766 // Get the next highest power of 2 to prevent increasing hwm excessively in
31767 // tiny amounts
31768 n--;
31769 n |= n >>> 1;
31770 n |= n >>> 2;
31771 n |= n >>> 4;
31772 n |= n >>> 8;
31773 n |= n >>> 16;
31774 n++;
31775 }
31776 return n;
31777}
31778
31779// This function is designed to be inlinable, so please take care when making
31780// changes to the function body.
31781function howMuchToRead(n, state) {
31782 if (n <= 0 || state.length === 0 && state.ended) return 0;
31783 if (state.objectMode) return 1;
31784 if (n !== n) {
31785 // Only flow one buffer at a time
31786 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
31787 }
31788 // If we're asking for more than the current hwm, then raise the hwm.
31789 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
31790 if (n <= state.length) return n;
31791 // Don't have enough
31792 if (!state.ended) {
31793 state.needReadable = true;
31794 return 0;
31795 }
31796 return state.length;
31797}
31798
31799// you can override either this method, or the async _read(n) below.
31800Readable.prototype.read = function (n) {
31801 debug('read', n);
31802 n = parseInt(n, 10);
31803 var state = this._readableState;
31804 var nOrig = n;
31805
31806 if (n !== 0) state.emittedReadable = false;
31807
31808 // if we're doing read(0) to trigger a readable event, but we
31809 // already have a bunch of data in the buffer, then just trigger
31810 // the 'readable' event and move on.
31811 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
31812 debug('read: emitReadable', state.length, state.ended);
31813 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
31814 return null;
31815 }
31816
31817 n = howMuchToRead(n, state);
31818
31819 // if we've ended, and we're now clear, then finish it up.
31820 if (n === 0 && state.ended) {
31821 if (state.length === 0) endReadable(this);
31822 return null;
31823 }
31824
31825 // All the actual chunk generation logic needs to be
31826 // *below* the call to _read. The reason is that in certain
31827 // synthetic stream cases, such as passthrough streams, _read
31828 // may be a completely synchronous operation which may change
31829 // the state of the read buffer, providing enough data when
31830 // before there was *not* enough.
31831 //
31832 // So, the steps are:
31833 // 1. Figure out what the state of things will be after we do
31834 // a read from the buffer.
31835 //
31836 // 2. If that resulting state will trigger a _read, then call _read.
31837 // Note that this may be asynchronous, or synchronous. Yes, it is
31838 // deeply ugly to write APIs this way, but that still doesn't mean
31839 // that the Readable class should behave improperly, as streams are
31840 // designed to be sync/async agnostic.
31841 // Take note if the _read call is sync or async (ie, if the read call
31842 // has returned yet), so that we know whether or not it's safe to emit
31843 // 'readable' etc.
31844 //
31845 // 3. Actually pull the requested chunks out of the buffer and return.
31846
31847 // if we need a readable event, then we need to do some reading.
31848 var doRead = state.needReadable;
31849 debug('need readable', doRead);
31850
31851 // if we currently have less than the highWaterMark, then also read some
31852 if (state.length === 0 || state.length - n < state.highWaterMark) {
31853 doRead = true;
31854 debug('length less than watermark', doRead);
31855 }
31856
31857 // however, if we've ended, then there's no point, and if we're already
31858 // reading, then it's unnecessary.
31859 if (state.ended || state.reading) {
31860 doRead = false;
31861 debug('reading or ended', doRead);
31862 } else if (doRead) {
31863 debug('do read');
31864 state.reading = true;
31865 state.sync = true;
31866 // if the length is currently zero, then we *need* a readable event.
31867 if (state.length === 0) state.needReadable = true;
31868 // call internal read method
31869 this._read(state.highWaterMark);
31870 state.sync = false;
31871 // If _read pushed data synchronously, then `reading` will be false,
31872 // and we need to re-evaluate how much data we can return to the user.
31873 if (!state.reading) n = howMuchToRead(nOrig, state);
31874 }
31875
31876 var ret;
31877 if (n > 0) ret = fromList(n, state);else ret = null;
31878
31879 if (ret === null) {
31880 state.needReadable = true;
31881 n = 0;
31882 } else {
31883 state.length -= n;
31884 }
31885
31886 if (state.length === 0) {
31887 // If we have nothing in the buffer, then we want to know
31888 // as soon as we *do* get something into the buffer.
31889 if (!state.ended) state.needReadable = true;
31890
31891 // If we tried to read() past the EOF, then emit end on the next tick.
31892 if (nOrig !== n && state.ended) endReadable(this);
31893 }
31894
31895 if (ret !== null) this.emit('data', ret);
31896
31897 return ret;
31898};
31899
31900function onEofChunk(stream, state) {
31901 if (state.ended) return;
31902 if (state.decoder) {
31903 var chunk = state.decoder.end();
31904 if (chunk && chunk.length) {
31905 state.buffer.push(chunk);
31906 state.length += state.objectMode ? 1 : chunk.length;
31907 }
31908 }
31909 state.ended = true;
31910
31911 // emit 'readable' now to make sure it gets picked up.
31912 emitReadable(stream);
31913}
31914
31915// Don't emit readable right away in sync mode, because this can trigger
31916// another read() call => stack overflow. This way, it might trigger
31917// a nextTick recursion warning, but that's not so bad.
31918function emitReadable(stream) {
31919 var state = stream._readableState;
31920 state.needReadable = false;
31921 if (!state.emittedReadable) {
31922 debug('emitReadable', state.flowing);
31923 state.emittedReadable = true;
31924 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
31925 }
31926}
31927
31928function emitReadable_(stream) {
31929 debug('emit readable');
31930 stream.emit('readable');
31931 flow(stream);
31932}
31933
31934// at this point, the user has presumably seen the 'readable' event,
31935// and called read() to consume some data. that may have triggered
31936// in turn another _read(n) call, in which case reading = true if
31937// it's in progress.
31938// However, if we're not ended, or reading, and the length < hwm,
31939// then go ahead and try to read some more preemptively.
31940function maybeReadMore(stream, state) {
31941 if (!state.readingMore) {
31942 state.readingMore = true;
31943 pna.nextTick(maybeReadMore_, stream, state);
31944 }
31945}
31946
31947function maybeReadMore_(stream, state) {
31948 var len = state.length;
31949 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
31950 debug('maybeReadMore read 0');
31951 stream.read(0);
31952 if (len === state.length)
31953 // didn't get any data, stop spinning.
31954 break;else len = state.length;
31955 }
31956 state.readingMore = false;
31957}
31958
31959// abstract method. to be overridden in specific implementation classes.
31960// call cb(er, data) where data is <= n in length.
31961// for virtual (non-string, non-buffer) streams, "length" is somewhat
31962// arbitrary, and perhaps not very meaningful.
31963Readable.prototype._read = function (n) {
31964 this.emit('error', new Error('_read() is not implemented'));
31965};
31966
31967Readable.prototype.pipe = function (dest, pipeOpts) {
31968 var src = this;
31969 var state = this._readableState;
31970
31971 switch (state.pipesCount) {
31972 case 0:
31973 state.pipes = dest;
31974 break;
31975 case 1:
31976 state.pipes = [state.pipes, dest];
31977 break;
31978 default:
31979 state.pipes.push(dest);
31980 break;
31981 }
31982 state.pipesCount += 1;
31983 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
31984
31985 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
31986
31987 var endFn = doEnd ? onend : unpipe;
31988 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
31989
31990 dest.on('unpipe', onunpipe);
31991 function onunpipe(readable, unpipeInfo) {
31992 debug('onunpipe');
31993 if (readable === src) {
31994 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
31995 unpipeInfo.hasUnpiped = true;
31996 cleanup();
31997 }
31998 }
31999 }
32000
32001 function onend() {
32002 debug('onend');
32003 dest.end();
32004 }
32005
32006 // when the dest drains, it reduces the awaitDrain counter
32007 // on the source. This would be more elegant with a .once()
32008 // handler in flow(), but adding and removing repeatedly is
32009 // too slow.
32010 var ondrain = pipeOnDrain(src);
32011 dest.on('drain', ondrain);
32012
32013 var cleanedUp = false;
32014 function cleanup() {
32015 debug('cleanup');
32016 // cleanup event handlers once the pipe is broken
32017 dest.removeListener('close', onclose);
32018 dest.removeListener('finish', onfinish);
32019 dest.removeListener('drain', ondrain);
32020 dest.removeListener('error', onerror);
32021 dest.removeListener('unpipe', onunpipe);
32022 src.removeListener('end', onend);
32023 src.removeListener('end', unpipe);
32024 src.removeListener('data', ondata);
32025
32026 cleanedUp = true;
32027
32028 // if the reader is waiting for a drain event from this
32029 // specific writer, then it would cause it to never start
32030 // flowing again.
32031 // So, if this is awaiting a drain, then we just call it now.
32032 // If we don't know, then assume that we are waiting for one.
32033 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
32034 }
32035
32036 // If the user pushes more data while we're writing to dest then we'll end up
32037 // in ondata again. However, we only want to increase awaitDrain once because
32038 // dest will only emit one 'drain' event for the multiple writes.
32039 // => Introduce a guard on increasing awaitDrain.
32040 var increasedAwaitDrain = false;
32041 src.on('data', ondata);
32042 function ondata(chunk) {
32043 debug('ondata');
32044 increasedAwaitDrain = false;
32045 var ret = dest.write(chunk);
32046 if (false === ret && !increasedAwaitDrain) {
32047 // If the user unpiped during `dest.write()`, it is possible
32048 // to get stuck in a permanently paused state if that write
32049 // also returned false.
32050 // => Check whether `dest` is still a piping destination.
32051 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
32052 debug('false write response, pause', src._readableState.awaitDrain);
32053 src._readableState.awaitDrain++;
32054 increasedAwaitDrain = true;
32055 }
32056 src.pause();
32057 }
32058 }
32059
32060 // if the dest has an error, then stop piping into it.
32061 // however, don't suppress the throwing behavior for this.
32062 function onerror(er) {
32063 debug('onerror', er);
32064 unpipe();
32065 dest.removeListener('error', onerror);
32066 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
32067 }
32068
32069 // Make sure our error handler is attached before userland ones.
32070 prependListener(dest, 'error', onerror);
32071
32072 // Both close and finish should trigger unpipe, but only once.
32073 function onclose() {
32074 dest.removeListener('finish', onfinish);
32075 unpipe();
32076 }
32077 dest.once('close', onclose);
32078 function onfinish() {
32079 debug('onfinish');
32080 dest.removeListener('close', onclose);
32081 unpipe();
32082 }
32083 dest.once('finish', onfinish);
32084
32085 function unpipe() {
32086 debug('unpipe');
32087 src.unpipe(dest);
32088 }
32089
32090 // tell the dest that it's being piped to
32091 dest.emit('pipe', src);
32092
32093 // start the flow if it hasn't been started already.
32094 if (!state.flowing) {
32095 debug('pipe resume');
32096 src.resume();
32097 }
32098
32099 return dest;
32100};
32101
32102function pipeOnDrain(src) {
32103 return function () {
32104 var state = src._readableState;
32105 debug('pipeOnDrain', state.awaitDrain);
32106 if (state.awaitDrain) state.awaitDrain--;
32107 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
32108 state.flowing = true;
32109 flow(src);
32110 }
32111 };
32112}
32113
32114Readable.prototype.unpipe = function (dest) {
32115 var state = this._readableState;
32116 var unpipeInfo = { hasUnpiped: false };
32117
32118 // if we're not piping anywhere, then do nothing.
32119 if (state.pipesCount === 0) return this;
32120
32121 // just one destination. most common case.
32122 if (state.pipesCount === 1) {
32123 // passed in one, but it's not the right one.
32124 if (dest && dest !== state.pipes) return this;
32125
32126 if (!dest) dest = state.pipes;
32127
32128 // got a match.
32129 state.pipes = null;
32130 state.pipesCount = 0;
32131 state.flowing = false;
32132 if (dest) dest.emit('unpipe', this, unpipeInfo);
32133 return this;
32134 }
32135
32136 // slow case. multiple pipe destinations.
32137
32138 if (!dest) {
32139 // remove all.
32140 var dests = state.pipes;
32141 var len = state.pipesCount;
32142 state.pipes = null;
32143 state.pipesCount = 0;
32144 state.flowing = false;
32145
32146 for (var i = 0; i < len; i++) {
32147 dests[i].emit('unpipe', this, unpipeInfo);
32148 }return this;
32149 }
32150
32151 // try to find the right one.
32152 var index = indexOf(state.pipes, dest);
32153 if (index === -1) return this;
32154
32155 state.pipes.splice(index, 1);
32156 state.pipesCount -= 1;
32157 if (state.pipesCount === 1) state.pipes = state.pipes[0];
32158
32159 dest.emit('unpipe', this, unpipeInfo);
32160
32161 return this;
32162};
32163
32164// set up data events if they are asked for
32165// Ensure readable listeners eventually get something
32166Readable.prototype.on = function (ev, fn) {
32167 var res = Stream.prototype.on.call(this, ev, fn);
32168
32169 if (ev === 'data') {
32170 // Start flowing on next tick if stream isn't explicitly paused
32171 if (this._readableState.flowing !== false) this.resume();
32172 } else if (ev === 'readable') {
32173 var state = this._readableState;
32174 if (!state.endEmitted && !state.readableListening) {
32175 state.readableListening = state.needReadable = true;
32176 state.emittedReadable = false;
32177 if (!state.reading) {
32178 pna.nextTick(nReadingNextTick, this);
32179 } else if (state.length) {
32180 emitReadable(this);
32181 }
32182 }
32183 }
32184
32185 return res;
32186};
32187Readable.prototype.addListener = Readable.prototype.on;
32188
32189function nReadingNextTick(self) {
32190 debug('readable nexttick read 0');
32191 self.read(0);
32192}
32193
32194// pause() and resume() are remnants of the legacy readable stream API
32195// If the user uses them, then switch into old mode.
32196Readable.prototype.resume = function () {
32197 var state = this._readableState;
32198 if (!state.flowing) {
32199 debug('resume');
32200 state.flowing = true;
32201 resume(this, state);
32202 }
32203 return this;
32204};
32205
32206function resume(stream, state) {
32207 if (!state.resumeScheduled) {
32208 state.resumeScheduled = true;
32209 pna.nextTick(resume_, stream, state);
32210 }
32211}
32212
32213function resume_(stream, state) {
32214 if (!state.reading) {
32215 debug('resume read 0');
32216 stream.read(0);
32217 }
32218
32219 state.resumeScheduled = false;
32220 state.awaitDrain = 0;
32221 stream.emit('resume');
32222 flow(stream);
32223 if (state.flowing && !state.reading) stream.read(0);
32224}
32225
32226Readable.prototype.pause = function () {
32227 debug('call pause flowing=%j', this._readableState.flowing);
32228 if (false !== this._readableState.flowing) {
32229 debug('pause');
32230 this._readableState.flowing = false;
32231 this.emit('pause');
32232 }
32233 return this;
32234};
32235
32236function flow(stream) {
32237 var state = stream._readableState;
32238 debug('flow', state.flowing);
32239 while (state.flowing && stream.read() !== null) {}
32240}
32241
32242// wrap an old-style stream as the async data source.
32243// This is *not* part of the readable stream interface.
32244// It is an ugly unfortunate mess of history.
32245Readable.prototype.wrap = function (stream) {
32246 var _this = this;
32247
32248 var state = this._readableState;
32249 var paused = false;
32250
32251 stream.on('end', function () {
32252 debug('wrapped end');
32253 if (state.decoder && !state.ended) {
32254 var chunk = state.decoder.end();
32255 if (chunk && chunk.length) _this.push(chunk);
32256 }
32257
32258 _this.push(null);
32259 });
32260
32261 stream.on('data', function (chunk) {
32262 debug('wrapped data');
32263 if (state.decoder) chunk = state.decoder.write(chunk);
32264
32265 // don't skip over falsy values in objectMode
32266 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
32267
32268 var ret = _this.push(chunk);
32269 if (!ret) {
32270 paused = true;
32271 stream.pause();
32272 }
32273 });
32274
32275 // proxy all the other methods.
32276 // important when wrapping filters and duplexes.
32277 for (var i in stream) {
32278 if (this[i] === undefined && typeof stream[i] === 'function') {
32279 this[i] = function (method) {
32280 return function () {
32281 return stream[method].apply(stream, arguments);
32282 };
32283 }(i);
32284 }
32285 }
32286
32287 // proxy certain important events.
32288 for (var n = 0; n < kProxyEvents.length; n++) {
32289 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
32290 }
32291
32292 // when we try to consume some more bytes, simply unpause the
32293 // underlying stream.
32294 this._read = function (n) {
32295 debug('wrapped _read', n);
32296 if (paused) {
32297 paused = false;
32298 stream.resume();
32299 }
32300 };
32301
32302 return this;
32303};
32304
32305Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
32306 // making it explicit this property is not enumerable
32307 // because otherwise some prototype manipulation in
32308 // userland will fail
32309 enumerable: false,
32310 get: function () {
32311 return this._readableState.highWaterMark;
32312 }
32313});
32314
32315// exposed for testing purposes only.
32316Readable._fromList = fromList;
32317
32318// Pluck off n bytes from an array of buffers.
32319// Length is the combined lengths of all the buffers in the list.
32320// This function is designed to be inlinable, so please take care when making
32321// changes to the function body.
32322function fromList(n, state) {
32323 // nothing buffered
32324 if (state.length === 0) return null;
32325
32326 var ret;
32327 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
32328 // read it all, truncate the list
32329 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);
32330 state.buffer.clear();
32331 } else {
32332 // read part of list
32333 ret = fromListPartial(n, state.buffer, state.decoder);
32334 }
32335
32336 return ret;
32337}
32338
32339// Extracts only enough buffered data to satisfy the amount requested.
32340// This function is designed to be inlinable, so please take care when making
32341// changes to the function body.
32342function fromListPartial(n, list, hasStrings) {
32343 var ret;
32344 if (n < list.head.data.length) {
32345 // slice is the same for buffers and strings
32346 ret = list.head.data.slice(0, n);
32347 list.head.data = list.head.data.slice(n);
32348 } else if (n === list.head.data.length) {
32349 // first chunk is a perfect match
32350 ret = list.shift();
32351 } else {
32352 // result spans more than one buffer
32353 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
32354 }
32355 return ret;
32356}
32357
32358// Copies a specified amount of characters from the list of buffered data
32359// chunks.
32360// This function is designed to be inlinable, so please take care when making
32361// changes to the function body.
32362function copyFromBufferString(n, list) {
32363 var p = list.head;
32364 var c = 1;
32365 var ret = p.data;
32366 n -= ret.length;
32367 while (p = p.next) {
32368 var str = p.data;
32369 var nb = n > str.length ? str.length : n;
32370 if (nb === str.length) ret += str;else ret += str.slice(0, n);
32371 n -= nb;
32372 if (n === 0) {
32373 if (nb === str.length) {
32374 ++c;
32375 if (p.next) list.head = p.next;else list.head = list.tail = null;
32376 } else {
32377 list.head = p;
32378 p.data = str.slice(nb);
32379 }
32380 break;
32381 }
32382 ++c;
32383 }
32384 list.length -= c;
32385 return ret;
32386}
32387
32388// Copies a specified amount of bytes from the list of buffered data chunks.
32389// This function is designed to be inlinable, so please take care when making
32390// changes to the function body.
32391function copyFromBuffer(n, list) {
32392 var ret = Buffer.allocUnsafe(n);
32393 var p = list.head;
32394 var c = 1;
32395 p.data.copy(ret);
32396 n -= p.data.length;
32397 while (p = p.next) {
32398 var buf = p.data;
32399 var nb = n > buf.length ? buf.length : n;
32400 buf.copy(ret, ret.length - n, 0, nb);
32401 n -= nb;
32402 if (n === 0) {
32403 if (nb === buf.length) {
32404 ++c;
32405 if (p.next) list.head = p.next;else list.head = list.tail = null;
32406 } else {
32407 list.head = p;
32408 p.data = buf.slice(nb);
32409 }
32410 break;
32411 }
32412 ++c;
32413 }
32414 list.length -= c;
32415 return ret;
32416}
32417
32418function endReadable(stream) {
32419 var state = stream._readableState;
32420
32421 // If we get here before consuming all the bytes, then that is a
32422 // bug in node. Should never happen.
32423 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
32424
32425 if (!state.endEmitted) {
32426 state.ended = true;
32427 pna.nextTick(endReadableNT, state, stream);
32428 }
32429}
32430
32431function endReadableNT(state, stream) {
32432 // Check that we didn't get one last unshift.
32433 if (!state.endEmitted && state.length === 0) {
32434 state.endEmitted = true;
32435 stream.readable = false;
32436 stream.emit('end');
32437 }
32438}
32439
32440function indexOf(xs, x) {
32441 for (var i = 0, l = xs.length; i < l; i++) {
32442 if (xs[i] === x) return i;
32443 }
32444 return -1;
32445}
32446}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
32447},{"./_stream_duplex":379,"./internal/streams/BufferList":384,"./internal/streams/destroy":385,"./internal/streams/stream":386,"_process":369,"core-util-is":51,"events":99,"inherits":116,"isarray":118,"process-nextick-args":368,"safe-buffer":393,"string_decoder/":387,"util":20}],382:[function(require,module,exports){
32448// Copyright Joyent, Inc. and other Node contributors.
32449//
32450// Permission is hereby granted, free of charge, to any person obtaining a
32451// copy of this software and associated documentation files (the
32452// "Software"), to deal in the Software without restriction, including
32453// without limitation the rights to use, copy, modify, merge, publish,
32454// distribute, sublicense, and/or sell copies of the Software, and to permit
32455// persons to whom the Software is furnished to do so, subject to the
32456// following conditions:
32457//
32458// The above copyright notice and this permission notice shall be included
32459// in all copies or substantial portions of the Software.
32460//
32461// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
32462// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32463// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
32464// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
32465// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
32466// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
32467// USE OR OTHER DEALINGS IN THE SOFTWARE.
32468
32469// a transform stream is a readable/writable stream where you do
32470// something with the data. Sometimes it's called a "filter",
32471// but that's not a great name for it, since that implies a thing where
32472// some bits pass through, and others are simply ignored. (That would
32473// be a valid example of a transform, of course.)
32474//
32475// While the output is causally related to the input, it's not a
32476// necessarily symmetric or synchronous transformation. For example,
32477// a zlib stream might take multiple plain-text writes(), and then
32478// emit a single compressed chunk some time in the future.
32479//
32480// Here's how this works:
32481//
32482// The Transform stream has all the aspects of the readable and writable
32483// stream classes. When you write(chunk), that calls _write(chunk,cb)
32484// internally, and returns false if there's a lot of pending writes
32485// buffered up. When you call read(), that calls _read(n) until
32486// there's enough pending readable data buffered up.
32487//
32488// In a transform stream, the written data is placed in a buffer. When
32489// _read(n) is called, it transforms the queued up data, calling the
32490// buffered _write cb's as it consumes chunks. If consuming a single
32491// written chunk would result in multiple output chunks, then the first
32492// outputted bit calls the readcb, and subsequent chunks just go into
32493// the read buffer, and will cause it to emit 'readable' if necessary.
32494//
32495// This way, back-pressure is actually determined by the reading side,
32496// since _read has to be called to start processing a new chunk. However,
32497// a pathological inflate type of transform can cause excessive buffering
32498// here. For example, imagine a stream where every byte of input is
32499// interpreted as an integer from 0-255, and then results in that many
32500// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
32501// 1kb of data being output. In this case, you could write a very small
32502// amount of input, and end up with a very large amount of output. In
32503// such a pathological inflating mechanism, there'd be no way to tell
32504// the system to stop doing the transform. A single 4MB write could
32505// cause the system to run out of memory.
32506//
32507// However, even in such a pathological case, only a single written chunk
32508// would be consumed, and then the rest would wait (un-transformed) until
32509// the results of the previous transformed chunk were consumed.
32510
32511'use strict';
32512
32513module.exports = Transform;
32514
32515var Duplex = require('./_stream_duplex');
32516
32517/*<replacement>*/
32518var util = require('core-util-is');
32519util.inherits = require('inherits');
32520/*</replacement>*/
32521
32522util.inherits(Transform, Duplex);
32523
32524function afterTransform(er, data) {
32525 var ts = this._transformState;
32526 ts.transforming = false;
32527
32528 var cb = ts.writecb;
32529
32530 if (!cb) {
32531 return this.emit('error', new Error('write callback called multiple times'));
32532 }
32533
32534 ts.writechunk = null;
32535 ts.writecb = null;
32536
32537 if (data != null) // single equals check for both `null` and `undefined`
32538 this.push(data);
32539
32540 cb(er);
32541
32542 var rs = this._readableState;
32543 rs.reading = false;
32544 if (rs.needReadable || rs.length < rs.highWaterMark) {
32545 this._read(rs.highWaterMark);
32546 }
32547}
32548
32549function Transform(options) {
32550 if (!(this instanceof Transform)) return new Transform(options);
32551
32552 Duplex.call(this, options);
32553
32554 this._transformState = {
32555 afterTransform: afterTransform.bind(this),
32556 needTransform: false,
32557 transforming: false,
32558 writecb: null,
32559 writechunk: null,
32560 writeencoding: null
32561 };
32562
32563 // start out asking for a readable event once data is transformed.
32564 this._readableState.needReadable = true;
32565
32566 // we have implemented the _read method, and done the other things
32567 // that Readable wants before the first _read call, so unset the
32568 // sync guard flag.
32569 this._readableState.sync = false;
32570
32571 if (options) {
32572 if (typeof options.transform === 'function') this._transform = options.transform;
32573
32574 if (typeof options.flush === 'function') this._flush = options.flush;
32575 }
32576
32577 // When the writable side finishes, then flush out anything remaining.
32578 this.on('prefinish', prefinish);
32579}
32580
32581function prefinish() {
32582 var _this = this;
32583
32584 if (typeof this._flush === 'function') {
32585 this._flush(function (er, data) {
32586 done(_this, er, data);
32587 });
32588 } else {
32589 done(this, null, null);
32590 }
32591}
32592
32593Transform.prototype.push = function (chunk, encoding) {
32594 this._transformState.needTransform = false;
32595 return Duplex.prototype.push.call(this, chunk, encoding);
32596};
32597
32598// This is the part where you do stuff!
32599// override this function in implementation classes.
32600// 'chunk' is an input chunk.
32601//
32602// Call `push(newChunk)` to pass along transformed output
32603// to the readable side. You may call 'push' zero or more times.
32604//
32605// Call `cb(err)` when you are done with this chunk. If you pass
32606// an error, then that'll put the hurt on the whole operation. If you
32607// never call cb(), then you'll never get another chunk.
32608Transform.prototype._transform = function (chunk, encoding, cb) {
32609 throw new Error('_transform() is not implemented');
32610};
32611
32612Transform.prototype._write = function (chunk, encoding, cb) {
32613 var ts = this._transformState;
32614 ts.writecb = cb;
32615 ts.writechunk = chunk;
32616 ts.writeencoding = encoding;
32617 if (!ts.transforming) {
32618 var rs = this._readableState;
32619 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
32620 }
32621};
32622
32623// Doesn't matter what the args are here.
32624// _transform does all the work.
32625// That we got here means that the readable side wants more data.
32626Transform.prototype._read = function (n) {
32627 var ts = this._transformState;
32628
32629 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
32630 ts.transforming = true;
32631 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
32632 } else {
32633 // mark that we need a transform, so that any data that comes in
32634 // will get processed, now that we've asked for it.
32635 ts.needTransform = true;
32636 }
32637};
32638
32639Transform.prototype._destroy = function (err, cb) {
32640 var _this2 = this;
32641
32642 Duplex.prototype._destroy.call(this, err, function (err2) {
32643 cb(err2);
32644 _this2.emit('close');
32645 });
32646};
32647
32648function done(stream, er, data) {
32649 if (er) return stream.emit('error', er);
32650
32651 if (data != null) // single equals check for both `null` and `undefined`
32652 stream.push(data);
32653
32654 // if there's nothing in the write buffer, then that means
32655 // that nothing more will ever be provided
32656 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
32657
32658 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
32659
32660 return stream.push(null);
32661}
32662},{"./_stream_duplex":379,"core-util-is":51,"inherits":116}],383:[function(require,module,exports){
32663(function (process,global,setImmediate){
32664// Copyright Joyent, Inc. and other Node contributors.
32665//
32666// Permission is hereby granted, free of charge, to any person obtaining a
32667// copy of this software and associated documentation files (the
32668// "Software"), to deal in the Software without restriction, including
32669// without limitation the rights to use, copy, modify, merge, publish,
32670// distribute, sublicense, and/or sell copies of the Software, and to permit
32671// persons to whom the Software is furnished to do so, subject to the
32672// following conditions:
32673//
32674// The above copyright notice and this permission notice shall be included
32675// in all copies or substantial portions of the Software.
32676//
32677// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
32678// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32679// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
32680// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
32681// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
32682// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
32683// USE OR OTHER DEALINGS IN THE SOFTWARE.
32684
32685// A bit simpler than readable streams.
32686// Implement an async ._write(chunk, encoding, cb), and it'll handle all
32687// the drain event emission and buffering.
32688
32689'use strict';
32690
32691/*<replacement>*/
32692
32693var pna = require('process-nextick-args');
32694/*</replacement>*/
32695
32696module.exports = Writable;
32697
32698/* <replacement> */
32699function WriteReq(chunk, encoding, cb) {
32700 this.chunk = chunk;
32701 this.encoding = encoding;
32702 this.callback = cb;
32703 this.next = null;
32704}
32705
32706// It seems a linked list but it is not
32707// there will be only 2 of these for each stream
32708function CorkedRequest(state) {
32709 var _this = this;
32710
32711 this.next = null;
32712 this.entry = null;
32713 this.finish = function () {
32714 onCorkedFinish(_this, state);
32715 };
32716}
32717/* </replacement> */
32718
32719/*<replacement>*/
32720var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
32721/*</replacement>*/
32722
32723/*<replacement>*/
32724var Duplex;
32725/*</replacement>*/
32726
32727Writable.WritableState = WritableState;
32728
32729/*<replacement>*/
32730var util = require('core-util-is');
32731util.inherits = require('inherits');
32732/*</replacement>*/
32733
32734/*<replacement>*/
32735var internalUtil = {
32736 deprecate: require('util-deprecate')
32737};
32738/*</replacement>*/
32739
32740/*<replacement>*/
32741var Stream = require('./internal/streams/stream');
32742/*</replacement>*/
32743
32744/*<replacement>*/
32745
32746var Buffer = require('safe-buffer').Buffer;
32747var OurUint8Array = global.Uint8Array || function () {};
32748function _uint8ArrayToBuffer(chunk) {
32749 return Buffer.from(chunk);
32750}
32751function _isUint8Array(obj) {
32752 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
32753}
32754
32755/*</replacement>*/
32756
32757var destroyImpl = require('./internal/streams/destroy');
32758
32759util.inherits(Writable, Stream);
32760
32761function nop() {}
32762
32763function WritableState(options, stream) {
32764 Duplex = Duplex || require('./_stream_duplex');
32765
32766 options = options || {};
32767
32768 // Duplex streams are both readable and writable, but share
32769 // the same options object.
32770 // However, some cases require setting options to different
32771 // values for the readable and the writable sides of the duplex stream.
32772 // These options can be provided separately as readableXXX and writableXXX.
32773 var isDuplex = stream instanceof Duplex;
32774
32775 // object stream flag to indicate whether or not this stream
32776 // contains buffers or objects.
32777 this.objectMode = !!options.objectMode;
32778
32779 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
32780
32781 // the point at which write() starts returning false
32782 // Note: 0 is a valid value, means that we always return false if
32783 // the entire buffer is not flushed immediately on write()
32784 var hwm = options.highWaterMark;
32785 var writableHwm = options.writableHighWaterMark;
32786 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
32787
32788 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
32789
32790 // cast to ints.
32791 this.highWaterMark = Math.floor(this.highWaterMark);
32792
32793 // if _final has been called
32794 this.finalCalled = false;
32795
32796 // drain event flag.
32797 this.needDrain = false;
32798 // at the start of calling end()
32799 this.ending = false;
32800 // when end() has been called, and returned
32801 this.ended = false;
32802 // when 'finish' is emitted
32803 this.finished = false;
32804
32805 // has it been destroyed
32806 this.destroyed = false;
32807
32808 // should we decode strings into buffers before passing to _write?
32809 // this is here so that some node-core streams can optimize string
32810 // handling at a lower level.
32811 var noDecode = options.decodeStrings === false;
32812 this.decodeStrings = !noDecode;
32813
32814 // Crypto is kind of old and crusty. Historically, its default string
32815 // encoding is 'binary' so we have to make this configurable.
32816 // Everything else in the universe uses 'utf8', though.
32817 this.defaultEncoding = options.defaultEncoding || 'utf8';
32818
32819 // not an actual buffer we keep track of, but a measurement
32820 // of how much we're waiting to get pushed to some underlying
32821 // socket or file.
32822 this.length = 0;
32823
32824 // a flag to see when we're in the middle of a write.
32825 this.writing = false;
32826
32827 // when true all writes will be buffered until .uncork() call
32828 this.corked = 0;
32829
32830 // a flag to be able to tell if the onwrite cb is called immediately,
32831 // or on a later tick. We set this to true at first, because any
32832 // actions that shouldn't happen until "later" should generally also
32833 // not happen before the first write call.
32834 this.sync = true;
32835
32836 // a flag to know if we're processing previously buffered items, which
32837 // may call the _write() callback in the same tick, so that we don't
32838 // end up in an overlapped onwrite situation.
32839 this.bufferProcessing = false;
32840
32841 // the callback that's passed to _write(chunk,cb)
32842 this.onwrite = function (er) {
32843 onwrite(stream, er);
32844 };
32845
32846 // the callback that the user supplies to write(chunk,encoding,cb)
32847 this.writecb = null;
32848
32849 // the amount that is being written when _write is called.
32850 this.writelen = 0;
32851
32852 this.bufferedRequest = null;
32853 this.lastBufferedRequest = null;
32854
32855 // number of pending user-supplied write callbacks
32856 // this must be 0 before 'finish' can be emitted
32857 this.pendingcb = 0;
32858
32859 // emit prefinish if the only thing we're waiting for is _write cbs
32860 // This is relevant for synchronous Transform streams
32861 this.prefinished = false;
32862
32863 // True if the error was already emitted and should not be thrown again
32864 this.errorEmitted = false;
32865
32866 // count buffered requests
32867 this.bufferedRequestCount = 0;
32868
32869 // allocate the first CorkedRequest, there is always
32870 // one allocated and free to use, and we maintain at most two
32871 this.corkedRequestsFree = new CorkedRequest(this);
32872}
32873
32874WritableState.prototype.getBuffer = function getBuffer() {
32875 var current = this.bufferedRequest;
32876 var out = [];
32877 while (current) {
32878 out.push(current);
32879 current = current.next;
32880 }
32881 return out;
32882};
32883
32884(function () {
32885 try {
32886 Object.defineProperty(WritableState.prototype, 'buffer', {
32887 get: internalUtil.deprecate(function () {
32888 return this.getBuffer();
32889 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
32890 });
32891 } catch (_) {}
32892})();
32893
32894// Test _writableState for inheritance to account for Duplex streams,
32895// whose prototype chain only points to Readable.
32896var realHasInstance;
32897if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
32898 realHasInstance = Function.prototype[Symbol.hasInstance];
32899 Object.defineProperty(Writable, Symbol.hasInstance, {
32900 value: function (object) {
32901 if (realHasInstance.call(this, object)) return true;
32902 if (this !== Writable) return false;
32903
32904 return object && object._writableState instanceof WritableState;
32905 }
32906 });
32907} else {
32908 realHasInstance = function (object) {
32909 return object instanceof this;
32910 };
32911}
32912
32913function Writable(options) {
32914 Duplex = Duplex || require('./_stream_duplex');
32915
32916 // Writable ctor is applied to Duplexes, too.
32917 // `realHasInstance` is necessary because using plain `instanceof`
32918 // would return false, as no `_writableState` property is attached.
32919
32920 // Trying to use the custom `instanceof` for Writable here will also break the
32921 // Node.js LazyTransform implementation, which has a non-trivial getter for
32922 // `_writableState` that would lead to infinite recursion.
32923 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
32924 return new Writable(options);
32925 }
32926
32927 this._writableState = new WritableState(options, this);
32928
32929 // legacy.
32930 this.writable = true;
32931
32932 if (options) {
32933 if (typeof options.write === 'function') this._write = options.write;
32934
32935 if (typeof options.writev === 'function') this._writev = options.writev;
32936
32937 if (typeof options.destroy === 'function') this._destroy = options.destroy;
32938
32939 if (typeof options.final === 'function') this._final = options.final;
32940 }
32941
32942 Stream.call(this);
32943}
32944
32945// Otherwise people can pipe Writable streams, which is just wrong.
32946Writable.prototype.pipe = function () {
32947 this.emit('error', new Error('Cannot pipe, not readable'));
32948};
32949
32950function writeAfterEnd(stream, cb) {
32951 var er = new Error('write after end');
32952 // TODO: defer error events consistently everywhere, not just the cb
32953 stream.emit('error', er);
32954 pna.nextTick(cb, er);
32955}
32956
32957// Checks that a user-supplied chunk is valid, especially for the particular
32958// mode the stream is in. Currently this means that `null` is never accepted
32959// and undefined/non-string values are only allowed in object mode.
32960function validChunk(stream, state, chunk, cb) {
32961 var valid = true;
32962 var er = false;
32963
32964 if (chunk === null) {
32965 er = new TypeError('May not write null values to stream');
32966 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
32967 er = new TypeError('Invalid non-string/buffer chunk');
32968 }
32969 if (er) {
32970 stream.emit('error', er);
32971 pna.nextTick(cb, er);
32972 valid = false;
32973 }
32974 return valid;
32975}
32976
32977Writable.prototype.write = function (chunk, encoding, cb) {
32978 var state = this._writableState;
32979 var ret = false;
32980 var isBuf = !state.objectMode && _isUint8Array(chunk);
32981
32982 if (isBuf && !Buffer.isBuffer(chunk)) {
32983 chunk = _uint8ArrayToBuffer(chunk);
32984 }
32985
32986 if (typeof encoding === 'function') {
32987 cb = encoding;
32988 encoding = null;
32989 }
32990
32991 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
32992
32993 if (typeof cb !== 'function') cb = nop;
32994
32995 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
32996 state.pendingcb++;
32997 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
32998 }
32999
33000 return ret;
33001};
33002
33003Writable.prototype.cork = function () {
33004 var state = this._writableState;
33005
33006 state.corked++;
33007};
33008
33009Writable.prototype.uncork = function () {
33010 var state = this._writableState;
33011
33012 if (state.corked) {
33013 state.corked--;
33014
33015 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
33016 }
33017};
33018
33019Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
33020 // node::ParseEncoding() requires lower case.
33021 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
33022 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);
33023 this._writableState.defaultEncoding = encoding;
33024 return this;
33025};
33026
33027function decodeChunk(state, chunk, encoding) {
33028 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
33029 chunk = Buffer.from(chunk, encoding);
33030 }
33031 return chunk;
33032}
33033
33034Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
33035 // making it explicit this property is not enumerable
33036 // because otherwise some prototype manipulation in
33037 // userland will fail
33038 enumerable: false,
33039 get: function () {
33040 return this._writableState.highWaterMark;
33041 }
33042});
33043
33044// if we're already writing something, then just put this
33045// in the queue, and wait our turn. Otherwise, call _write
33046// If we return false, then we need a drain event, so set that flag.
33047function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
33048 if (!isBuf) {
33049 var newChunk = decodeChunk(state, chunk, encoding);
33050 if (chunk !== newChunk) {
33051 isBuf = true;
33052 encoding = 'buffer';
33053 chunk = newChunk;
33054 }
33055 }
33056 var len = state.objectMode ? 1 : chunk.length;
33057
33058 state.length += len;
33059
33060 var ret = state.length < state.highWaterMark;
33061 // we must ensure that previous needDrain will not be reset to false.
33062 if (!ret) state.needDrain = true;
33063
33064 if (state.writing || state.corked) {
33065 var last = state.lastBufferedRequest;
33066 state.lastBufferedRequest = {
33067 chunk: chunk,
33068 encoding: encoding,
33069 isBuf: isBuf,
33070 callback: cb,
33071 next: null
33072 };
33073 if (last) {
33074 last.next = state.lastBufferedRequest;
33075 } else {
33076 state.bufferedRequest = state.lastBufferedRequest;
33077 }
33078 state.bufferedRequestCount += 1;
33079 } else {
33080 doWrite(stream, state, false, len, chunk, encoding, cb);
33081 }
33082
33083 return ret;
33084}
33085
33086function doWrite(stream, state, writev, len, chunk, encoding, cb) {
33087 state.writelen = len;
33088 state.writecb = cb;
33089 state.writing = true;
33090 state.sync = true;
33091 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
33092 state.sync = false;
33093}
33094
33095function onwriteError(stream, state, sync, er, cb) {
33096 --state.pendingcb;
33097
33098 if (sync) {
33099 // defer the callback if we are being called synchronously
33100 // to avoid piling up things on the stack
33101 pna.nextTick(cb, er);
33102 // this can emit finish, and it will always happen
33103 // after error
33104 pna.nextTick(finishMaybe, stream, state);
33105 stream._writableState.errorEmitted = true;
33106 stream.emit('error', er);
33107 } else {
33108 // the caller expect this to happen before if
33109 // it is async
33110 cb(er);
33111 stream._writableState.errorEmitted = true;
33112 stream.emit('error', er);
33113 // this can emit finish, but finish must
33114 // always follow error
33115 finishMaybe(stream, state);
33116 }
33117}
33118
33119function onwriteStateUpdate(state) {
33120 state.writing = false;
33121 state.writecb = null;
33122 state.length -= state.writelen;
33123 state.writelen = 0;
33124}
33125
33126function onwrite(stream, er) {
33127 var state = stream._writableState;
33128 var sync = state.sync;
33129 var cb = state.writecb;
33130
33131 onwriteStateUpdate(state);
33132
33133 if (er) onwriteError(stream, state, sync, er, cb);else {
33134 // Check if we're actually ready to finish, but don't emit yet
33135 var finished = needFinish(state);
33136
33137 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
33138 clearBuffer(stream, state);
33139 }
33140
33141 if (sync) {
33142 /*<replacement>*/
33143 asyncWrite(afterWrite, stream, state, finished, cb);
33144 /*</replacement>*/
33145 } else {
33146 afterWrite(stream, state, finished, cb);
33147 }
33148 }
33149}
33150
33151function afterWrite(stream, state, finished, cb) {
33152 if (!finished) onwriteDrain(stream, state);
33153 state.pendingcb--;
33154 cb();
33155 finishMaybe(stream, state);
33156}
33157
33158// Must force callback to be called on nextTick, so that we don't
33159// emit 'drain' before the write() consumer gets the 'false' return
33160// value, and has a chance to attach a 'drain' listener.
33161function onwriteDrain(stream, state) {
33162 if (state.length === 0 && state.needDrain) {
33163 state.needDrain = false;
33164 stream.emit('drain');
33165 }
33166}
33167
33168// if there's something in the buffer waiting, then process it
33169function clearBuffer(stream, state) {
33170 state.bufferProcessing = true;
33171 var entry = state.bufferedRequest;
33172
33173 if (stream._writev && entry && entry.next) {
33174 // Fast case, write everything using _writev()
33175 var l = state.bufferedRequestCount;
33176 var buffer = new Array(l);
33177 var holder = state.corkedRequestsFree;
33178 holder.entry = entry;
33179
33180 var count = 0;
33181 var allBuffers = true;
33182 while (entry) {
33183 buffer[count] = entry;
33184 if (!entry.isBuf) allBuffers = false;
33185 entry = entry.next;
33186 count += 1;
33187 }
33188 buffer.allBuffers = allBuffers;
33189
33190 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
33191
33192 // doWrite is almost always async, defer these to save a bit of time
33193 // as the hot path ends with doWrite
33194 state.pendingcb++;
33195 state.lastBufferedRequest = null;
33196 if (holder.next) {
33197 state.corkedRequestsFree = holder.next;
33198 holder.next = null;
33199 } else {
33200 state.corkedRequestsFree = new CorkedRequest(state);
33201 }
33202 state.bufferedRequestCount = 0;
33203 } else {
33204 // Slow case, write chunks one-by-one
33205 while (entry) {
33206 var chunk = entry.chunk;
33207 var encoding = entry.encoding;
33208 var cb = entry.callback;
33209 var len = state.objectMode ? 1 : chunk.length;
33210
33211 doWrite(stream, state, false, len, chunk, encoding, cb);
33212 entry = entry.next;
33213 state.bufferedRequestCount--;
33214 // if we didn't call the onwrite immediately, then
33215 // it means that we need to wait until it does.
33216 // also, that means that the chunk and cb are currently
33217 // being processed, so move the buffer counter past them.
33218 if (state.writing) {
33219 break;
33220 }
33221 }
33222
33223 if (entry === null) state.lastBufferedRequest = null;
33224 }
33225
33226 state.bufferedRequest = entry;
33227 state.bufferProcessing = false;
33228}
33229
33230Writable.prototype._write = function (chunk, encoding, cb) {
33231 cb(new Error('_write() is not implemented'));
33232};
33233
33234Writable.prototype._writev = null;
33235
33236Writable.prototype.end = function (chunk, encoding, cb) {
33237 var state = this._writableState;
33238
33239 if (typeof chunk === 'function') {
33240 cb = chunk;
33241 chunk = null;
33242 encoding = null;
33243 } else if (typeof encoding === 'function') {
33244 cb = encoding;
33245 encoding = null;
33246 }
33247
33248 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
33249
33250 // .end() fully uncorks
33251 if (state.corked) {
33252 state.corked = 1;
33253 this.uncork();
33254 }
33255
33256 // ignore unnecessary end() calls.
33257 if (!state.ending && !state.finished) endWritable(this, state, cb);
33258};
33259
33260function needFinish(state) {
33261 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
33262}
33263function callFinal(stream, state) {
33264 stream._final(function (err) {
33265 state.pendingcb--;
33266 if (err) {
33267 stream.emit('error', err);
33268 }
33269 state.prefinished = true;
33270 stream.emit('prefinish');
33271 finishMaybe(stream, state);
33272 });
33273}
33274function prefinish(stream, state) {
33275 if (!state.prefinished && !state.finalCalled) {
33276 if (typeof stream._final === 'function') {
33277 state.pendingcb++;
33278 state.finalCalled = true;
33279 pna.nextTick(callFinal, stream, state);
33280 } else {
33281 state.prefinished = true;
33282 stream.emit('prefinish');
33283 }
33284 }
33285}
33286
33287function finishMaybe(stream, state) {
33288 var need = needFinish(state);
33289 if (need) {
33290 prefinish(stream, state);
33291 if (state.pendingcb === 0) {
33292 state.finished = true;
33293 stream.emit('finish');
33294 }
33295 }
33296 return need;
33297}
33298
33299function endWritable(stream, state, cb) {
33300 state.ending = true;
33301 finishMaybe(stream, state);
33302 if (cb) {
33303 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
33304 }
33305 state.ended = true;
33306 stream.writable = false;
33307}
33308
33309function onCorkedFinish(corkReq, state, err) {
33310 var entry = corkReq.entry;
33311 corkReq.entry = null;
33312 while (entry) {
33313 var cb = entry.callback;
33314 state.pendingcb--;
33315 cb(err);
33316 entry = entry.next;
33317 }
33318 if (state.corkedRequestsFree) {
33319 state.corkedRequestsFree.next = corkReq;
33320 } else {
33321 state.corkedRequestsFree = corkReq;
33322 }
33323}
33324
33325Object.defineProperty(Writable.prototype, 'destroyed', {
33326 get: function () {
33327 if (this._writableState === undefined) {
33328 return false;
33329 }
33330 return this._writableState.destroyed;
33331 },
33332 set: function (value) {
33333 // we ignore the value if the stream
33334 // has not been initialized yet
33335 if (!this._writableState) {
33336 return;
33337 }
33338
33339 // backward compatibility, the user is explicitly
33340 // managing destroyed
33341 this._writableState.destroyed = value;
33342 }
33343});
33344
33345Writable.prototype.destroy = destroyImpl.destroy;
33346Writable.prototype._undestroy = destroyImpl.undestroy;
33347Writable.prototype._destroy = function (err, cb) {
33348 this.end();
33349 cb(err);
33350};
33351}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
33352},{"./_stream_duplex":379,"./internal/streams/destroy":385,"./internal/streams/stream":386,"_process":369,"core-util-is":51,"inherits":116,"process-nextick-args":368,"safe-buffer":393,"timers":434,"util-deprecate":436}],384:[function(require,module,exports){
33353'use strict';
33354
33355function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
33356
33357var Buffer = require('safe-buffer').Buffer;
33358var util = require('util');
33359
33360function copyBuffer(src, target, offset) {
33361 src.copy(target, offset);
33362}
33363
33364module.exports = function () {
33365 function BufferList() {
33366 _classCallCheck(this, BufferList);
33367
33368 this.head = null;
33369 this.tail = null;
33370 this.length = 0;
33371 }
33372
33373 BufferList.prototype.push = function push(v) {
33374 var entry = { data: v, next: null };
33375 if (this.length > 0) this.tail.next = entry;else this.head = entry;
33376 this.tail = entry;
33377 ++this.length;
33378 };
33379
33380 BufferList.prototype.unshift = function unshift(v) {
33381 var entry = { data: v, next: this.head };
33382 if (this.length === 0) this.tail = entry;
33383 this.head = entry;
33384 ++this.length;
33385 };
33386
33387 BufferList.prototype.shift = function shift() {
33388 if (this.length === 0) return;
33389 var ret = this.head.data;
33390 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
33391 --this.length;
33392 return ret;
33393 };
33394
33395 BufferList.prototype.clear = function clear() {
33396 this.head = this.tail = null;
33397 this.length = 0;
33398 };
33399
33400 BufferList.prototype.join = function join(s) {
33401 if (this.length === 0) return '';
33402 var p = this.head;
33403 var ret = '' + p.data;
33404 while (p = p.next) {
33405 ret += s + p.data;
33406 }return ret;
33407 };
33408
33409 BufferList.prototype.concat = function concat(n) {
33410 if (this.length === 0) return Buffer.alloc(0);
33411 if (this.length === 1) return this.head.data;
33412 var ret = Buffer.allocUnsafe(n >>> 0);
33413 var p = this.head;
33414 var i = 0;
33415 while (p) {
33416 copyBuffer(p.data, ret, i);
33417 i += p.data.length;
33418 p = p.next;
33419 }
33420 return ret;
33421 };
33422
33423 return BufferList;
33424}();
33425
33426if (util && util.inspect && util.inspect.custom) {
33427 module.exports.prototype[util.inspect.custom] = function () {
33428 var obj = util.inspect({ length: this.length });
33429 return this.constructor.name + ' ' + obj;
33430 };
33431}
33432},{"safe-buffer":393,"util":20}],385:[function(require,module,exports){
33433'use strict';
33434
33435/*<replacement>*/
33436
33437var pna = require('process-nextick-args');
33438/*</replacement>*/
33439
33440// undocumented cb() API, needed for core, not for public API
33441function destroy(err, cb) {
33442 var _this = this;
33443
33444 var readableDestroyed = this._readableState && this._readableState.destroyed;
33445 var writableDestroyed = this._writableState && this._writableState.destroyed;
33446
33447 if (readableDestroyed || writableDestroyed) {
33448 if (cb) {
33449 cb(err);
33450 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
33451 pna.nextTick(emitErrorNT, this, err);
33452 }
33453 return this;
33454 }
33455
33456 // we set destroyed to true before firing error callbacks in order
33457 // to make it re-entrance safe in case destroy() is called within callbacks
33458
33459 if (this._readableState) {
33460 this._readableState.destroyed = true;
33461 }
33462
33463 // if this is a duplex stream mark the writable part as destroyed as well
33464 if (this._writableState) {
33465 this._writableState.destroyed = true;
33466 }
33467
33468 this._destroy(err || null, function (err) {
33469 if (!cb && err) {
33470 pna.nextTick(emitErrorNT, _this, err);
33471 if (_this._writableState) {
33472 _this._writableState.errorEmitted = true;
33473 }
33474 } else if (cb) {
33475 cb(err);
33476 }
33477 });
33478
33479 return this;
33480}
33481
33482function undestroy() {
33483 if (this._readableState) {
33484 this._readableState.destroyed = false;
33485 this._readableState.reading = false;
33486 this._readableState.ended = false;
33487 this._readableState.endEmitted = false;
33488 }
33489
33490 if (this._writableState) {
33491 this._writableState.destroyed = false;
33492 this._writableState.ended = false;
33493 this._writableState.ending = false;
33494 this._writableState.finished = false;
33495 this._writableState.errorEmitted = false;
33496 }
33497}
33498
33499function emitErrorNT(self, err) {
33500 self.emit('error', err);
33501}
33502
33503module.exports = {
33504 destroy: destroy,
33505 undestroy: undestroy
33506};
33507},{"process-nextick-args":368}],386:[function(require,module,exports){
33508module.exports = require('events').EventEmitter;
33509
33510},{"events":99}],387:[function(require,module,exports){
33511// Copyright Joyent, Inc. and other Node contributors.
33512//
33513// Permission is hereby granted, free of charge, to any person obtaining a
33514// copy of this software and associated documentation files (the
33515// "Software"), to deal in the Software without restriction, including
33516// without limitation the rights to use, copy, modify, merge, publish,
33517// distribute, sublicense, and/or sell copies of the Software, and to permit
33518// persons to whom the Software is furnished to do so, subject to the
33519// following conditions:
33520//
33521// The above copyright notice and this permission notice shall be included
33522// in all copies or substantial portions of the Software.
33523//
33524// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
33525// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33526// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
33527// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
33528// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
33529// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
33530// USE OR OTHER DEALINGS IN THE SOFTWARE.
33531
33532'use strict';
33533
33534/*<replacement>*/
33535
33536var Buffer = require('safe-buffer').Buffer;
33537/*</replacement>*/
33538
33539var isEncoding = Buffer.isEncoding || function (encoding) {
33540 encoding = '' + encoding;
33541 switch (encoding && encoding.toLowerCase()) {
33542 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':
33543 return true;
33544 default:
33545 return false;
33546 }
33547};
33548
33549function _normalizeEncoding(enc) {
33550 if (!enc) return 'utf8';
33551 var retried;
33552 while (true) {
33553 switch (enc) {
33554 case 'utf8':
33555 case 'utf-8':
33556 return 'utf8';
33557 case 'ucs2':
33558 case 'ucs-2':
33559 case 'utf16le':
33560 case 'utf-16le':
33561 return 'utf16le';
33562 case 'latin1':
33563 case 'binary':
33564 return 'latin1';
33565 case 'base64':
33566 case 'ascii':
33567 case 'hex':
33568 return enc;
33569 default:
33570 if (retried) return; // undefined
33571 enc = ('' + enc).toLowerCase();
33572 retried = true;
33573 }
33574 }
33575};
33576
33577// Do not cache `Buffer.isEncoding` when checking encoding names as some
33578// modules monkey-patch it to support additional encodings
33579function normalizeEncoding(enc) {
33580 var nenc = _normalizeEncoding(enc);
33581 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
33582 return nenc || enc;
33583}
33584
33585// StringDecoder provides an interface for efficiently splitting a series of
33586// buffers into a series of JS strings without breaking apart multi-byte
33587// characters.
33588exports.StringDecoder = StringDecoder;
33589function StringDecoder(encoding) {
33590 this.encoding = normalizeEncoding(encoding);
33591 var nb;
33592 switch (this.encoding) {
33593 case 'utf16le':
33594 this.text = utf16Text;
33595 this.end = utf16End;
33596 nb = 4;
33597 break;
33598 case 'utf8':
33599 this.fillLast = utf8FillLast;
33600 nb = 4;
33601 break;
33602 case 'base64':
33603 this.text = base64Text;
33604 this.end = base64End;
33605 nb = 3;
33606 break;
33607 default:
33608 this.write = simpleWrite;
33609 this.end = simpleEnd;
33610 return;
33611 }
33612 this.lastNeed = 0;
33613 this.lastTotal = 0;
33614 this.lastChar = Buffer.allocUnsafe(nb);
33615}
33616
33617StringDecoder.prototype.write = function (buf) {
33618 if (buf.length === 0) return '';
33619 var r;
33620 var i;
33621 if (this.lastNeed) {
33622 r = this.fillLast(buf);
33623 if (r === undefined) return '';
33624 i = this.lastNeed;
33625 this.lastNeed = 0;
33626 } else {
33627 i = 0;
33628 }
33629 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
33630 return r || '';
33631};
33632
33633StringDecoder.prototype.end = utf8End;
33634
33635// Returns only complete characters in a Buffer
33636StringDecoder.prototype.text = utf8Text;
33637
33638// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
33639StringDecoder.prototype.fillLast = function (buf) {
33640 if (this.lastNeed <= buf.length) {
33641 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
33642 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
33643 }
33644 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
33645 this.lastNeed -= buf.length;
33646};
33647
33648// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
33649// continuation byte. If an invalid byte is detected, -2 is returned.
33650function utf8CheckByte(byte) {
33651 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;
33652 return byte >> 6 === 0x02 ? -1 : -2;
33653}
33654
33655// Checks at most 3 bytes at the end of a Buffer in order to detect an
33656// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
33657// needed to complete the UTF-8 character (if applicable) are returned.
33658function utf8CheckIncomplete(self, buf, i) {
33659 var j = buf.length - 1;
33660 if (j < i) return 0;
33661 var nb = utf8CheckByte(buf[j]);
33662 if (nb >= 0) {
33663 if (nb > 0) self.lastNeed = nb - 1;
33664 return nb;
33665 }
33666 if (--j < i || nb === -2) return 0;
33667 nb = utf8CheckByte(buf[j]);
33668 if (nb >= 0) {
33669 if (nb > 0) self.lastNeed = nb - 2;
33670 return nb;
33671 }
33672 if (--j < i || nb === -2) return 0;
33673 nb = utf8CheckByte(buf[j]);
33674 if (nb >= 0) {
33675 if (nb > 0) {
33676 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
33677 }
33678 return nb;
33679 }
33680 return 0;
33681}
33682
33683// Validates as many continuation bytes for a multi-byte UTF-8 character as
33684// needed or are available. If we see a non-continuation byte where we expect
33685// one, we "replace" the validated continuation bytes we've seen so far with
33686// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
33687// behavior. The continuation byte check is included three times in the case
33688// where all of the continuation bytes for a character exist in the same buffer.
33689// It is also done this way as a slight performance increase instead of using a
33690// loop.
33691function utf8CheckExtraBytes(self, buf, p) {
33692 if ((buf[0] & 0xC0) !== 0x80) {
33693 self.lastNeed = 0;
33694 return '\ufffd';
33695 }
33696 if (self.lastNeed > 1 && buf.length > 1) {
33697 if ((buf[1] & 0xC0) !== 0x80) {
33698 self.lastNeed = 1;
33699 return '\ufffd';
33700 }
33701 if (self.lastNeed > 2 && buf.length > 2) {
33702 if ((buf[2] & 0xC0) !== 0x80) {
33703 self.lastNeed = 2;
33704 return '\ufffd';
33705 }
33706 }
33707 }
33708}
33709
33710// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
33711function utf8FillLast(buf) {
33712 var p = this.lastTotal - this.lastNeed;
33713 var r = utf8CheckExtraBytes(this, buf, p);
33714 if (r !== undefined) return r;
33715 if (this.lastNeed <= buf.length) {
33716 buf.copy(this.lastChar, p, 0, this.lastNeed);
33717 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
33718 }
33719 buf.copy(this.lastChar, p, 0, buf.length);
33720 this.lastNeed -= buf.length;
33721}
33722
33723// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
33724// partial character, the character's bytes are buffered until the required
33725// number of bytes are available.
33726function utf8Text(buf, i) {
33727 var total = utf8CheckIncomplete(this, buf, i);
33728 if (!this.lastNeed) return buf.toString('utf8', i);
33729 this.lastTotal = total;
33730 var end = buf.length - (total - this.lastNeed);
33731 buf.copy(this.lastChar, 0, end);
33732 return buf.toString('utf8', i, end);
33733}
33734
33735// For UTF-8, a replacement character is added when ending on a partial
33736// character.
33737function utf8End(buf) {
33738 var r = buf && buf.length ? this.write(buf) : '';
33739 if (this.lastNeed) return r + '\ufffd';
33740 return r;
33741}
33742
33743// UTF-16LE typically needs two bytes per character, but even if we have an even
33744// number of bytes available, we need to check if we end on a leading/high
33745// surrogate. In that case, we need to wait for the next two bytes in order to
33746// decode the last character properly.
33747function utf16Text(buf, i) {
33748 if ((buf.length - i) % 2 === 0) {
33749 var r = buf.toString('utf16le', i);
33750 if (r) {
33751 var c = r.charCodeAt(r.length - 1);
33752 if (c >= 0xD800 && c <= 0xDBFF) {
33753 this.lastNeed = 2;
33754 this.lastTotal = 4;
33755 this.lastChar[0] = buf[buf.length - 2];
33756 this.lastChar[1] = buf[buf.length - 1];
33757 return r.slice(0, -1);
33758 }
33759 }
33760 return r;
33761 }
33762 this.lastNeed = 1;
33763 this.lastTotal = 2;
33764 this.lastChar[0] = buf[buf.length - 1];
33765 return buf.toString('utf16le', i, buf.length - 1);
33766}
33767
33768// For UTF-16LE we do not explicitly append special replacement characters if we
33769// end on a partial character, we simply let v8 handle that.
33770function utf16End(buf) {
33771 var r = buf && buf.length ? this.write(buf) : '';
33772 if (this.lastNeed) {
33773 var end = this.lastTotal - this.lastNeed;
33774 return r + this.lastChar.toString('utf16le', 0, end);
33775 }
33776 return r;
33777}
33778
33779function base64Text(buf, i) {
33780 var n = (buf.length - i) % 3;
33781 if (n === 0) return buf.toString('base64', i);
33782 this.lastNeed = 3 - n;
33783 this.lastTotal = 3;
33784 if (n === 1) {
33785 this.lastChar[0] = buf[buf.length - 1];
33786 } else {
33787 this.lastChar[0] = buf[buf.length - 2];
33788 this.lastChar[1] = buf[buf.length - 1];
33789 }
33790 return buf.toString('base64', i, buf.length - n);
33791}
33792
33793function base64End(buf) {
33794 var r = buf && buf.length ? this.write(buf) : '';
33795 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
33796 return r;
33797}
33798
33799// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
33800function simpleWrite(buf) {
33801 return buf.toString(this.encoding);
33802}
33803
33804function simpleEnd(buf) {
33805 return buf && buf.length ? this.write(buf) : '';
33806}
33807},{"safe-buffer":393}],388:[function(require,module,exports){
33808module.exports = require('./readable').PassThrough
33809
33810},{"./readable":389}],389:[function(require,module,exports){
33811exports = module.exports = require('./lib/_stream_readable.js');
33812exports.Stream = exports;
33813exports.Readable = exports;
33814exports.Writable = require('./lib/_stream_writable.js');
33815exports.Duplex = require('./lib/_stream_duplex.js');
33816exports.Transform = require('./lib/_stream_transform.js');
33817exports.PassThrough = require('./lib/_stream_passthrough.js');
33818
33819},{"./lib/_stream_duplex.js":379,"./lib/_stream_passthrough.js":380,"./lib/_stream_readable.js":381,"./lib/_stream_transform.js":382,"./lib/_stream_writable.js":383}],390:[function(require,module,exports){
33820module.exports = require('./readable').Transform
33821
33822},{"./readable":389}],391:[function(require,module,exports){
33823module.exports = require('./lib/_stream_writable.js');
33824
33825},{"./lib/_stream_writable.js":383}],392:[function(require,module,exports){
33826'use strict'
33827var Buffer = require('buffer').Buffer
33828var inherits = require('inherits')
33829var HashBase = require('hash-base')
33830
33831var ARRAY16 = new Array(16)
33832
33833var zl = [
33834 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
33835 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
33836 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
33837 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
33838 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
33839]
33840
33841var zr = [
33842 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
33843 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
33844 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
33845 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
33846 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
33847]
33848
33849var sl = [
33850 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
33851 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
33852 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
33853 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
33854 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
33855]
33856
33857var sr = [
33858 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
33859 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
33860 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
33861 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
33862 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
33863]
33864
33865var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
33866var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]
33867
33868function RIPEMD160 () {
33869 HashBase.call(this, 64)
33870
33871 // state
33872 this._a = 0x67452301
33873 this._b = 0xefcdab89
33874 this._c = 0x98badcfe
33875 this._d = 0x10325476
33876 this._e = 0xc3d2e1f0
33877}
33878
33879inherits(RIPEMD160, HashBase)
33880
33881RIPEMD160.prototype._update = function () {
33882 var words = ARRAY16
33883 for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)
33884
33885 var al = this._a | 0
33886 var bl = this._b | 0
33887 var cl = this._c | 0
33888 var dl = this._d | 0
33889 var el = this._e | 0
33890
33891 var ar = this._a | 0
33892 var br = this._b | 0
33893 var cr = this._c | 0
33894 var dr = this._d | 0
33895 var er = this._e | 0
33896
33897 // computation
33898 for (var i = 0; i < 80; i += 1) {
33899 var tl
33900 var tr
33901 if (i < 16) {
33902 tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
33903 tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
33904 } else if (i < 32) {
33905 tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
33906 tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
33907 } else if (i < 48) {
33908 tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
33909 tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
33910 } else if (i < 64) {
33911 tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
33912 tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
33913 } else { // if (i<80) {
33914 tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
33915 tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
33916 }
33917
33918 al = el
33919 el = dl
33920 dl = rotl(cl, 10)
33921 cl = bl
33922 bl = tl
33923
33924 ar = er
33925 er = dr
33926 dr = rotl(cr, 10)
33927 cr = br
33928 br = tr
33929 }
33930
33931 // update state
33932 var t = (this._b + cl + dr) | 0
33933 this._b = (this._c + dl + er) | 0
33934 this._c = (this._d + el + ar) | 0
33935 this._d = (this._e + al + br) | 0
33936 this._e = (this._a + bl + cr) | 0
33937 this._a = t
33938}
33939
33940RIPEMD160.prototype._digest = function () {
33941 // create padding and handle blocks
33942 this._block[this._blockOffset++] = 0x80
33943 if (this._blockOffset > 56) {
33944 this._block.fill(0, this._blockOffset, 64)
33945 this._update()
33946 this._blockOffset = 0
33947 }
33948
33949 this._block.fill(0, this._blockOffset, 56)
33950 this._block.writeUInt32LE(this._length[0], 56)
33951 this._block.writeUInt32LE(this._length[1], 60)
33952 this._update()
33953
33954 // produce result
33955 var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
33956 buffer.writeInt32LE(this._a, 0)
33957 buffer.writeInt32LE(this._b, 4)
33958 buffer.writeInt32LE(this._c, 8)
33959 buffer.writeInt32LE(this._d, 12)
33960 buffer.writeInt32LE(this._e, 16)
33961 return buffer
33962}
33963
33964function rotl (x, n) {
33965 return (x << n) | (x >>> (32 - n))
33966}
33967
33968function fn1 (a, b, c, d, e, m, k, s) {
33969 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
33970}
33971
33972function fn2 (a, b, c, d, e, m, k, s) {
33973 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
33974}
33975
33976function fn3 (a, b, c, d, e, m, k, s) {
33977 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
33978}
33979
33980function fn4 (a, b, c, d, e, m, k, s) {
33981 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
33982}
33983
33984function fn5 (a, b, c, d, e, m, k, s) {
33985 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
33986}
33987
33988module.exports = RIPEMD160
33989
33990},{"buffer":49,"hash-base":101,"inherits":116}],393:[function(require,module,exports){
33991/* eslint-disable node/no-deprecated-api */
33992var buffer = require('buffer')
33993var Buffer = buffer.Buffer
33994
33995// alternative to using Object.keys for old browsers
33996function copyProps (src, dst) {
33997 for (var key in src) {
33998 dst[key] = src[key]
33999 }
34000}
34001if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
34002 module.exports = buffer
34003} else {
34004 // Copy properties from require('buffer')
34005 copyProps(buffer, exports)
34006 exports.Buffer = SafeBuffer
34007}
34008
34009function SafeBuffer (arg, encodingOrOffset, length) {
34010 return Buffer(arg, encodingOrOffset, length)
34011}
34012
34013// Copy static methods from Buffer
34014copyProps(Buffer, SafeBuffer)
34015
34016SafeBuffer.from = function (arg, encodingOrOffset, length) {
34017 if (typeof arg === 'number') {
34018 throw new TypeError('Argument must not be a number')
34019 }
34020 return Buffer(arg, encodingOrOffset, length)
34021}
34022
34023SafeBuffer.alloc = function (size, fill, encoding) {
34024 if (typeof size !== 'number') {
34025 throw new TypeError('Argument must be a number')
34026 }
34027 var buf = Buffer(size)
34028 if (fill !== undefined) {
34029 if (typeof encoding === 'string') {
34030 buf.fill(fill, encoding)
34031 } else {
34032 buf.fill(fill)
34033 }
34034 } else {
34035 buf.fill(0)
34036 }
34037 return buf
34038}
34039
34040SafeBuffer.allocUnsafe = function (size) {
34041 if (typeof size !== 'number') {
34042 throw new TypeError('Argument must be a number')
34043 }
34044 return Buffer(size)
34045}
34046
34047SafeBuffer.allocUnsafeSlow = function (size) {
34048 if (typeof size !== 'number') {
34049 throw new TypeError('Argument must be a number')
34050 }
34051 return buffer.SlowBuffer(size)
34052}
34053
34054},{"buffer":49}],394:[function(require,module,exports){
34055var Buffer = require('safe-buffer').Buffer
34056
34057// prototype class for hash functions
34058function Hash (blockSize, finalSize) {
34059 this._block = Buffer.alloc(blockSize)
34060 this._finalSize = finalSize
34061 this._blockSize = blockSize
34062 this._len = 0
34063}
34064
34065Hash.prototype.update = function (data, enc) {
34066 if (typeof data === 'string') {
34067 enc = enc || 'utf8'
34068 data = Buffer.from(data, enc)
34069 }
34070
34071 var block = this._block
34072 var blockSize = this._blockSize
34073 var length = data.length
34074 var accum = this._len
34075
34076 for (var offset = 0; offset < length;) {
34077 var assigned = accum % blockSize
34078 var remainder = Math.min(length - offset, blockSize - assigned)
34079
34080 for (var i = 0; i < remainder; i++) {
34081 block[assigned + i] = data[offset + i]
34082 }
34083
34084 accum += remainder
34085 offset += remainder
34086
34087 if ((accum % blockSize) === 0) {
34088 this._update(block)
34089 }
34090 }
34091
34092 this._len += length
34093 return this
34094}
34095
34096Hash.prototype.digest = function (enc) {
34097 var rem = this._len % this._blockSize
34098
34099 this._block[rem] = 0x80
34100
34101 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
34102 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
34103 this._block.fill(0, rem + 1)
34104
34105 if (rem >= this._finalSize) {
34106 this._update(this._block)
34107 this._block.fill(0)
34108 }
34109
34110 var bits = this._len * 8
34111
34112 // uint32
34113 if (bits <= 0xffffffff) {
34114 this._block.writeUInt32BE(bits, this._blockSize - 4)
34115
34116 // uint64
34117 } else {
34118 var lowBits = (bits & 0xffffffff) >>> 0
34119 var highBits = (bits - lowBits) / 0x100000000
34120
34121 this._block.writeUInt32BE(highBits, this._blockSize - 8)
34122 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
34123 }
34124
34125 this._update(this._block)
34126 var hash = this._hash()
34127
34128 return enc ? hash.toString(enc) : hash
34129}
34130
34131Hash.prototype._update = function () {
34132 throw new Error('_update must be implemented by subclass')
34133}
34134
34135module.exports = Hash
34136
34137},{"safe-buffer":393}],395:[function(require,module,exports){
34138var exports = module.exports = function SHA (algorithm) {
34139 algorithm = algorithm.toLowerCase()
34140
34141 var Algorithm = exports[algorithm]
34142 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
34143
34144 return new Algorithm()
34145}
34146
34147exports.sha = require('./sha')
34148exports.sha1 = require('./sha1')
34149exports.sha224 = require('./sha224')
34150exports.sha256 = require('./sha256')
34151exports.sha384 = require('./sha384')
34152exports.sha512 = require('./sha512')
34153
34154},{"./sha":396,"./sha1":397,"./sha224":398,"./sha256":399,"./sha384":400,"./sha512":401}],396:[function(require,module,exports){
34155/*
34156 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
34157 * in FIPS PUB 180-1
34158 * This source code is derived from sha1.js of the same repository.
34159 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
34160 * operation was added.
34161 */
34162
34163var inherits = require('inherits')
34164var Hash = require('./hash')
34165var Buffer = require('safe-buffer').Buffer
34166
34167var K = [
34168 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
34169]
34170
34171var W = new Array(80)
34172
34173function Sha () {
34174 this.init()
34175 this._w = W
34176
34177 Hash.call(this, 64, 56)
34178}
34179
34180inherits(Sha, Hash)
34181
34182Sha.prototype.init = function () {
34183 this._a = 0x67452301
34184 this._b = 0xefcdab89
34185 this._c = 0x98badcfe
34186 this._d = 0x10325476
34187 this._e = 0xc3d2e1f0
34188
34189 return this
34190}
34191
34192function rotl5 (num) {
34193 return (num << 5) | (num >>> 27)
34194}
34195
34196function rotl30 (num) {
34197 return (num << 30) | (num >>> 2)
34198}
34199
34200function ft (s, b, c, d) {
34201 if (s === 0) return (b & c) | ((~b) & d)
34202 if (s === 2) return (b & c) | (b & d) | (c & d)
34203 return b ^ c ^ d
34204}
34205
34206Sha.prototype._update = function (M) {
34207 var W = this._w
34208
34209 var a = this._a | 0
34210 var b = this._b | 0
34211 var c = this._c | 0
34212 var d = this._d | 0
34213 var e = this._e | 0
34214
34215 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
34216 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
34217
34218 for (var j = 0; j < 80; ++j) {
34219 var s = ~~(j / 20)
34220 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
34221
34222 e = d
34223 d = c
34224 c = rotl30(b)
34225 b = a
34226 a = t
34227 }
34228
34229 this._a = (a + this._a) | 0
34230 this._b = (b + this._b) | 0
34231 this._c = (c + this._c) | 0
34232 this._d = (d + this._d) | 0
34233 this._e = (e + this._e) | 0
34234}
34235
34236Sha.prototype._hash = function () {
34237 var H = Buffer.allocUnsafe(20)
34238
34239 H.writeInt32BE(this._a | 0, 0)
34240 H.writeInt32BE(this._b | 0, 4)
34241 H.writeInt32BE(this._c | 0, 8)
34242 H.writeInt32BE(this._d | 0, 12)
34243 H.writeInt32BE(this._e | 0, 16)
34244
34245 return H
34246}
34247
34248module.exports = Sha
34249
34250},{"./hash":394,"inherits":116,"safe-buffer":393}],397:[function(require,module,exports){
34251/*
34252 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
34253 * in FIPS PUB 180-1
34254 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
34255 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
34256 * Distributed under the BSD License
34257 * See http://pajhome.org.uk/crypt/md5 for details.
34258 */
34259
34260var inherits = require('inherits')
34261var Hash = require('./hash')
34262var Buffer = require('safe-buffer').Buffer
34263
34264var K = [
34265 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
34266]
34267
34268var W = new Array(80)
34269
34270function Sha1 () {
34271 this.init()
34272 this._w = W
34273
34274 Hash.call(this, 64, 56)
34275}
34276
34277inherits(Sha1, Hash)
34278
34279Sha1.prototype.init = function () {
34280 this._a = 0x67452301
34281 this._b = 0xefcdab89
34282 this._c = 0x98badcfe
34283 this._d = 0x10325476
34284 this._e = 0xc3d2e1f0
34285
34286 return this
34287}
34288
34289function rotl1 (num) {
34290 return (num << 1) | (num >>> 31)
34291}
34292
34293function rotl5 (num) {
34294 return (num << 5) | (num >>> 27)
34295}
34296
34297function rotl30 (num) {
34298 return (num << 30) | (num >>> 2)
34299}
34300
34301function ft (s, b, c, d) {
34302 if (s === 0) return (b & c) | ((~b) & d)
34303 if (s === 2) return (b & c) | (b & d) | (c & d)
34304 return b ^ c ^ d
34305}
34306
34307Sha1.prototype._update = function (M) {
34308 var W = this._w
34309
34310 var a = this._a | 0
34311 var b = this._b | 0
34312 var c = this._c | 0
34313 var d = this._d | 0
34314 var e = this._e | 0
34315
34316 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
34317 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
34318
34319 for (var j = 0; j < 80; ++j) {
34320 var s = ~~(j / 20)
34321 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
34322
34323 e = d
34324 d = c
34325 c = rotl30(b)
34326 b = a
34327 a = t
34328 }
34329
34330 this._a = (a + this._a) | 0
34331 this._b = (b + this._b) | 0
34332 this._c = (c + this._c) | 0
34333 this._d = (d + this._d) | 0
34334 this._e = (e + this._e) | 0
34335}
34336
34337Sha1.prototype._hash = function () {
34338 var H = Buffer.allocUnsafe(20)
34339
34340 H.writeInt32BE(this._a | 0, 0)
34341 H.writeInt32BE(this._b | 0, 4)
34342 H.writeInt32BE(this._c | 0, 8)
34343 H.writeInt32BE(this._d | 0, 12)
34344 H.writeInt32BE(this._e | 0, 16)
34345
34346 return H
34347}
34348
34349module.exports = Sha1
34350
34351},{"./hash":394,"inherits":116,"safe-buffer":393}],398:[function(require,module,exports){
34352/**
34353 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
34354 * in FIPS 180-2
34355 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
34356 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
34357 *
34358 */
34359
34360var inherits = require('inherits')
34361var Sha256 = require('./sha256')
34362var Hash = require('./hash')
34363var Buffer = require('safe-buffer').Buffer
34364
34365var W = new Array(64)
34366
34367function Sha224 () {
34368 this.init()
34369
34370 this._w = W // new Array(64)
34371
34372 Hash.call(this, 64, 56)
34373}
34374
34375inherits(Sha224, Sha256)
34376
34377Sha224.prototype.init = function () {
34378 this._a = 0xc1059ed8
34379 this._b = 0x367cd507
34380 this._c = 0x3070dd17
34381 this._d = 0xf70e5939
34382 this._e = 0xffc00b31
34383 this._f = 0x68581511
34384 this._g = 0x64f98fa7
34385 this._h = 0xbefa4fa4
34386
34387 return this
34388}
34389
34390Sha224.prototype._hash = function () {
34391 var H = Buffer.allocUnsafe(28)
34392
34393 H.writeInt32BE(this._a, 0)
34394 H.writeInt32BE(this._b, 4)
34395 H.writeInt32BE(this._c, 8)
34396 H.writeInt32BE(this._d, 12)
34397 H.writeInt32BE(this._e, 16)
34398 H.writeInt32BE(this._f, 20)
34399 H.writeInt32BE(this._g, 24)
34400
34401 return H
34402}
34403
34404module.exports = Sha224
34405
34406},{"./hash":394,"./sha256":399,"inherits":116,"safe-buffer":393}],399:[function(require,module,exports){
34407/**
34408 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
34409 * in FIPS 180-2
34410 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
34411 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
34412 *
34413 */
34414
34415var inherits = require('inherits')
34416var Hash = require('./hash')
34417var Buffer = require('safe-buffer').Buffer
34418
34419var K = [
34420 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
34421 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
34422 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
34423 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
34424 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
34425 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
34426 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
34427 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
34428 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
34429 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
34430 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
34431 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
34432 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
34433 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
34434 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
34435 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
34436]
34437
34438var W = new Array(64)
34439
34440function Sha256 () {
34441 this.init()
34442
34443 this._w = W // new Array(64)
34444
34445 Hash.call(this, 64, 56)
34446}
34447
34448inherits(Sha256, Hash)
34449
34450Sha256.prototype.init = function () {
34451 this._a = 0x6a09e667
34452 this._b = 0xbb67ae85
34453 this._c = 0x3c6ef372
34454 this._d = 0xa54ff53a
34455 this._e = 0x510e527f
34456 this._f = 0x9b05688c
34457 this._g = 0x1f83d9ab
34458 this._h = 0x5be0cd19
34459
34460 return this
34461}
34462
34463function ch (x, y, z) {
34464 return z ^ (x & (y ^ z))
34465}
34466
34467function maj (x, y, z) {
34468 return (x & y) | (z & (x | y))
34469}
34470
34471function sigma0 (x) {
34472 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
34473}
34474
34475function sigma1 (x) {
34476 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
34477}
34478
34479function gamma0 (x) {
34480 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
34481}
34482
34483function gamma1 (x) {
34484 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
34485}
34486
34487Sha256.prototype._update = function (M) {
34488 var W = this._w
34489
34490 var a = this._a | 0
34491 var b = this._b | 0
34492 var c = this._c | 0
34493 var d = this._d | 0
34494 var e = this._e | 0
34495 var f = this._f | 0
34496 var g = this._g | 0
34497 var h = this._h | 0
34498
34499 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
34500 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
34501
34502 for (var j = 0; j < 64; ++j) {
34503 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
34504 var T2 = (sigma0(a) + maj(a, b, c)) | 0
34505
34506 h = g
34507 g = f
34508 f = e
34509 e = (d + T1) | 0
34510 d = c
34511 c = b
34512 b = a
34513 a = (T1 + T2) | 0
34514 }
34515
34516 this._a = (a + this._a) | 0
34517 this._b = (b + this._b) | 0
34518 this._c = (c + this._c) | 0
34519 this._d = (d + this._d) | 0
34520 this._e = (e + this._e) | 0
34521 this._f = (f + this._f) | 0
34522 this._g = (g + this._g) | 0
34523 this._h = (h + this._h) | 0
34524}
34525
34526Sha256.prototype._hash = function () {
34527 var H = Buffer.allocUnsafe(32)
34528
34529 H.writeInt32BE(this._a, 0)
34530 H.writeInt32BE(this._b, 4)
34531 H.writeInt32BE(this._c, 8)
34532 H.writeInt32BE(this._d, 12)
34533 H.writeInt32BE(this._e, 16)
34534 H.writeInt32BE(this._f, 20)
34535 H.writeInt32BE(this._g, 24)
34536 H.writeInt32BE(this._h, 28)
34537
34538 return H
34539}
34540
34541module.exports = Sha256
34542
34543},{"./hash":394,"inherits":116,"safe-buffer":393}],400:[function(require,module,exports){
34544var inherits = require('inherits')
34545var SHA512 = require('./sha512')
34546var Hash = require('./hash')
34547var Buffer = require('safe-buffer').Buffer
34548
34549var W = new Array(160)
34550
34551function Sha384 () {
34552 this.init()
34553 this._w = W
34554
34555 Hash.call(this, 128, 112)
34556}
34557
34558inherits(Sha384, SHA512)
34559
34560Sha384.prototype.init = function () {
34561 this._ah = 0xcbbb9d5d
34562 this._bh = 0x629a292a
34563 this._ch = 0x9159015a
34564 this._dh = 0x152fecd8
34565 this._eh = 0x67332667
34566 this._fh = 0x8eb44a87
34567 this._gh = 0xdb0c2e0d
34568 this._hh = 0x47b5481d
34569
34570 this._al = 0xc1059ed8
34571 this._bl = 0x367cd507
34572 this._cl = 0x3070dd17
34573 this._dl = 0xf70e5939
34574 this._el = 0xffc00b31
34575 this._fl = 0x68581511
34576 this._gl = 0x64f98fa7
34577 this._hl = 0xbefa4fa4
34578
34579 return this
34580}
34581
34582Sha384.prototype._hash = function () {
34583 var H = Buffer.allocUnsafe(48)
34584
34585 function writeInt64BE (h, l, offset) {
34586 H.writeInt32BE(h, offset)
34587 H.writeInt32BE(l, offset + 4)
34588 }
34589
34590 writeInt64BE(this._ah, this._al, 0)
34591 writeInt64BE(this._bh, this._bl, 8)
34592 writeInt64BE(this._ch, this._cl, 16)
34593 writeInt64BE(this._dh, this._dl, 24)
34594 writeInt64BE(this._eh, this._el, 32)
34595 writeInt64BE(this._fh, this._fl, 40)
34596
34597 return H
34598}
34599
34600module.exports = Sha384
34601
34602},{"./hash":394,"./sha512":401,"inherits":116,"safe-buffer":393}],401:[function(require,module,exports){
34603var inherits = require('inherits')
34604var Hash = require('./hash')
34605var Buffer = require('safe-buffer').Buffer
34606
34607var K = [
34608 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
34609 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
34610 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
34611 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
34612 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
34613 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
34614 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
34615 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
34616 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
34617 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
34618 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
34619 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
34620 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
34621 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
34622 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
34623 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
34624 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
34625 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
34626 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
34627 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
34628 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
34629 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
34630 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
34631 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
34632 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
34633 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
34634 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
34635 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
34636 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
34637 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
34638 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
34639 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
34640 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
34641 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
34642 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
34643 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
34644 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
34645 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
34646 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
34647 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
34648]
34649
34650var W = new Array(160)
34651
34652function Sha512 () {
34653 this.init()
34654 this._w = W
34655
34656 Hash.call(this, 128, 112)
34657}
34658
34659inherits(Sha512, Hash)
34660
34661Sha512.prototype.init = function () {
34662 this._ah = 0x6a09e667
34663 this._bh = 0xbb67ae85
34664 this._ch = 0x3c6ef372
34665 this._dh = 0xa54ff53a
34666 this._eh = 0x510e527f
34667 this._fh = 0x9b05688c
34668 this._gh = 0x1f83d9ab
34669 this._hh = 0x5be0cd19
34670
34671 this._al = 0xf3bcc908
34672 this._bl = 0x84caa73b
34673 this._cl = 0xfe94f82b
34674 this._dl = 0x5f1d36f1
34675 this._el = 0xade682d1
34676 this._fl = 0x2b3e6c1f
34677 this._gl = 0xfb41bd6b
34678 this._hl = 0x137e2179
34679
34680 return this
34681}
34682
34683function Ch (x, y, z) {
34684 return z ^ (x & (y ^ z))
34685}
34686
34687function maj (x, y, z) {
34688 return (x & y) | (z & (x | y))
34689}
34690
34691function sigma0 (x, xl) {
34692 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
34693}
34694
34695function sigma1 (x, xl) {
34696 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
34697}
34698
34699function Gamma0 (x, xl) {
34700 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
34701}
34702
34703function Gamma0l (x, xl) {
34704 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
34705}
34706
34707function Gamma1 (x, xl) {
34708 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
34709}
34710
34711function Gamma1l (x, xl) {
34712 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
34713}
34714
34715function getCarry (a, b) {
34716 return (a >>> 0) < (b >>> 0) ? 1 : 0
34717}
34718
34719Sha512.prototype._update = function (M) {
34720 var W = this._w
34721
34722 var ah = this._ah | 0
34723 var bh = this._bh | 0
34724 var ch = this._ch | 0
34725 var dh = this._dh | 0
34726 var eh = this._eh | 0
34727 var fh = this._fh | 0
34728 var gh = this._gh | 0
34729 var hh = this._hh | 0
34730
34731 var al = this._al | 0
34732 var bl = this._bl | 0
34733 var cl = this._cl | 0
34734 var dl = this._dl | 0
34735 var el = this._el | 0
34736 var fl = this._fl | 0
34737 var gl = this._gl | 0
34738 var hl = this._hl | 0
34739
34740 for (var i = 0; i < 32; i += 2) {
34741 W[i] = M.readInt32BE(i * 4)
34742 W[i + 1] = M.readInt32BE(i * 4 + 4)
34743 }
34744 for (; i < 160; i += 2) {
34745 var xh = W[i - 15 * 2]
34746 var xl = W[i - 15 * 2 + 1]
34747 var gamma0 = Gamma0(xh, xl)
34748 var gamma0l = Gamma0l(xl, xh)
34749
34750 xh = W[i - 2 * 2]
34751 xl = W[i - 2 * 2 + 1]
34752 var gamma1 = Gamma1(xh, xl)
34753 var gamma1l = Gamma1l(xl, xh)
34754
34755 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
34756 var Wi7h = W[i - 7 * 2]
34757 var Wi7l = W[i - 7 * 2 + 1]
34758
34759 var Wi16h = W[i - 16 * 2]
34760 var Wi16l = W[i - 16 * 2 + 1]
34761
34762 var Wil = (gamma0l + Wi7l) | 0
34763 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
34764 Wil = (Wil + gamma1l) | 0
34765 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
34766 Wil = (Wil + Wi16l) | 0
34767 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
34768
34769 W[i] = Wih
34770 W[i + 1] = Wil
34771 }
34772
34773 for (var j = 0; j < 160; j += 2) {
34774 Wih = W[j]
34775 Wil = W[j + 1]
34776
34777 var majh = maj(ah, bh, ch)
34778 var majl = maj(al, bl, cl)
34779
34780 var sigma0h = sigma0(ah, al)
34781 var sigma0l = sigma0(al, ah)
34782 var sigma1h = sigma1(eh, el)
34783 var sigma1l = sigma1(el, eh)
34784
34785 // t1 = h + sigma1 + ch + K[j] + W[j]
34786 var Kih = K[j]
34787 var Kil = K[j + 1]
34788
34789 var chh = Ch(eh, fh, gh)
34790 var chl = Ch(el, fl, gl)
34791
34792 var t1l = (hl + sigma1l) | 0
34793 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
34794 t1l = (t1l + chl) | 0
34795 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
34796 t1l = (t1l + Kil) | 0
34797 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
34798 t1l = (t1l + Wil) | 0
34799 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
34800
34801 // t2 = sigma0 + maj
34802 var t2l = (sigma0l + majl) | 0
34803 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
34804
34805 hh = gh
34806 hl = gl
34807 gh = fh
34808 gl = fl
34809 fh = eh
34810 fl = el
34811 el = (dl + t1l) | 0
34812 eh = (dh + t1h + getCarry(el, dl)) | 0
34813 dh = ch
34814 dl = cl
34815 ch = bh
34816 cl = bl
34817 bh = ah
34818 bl = al
34819 al = (t1l + t2l) | 0
34820 ah = (t1h + t2h + getCarry(al, t1l)) | 0
34821 }
34822
34823 this._al = (this._al + al) | 0
34824 this._bl = (this._bl + bl) | 0
34825 this._cl = (this._cl + cl) | 0
34826 this._dl = (this._dl + dl) | 0
34827 this._el = (this._el + el) | 0
34828 this._fl = (this._fl + fl) | 0
34829 this._gl = (this._gl + gl) | 0
34830 this._hl = (this._hl + hl) | 0
34831
34832 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
34833 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
34834 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
34835 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
34836 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
34837 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
34838 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
34839 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
34840}
34841
34842Sha512.prototype._hash = function () {
34843 var H = Buffer.allocUnsafe(64)
34844
34845 function writeInt64BE (h, l, offset) {
34846 H.writeInt32BE(h, offset)
34847 H.writeInt32BE(l, offset + 4)
34848 }
34849
34850 writeInt64BE(this._ah, this._al, 0)
34851 writeInt64BE(this._bh, this._bl, 8)
34852 writeInt64BE(this._ch, this._cl, 16)
34853 writeInt64BE(this._dh, this._dl, 24)
34854 writeInt64BE(this._eh, this._el, 32)
34855 writeInt64BE(this._fh, this._fl, 40)
34856 writeInt64BE(this._gh, this._gl, 48)
34857 writeInt64BE(this._hh, this._hl, 56)
34858
34859 return H
34860}
34861
34862module.exports = Sha512
34863
34864},{"./hash":394,"inherits":116,"safe-buffer":393}],402:[function(require,module,exports){
34865"use strict";
34866
34867var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
34868
34869var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
34870
34871var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
34872
34873Object.defineProperty(exports, "__esModule", {
34874 value: true
34875});
34876
34877var BigNumber = _interopRequire(require("bignumber.js"));
34878
34879var isString = _interopRequire(require("lodash/isString"));
34880
34881var Keypair = require("./keypair").Keypair;
34882
34883var StrKey = require("./strkey").StrKey;
34884
34885/**
34886 * Create a new Account object.
34887 *
34888 * `Account` represents a single account in Stellar network and its sequence number.
34889 * Account tracks the sequence number as it is used by {@link TransactionBuilder}.
34890 * See [Accounts](https://stellar.org/developers/learn/concepts/accounts.html) for more information about how
34891 * accounts work in Stellar.
34892 * @constructor
34893 * @param {string} accountId ID of the account (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`)
34894 * @param {string} sequence current sequence number of the account
34895 */
34896
34897var Account = exports.Account = (function () {
34898 function Account(accountId, sequence) {
34899 _classCallCheck(this, Account);
34900
34901 if (!StrKey.isValidEd25519PublicKey(accountId)) {
34902 throw new Error("accountId is invalid");
34903 }
34904 if (!isString(sequence)) {
34905 throw new Error("sequence must be of type string");
34906 }
34907 this._accountId = accountId;
34908 this.sequence = new BigNumber(sequence);
34909 }
34910
34911 _createClass(Account, {
34912 accountId: {
34913
34914 /**
34915 * Returns Stellar account ID, ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`
34916 * @returns {string}
34917 */
34918
34919 value: function accountId() {
34920 return this._accountId;
34921 }
34922 },
34923 sequenceNumber: {
34924
34925 /**
34926 * @returns {string}
34927 */
34928
34929 value: function sequenceNumber() {
34930 return this.sequence.toString();
34931 }
34932 },
34933 incrementSequenceNumber: {
34934
34935 /**
34936 * Increments sequence number in this object by one.
34937 */
34938
34939 value: function incrementSequenceNumber() {
34940 this.sequence = this.sequence.add(1);
34941 }
34942 }
34943 });
34944
34945 return Account;
34946})();
34947},{"./keypair":408,"./strkey":426,"bignumber.js":17,"lodash/isString":333}],403:[function(require,module,exports){
34948"use strict";
34949
34950var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
34951
34952var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
34953
34954var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
34955
34956Object.defineProperty(exports, "__esModule", {
34957 value: true
34958});
34959
34960var xdr = _interopRequire(require("./generated/stellar-xdr_generated"));
34961
34962var Keypair = require("./keypair").Keypair;
34963
34964var StrKey = require("./strkey").StrKey;
34965
34966var clone = _interopRequire(require("lodash/clone"));
34967
34968var padEnd = _interopRequire(require("lodash/padEnd"));
34969
34970var trimEnd = _interopRequire(require("lodash/trimEnd"));
34971
34972/**
34973 * Asset class represents an asset, either the native asset (`XLM`)
34974 * or an asset code / issuer account ID pair.
34975 *
34976 * An asset code describes an asset code and issuer pair. In the case of the native
34977 * asset XLM, the issuer will be null.
34978 *
34979 * @constructor
34980 * @param {string} code - The asset code.
34981 * @param {string} issuer - The account ID of the issuer.
34982 */
34983
34984var Asset = exports.Asset = (function () {
34985 function Asset(code, issuer) {
34986 _classCallCheck(this, Asset);
34987
34988 if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) {
34989 throw new Error("Asset code is invalid (maximum alphanumeric, 12 characters at max)");
34990 }
34991 if (String(code).toLowerCase() !== "xlm" && !issuer) {
34992 throw new Error("Issuer cannot be null");
34993 }
34994 if (issuer && !StrKey.isValidEd25519PublicKey(issuer)) {
34995 throw new Error("Issuer is invalid");
34996 }
34997
34998 this.code = code;
34999 this.issuer = issuer;
35000 }
35001
35002 _createClass(Asset, {
35003 toXDRObject: {
35004
35005 /**
35006 * Returns the xdr object for this asset.
35007 * @returns {xdr.Asset}
35008 */
35009
35010 value: function toXDRObject() {
35011 if (this.isNative()) {
35012 return xdr.Asset.assetTypeNative();
35013 }
35014
35015 var xdrType = undefined,
35016 xdrTypeString = undefined;
35017 if (this.code.length <= 4) {
35018 xdrType = xdr.AssetAlphaNum4;
35019 xdrTypeString = "assetTypeCreditAlphanum4";
35020 } else {
35021 xdrType = xdr.AssetAlphaNum12;
35022 xdrTypeString = "assetTypeCreditAlphanum12";
35023 }
35024
35025 // pad code with null bytes if necessary
35026 var padLength = this.code.length <= 4 ? 4 : 12;
35027 var paddedCode = padEnd(this.code, padLength, "\u0000");
35028
35029 var assetType = new xdrType({
35030 assetCode: paddedCode,
35031 issuer: Keypair.fromPublicKey(this.issuer).xdrAccountId()
35032 });
35033
35034 return new xdr.Asset(xdrTypeString, assetType);
35035 }
35036 },
35037 getCode: {
35038
35039 /**
35040 * Return the asset code
35041 * @returns {string}
35042 */
35043
35044 value: function getCode() {
35045 return clone(this.code);
35046 }
35047 },
35048 getIssuer: {
35049
35050 /**
35051 * Return the asset issuer
35052 * @returns {string}
35053 */
35054
35055 value: function getIssuer() {
35056 return clone(this.issuer);
35057 }
35058 },
35059 getAssetType: {
35060
35061 /**
35062 * Return the asset type. Can be one of following types:
35063 *
35064 * * `native`
35065 * * `credit_alphanum4`
35066 * * `credit_alphanum12`
35067 *
35068 * @see [Assets concept](https://www.stellar.org/developers/learn/concepts/assets.html)
35069 * @returns {string}
35070 */
35071
35072 value: function getAssetType() {
35073 if (this.isNative()) {
35074 return "native";
35075 }
35076 if (this.code.length >= 1 && this.code.length <= 4) {
35077 return "credit_alphanum4";
35078 }
35079 if (this.code.length >= 5 && this.code.length <= 12) {
35080 return "credit_alphanum12";
35081 }
35082 }
35083 },
35084 isNative: {
35085
35086 /**
35087 * Returns true if this asset object is the native asset.
35088 * @returns {boolean}
35089 */
35090
35091 value: function isNative() {
35092 return !this.issuer;
35093 }
35094 },
35095 equals: {
35096
35097 /**
35098 * Returns true if this asset equals the given asset.
35099 * @param {Asset} asset Asset to compare
35100 * @returns {boolean}
35101 */
35102
35103 value: function equals(asset) {
35104 return this.code == asset.getCode() && this.issuer == asset.getIssuer();
35105 }
35106 }
35107 }, {
35108 native: {
35109
35110 /**
35111 * Returns an asset object for the native asset.
35112 * @Return {Asset}
35113 */
35114
35115 value: function native() {
35116 return new Asset("XLM");
35117 }
35118 },
35119 fromOperation: {
35120
35121 /**
35122 * Returns an asset object from its XDR object representation.
35123 * @param {xdr.Asset} assetXdr - The asset xdr object.
35124 * @returns {Asset}
35125 */
35126
35127 value: function fromOperation(assetXdr) {
35128 var anum = undefined,
35129 code = undefined,
35130 issuer = undefined;
35131 switch (assetXdr["switch"]()) {
35132 case xdr.AssetType.assetTypeNative():
35133 return this.native();
35134 case xdr.AssetType.assetTypeCreditAlphanum4():
35135 anum = assetXdr.alphaNum4();
35136 /* falls through */
35137 case xdr.AssetType.assetTypeCreditAlphanum12():
35138 anum = anum || assetXdr.alphaNum12();
35139 issuer = StrKey.encodeEd25519PublicKey(anum.issuer().ed25519());
35140 code = trimEnd(anum.assetCode(), "\u0000");
35141 return new this(code, issuer);
35142 default:
35143 throw new Error("Invalid asset type: " + assetXdr["switch"]().name);
35144 }
35145 }
35146 }
35147 });
35148
35149 return Asset;
35150})();
35151},{"./generated/stellar-xdr_generated":405,"./keypair":408,"./strkey":426,"lodash/clone":306,"lodash/padEnd":341,"lodash/trimEnd":351}],404:[function(require,module,exports){
35152(function (Buffer){
35153"use strict";
35154
35155var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
35156
35157exports.decodeBase58Check = decodeBase58Check;
35158Object.defineProperty(exports, "__esModule", {
35159 value: true
35160});
35161
35162var bs58 = _interopRequire(require("./vendor/bs58"));
35163
35164var isUndefined = _interopRequire(require("lodash/isUndefined"));
35165
35166var hash = require("./hashing").hash;
35167
35168var verifyChecksum = require("./util/checksum").verifyChecksum;
35169
35170var versionBytes = {
35171 accountId: 0, // decimal 0
35172 none: 1, // decimal 1
35173 seed: 33 };
35174
35175function decodeBase58Check(versionByteName, encoded) {
35176 var decoded = bs58.decode(encoded);
35177 var versionByte = decoded[0];
35178 var payload = decoded.slice(0, decoded.length - 4);
35179 var data = payload.slice(1);
35180 var checksum = decoded.slice(decoded.length - 4);
35181
35182 var expectedVersion = versionBytes[versionByteName];
35183
35184 if (isUndefined(expectedVersion)) {
35185 throw new Error("" + versionByteName + " is not a valid version byte name. expected one of \"accountId\", \"seed\", or \"none\"");
35186 }
35187
35188 if (versionByte !== expectedVersion) {
35189 throw new Error("invalid version byte. expected " + expectedVersion + ", got " + versionByte);
35190 }
35191
35192 var expectedChecksum = calculateChecksum(payload);
35193
35194 if (!verifyChecksum(expectedChecksum, checksum)) {
35195 throw new Error("invalid checksum");
35196 }
35197
35198 if (versionByteName === "accountId" && decoded.length !== 37) {
35199 throw new Error("Decoded address length is invalid. Expected 37, got " + decoded.length);
35200 }
35201
35202 return Buffer.from(data);
35203}
35204
35205function calculateChecksum(payload) {
35206 var inner = hash(payload);
35207 var outer = hash(inner);
35208 return outer.slice(0, 4);
35209}
35210// decimal 33
35211}).call(this,require("buffer").Buffer)
35212},{"./hashing":406,"./util/checksum":429,"./vendor/bs58":431,"buffer":49,"lodash/isUndefined":336}],405:[function(require,module,exports){
35213"use strict";var _interopRequireWildcard=function(obj){return obj && obj.__esModule?obj:{"default":obj};};var XDR=_interopRequireWildcard(require("js-xdr"));var types=XDR.config(function(xdr){xdr.typedef("Value", xdr.varOpaque());xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]);xdr["enum"]("ScpStatementType", {scpStPrepare:0, scpStConfirm:1, scpStExternalize:2, scpStNominate:3});xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]);xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]);xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]);xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]);xdr.union("ScpStatementPledges", {switchOn:xdr.lookup("ScpStatementType"), switchName:"type", switches:[["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]], arms:{prepare:xdr.lookup("ScpStatementPrepare"), confirm:xdr.lookup("ScpStatementConfirm"), externalize:xdr.lookup("ScpStatementExternalize"), nominate:xdr.lookup("ScpNomination")}});xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]);xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]);xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("PublicKey"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]);xdr.typedef("AccountId", xdr.lookup("PublicKey"));xdr.typedef("Thresholds", xdr.opaque(4));xdr.typedef("String32", xdr.string(32));xdr.typedef("String64", xdr.string(64));xdr.typedef("SequenceNumber", xdr.lookup("Int64"));xdr.typedef("DataValue", xdr.varOpaque(64));xdr["enum"]("AssetType", {assetTypeNative:0, assetTypeCreditAlphanum4:1, assetTypeCreditAlphanum12:2});xdr.struct("AssetAlphaNum4", [["assetCode", xdr.opaque(4)], ["issuer", xdr.lookup("AccountId")]]);xdr.struct("AssetAlphaNum12", [["assetCode", xdr.opaque(12)], ["issuer", xdr.lookup("AccountId")]]);xdr.union("Asset", {switchOn:xdr.lookup("AssetType"), switchName:"type", switches:[["assetTypeNative", xdr["void"]()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]], arms:{alphaNum4:xdr.lookup("AssetAlphaNum4"), alphaNum12:xdr.lookup("AssetAlphaNum12")}});xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]);xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]);xdr["enum"]("ThresholdIndices", {thresholdMasterWeight:0, thresholdLow:1, thresholdMed:2, thresholdHigh:3});xdr["enum"]("LedgerEntryType", {account:0, trustline:1, offer:2, datum:3});xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]);xdr["enum"]("AccountFlags", {authRequiredFlag:1, authRevocableFlag:2, authImmutableFlag:4});xdr["const"]("MASK_ACCOUNT_FLAGS", 7);xdr.union("AccountEntryV1Ext", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("AccountEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryV1Ext")]]);xdr.union("AccountEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()], [1, "v1"]], arms:{v1:xdr.lookup("AccountEntryV1")}});xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), 20)], ["ext", xdr.lookup("AccountEntryExt")]]);xdr["enum"]("TrustLineFlags", {authorizedFlag:1});xdr["const"]("MASK_TRUSTLINE_FLAGS", 1);xdr.union("TrustLineEntryV1Ext", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]);xdr.union("TrustLineEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()], [1, "v1"]], arms:{v1:xdr.lookup("TrustLineEntryV1")}});xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]);xdr["enum"]("OfferEntryFlags", {passiveFlag:1});xdr["const"]("MASK_OFFERENTRY_FLAGS", 1);xdr.union("OfferEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Uint64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]);xdr.union("DataEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]);xdr.union("LedgerEntryData", {switchOn:xdr.lookup("LedgerEntryType"), switchName:"type", switches:[["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["datum", "data"]], arms:{account:xdr.lookup("AccountEntry"), trustLine:xdr.lookup("TrustLineEntry"), offer:xdr.lookup("OfferEntry"), data:xdr.lookup("DataEntry")}});xdr.union("LedgerEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]);xdr["enum"]("EnvelopeType", {envelopeTypeScp:1, envelopeTypeTx:2, envelopeTypeAuth:3});xdr.typedef("UpgradeType", xdr.varOpaque(128));xdr.union("StellarValueExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("Uint64")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]);xdr.union("LedgerHeaderExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]);xdr["enum"]("LedgerUpgradeType", {ledgerUpgradeVersion:1, ledgerUpgradeBaseFee:2, ledgerUpgradeMaxTxSetSize:3, ledgerUpgradeBaseReserve:4});xdr.union("LedgerUpgrade", {switchOn:xdr.lookup("LedgerUpgradeType"), switchName:"type", switches:[["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"]], arms:{newLedgerVersion:xdr.lookup("Uint32"), newBaseFee:xdr.lookup("Uint32"), newMaxTxSetSize:xdr.lookup("Uint32"), newBaseReserve:xdr.lookup("Uint32")}});xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]);xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")]]);xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Uint64")]]);xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]);xdr.union("LedgerKey", {switchOn:xdr.lookup("LedgerEntryType"), switchName:"type", switches:[["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["datum", "data"]], arms:{account:xdr.lookup("LedgerKeyAccount"), trustLine:xdr.lookup("LedgerKeyTrustLine"), offer:xdr.lookup("LedgerKeyOffer"), data:xdr.lookup("LedgerKeyData")}});xdr["enum"]("BucketEntryType", {liveentry:0, deadentry:1});xdr.union("BucketEntry", {switchOn:xdr.lookup("BucketEntryType"), switchName:"type", switches:[["liveentry", "liveEntry"], ["deadentry", "deadEntry"]], arms:{liveEntry:xdr.lookup("LedgerEntry"), deadEntry:xdr.lookup("LedgerKey")}});xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]);xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]);xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]);xdr.union("TransactionHistoryEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]);xdr.union("TransactionHistoryResultEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]);xdr.union("LedgerHeaderHistoryEntryExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]);xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]);xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]);xdr.union("ScpHistoryEntry", {switchOn:xdr.int(), switchName:"v", switches:[[0, "v0"]], arms:{v0:xdr.lookup("ScpHistoryEntryV0")}});xdr["enum"]("LedgerEntryChangeType", {ledgerEntryCreated:0, ledgerEntryUpdated:1, ledgerEntryRemoved:2, ledgerEntryState:3});xdr.union("LedgerEntryChange", {switchOn:xdr.lookup("LedgerEntryChangeType"), switchName:"type", switches:[["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]], arms:{created:xdr.lookup("LedgerEntry"), updated:xdr.lookup("LedgerEntry"), removed:xdr.lookup("LedgerKey"), state:xdr.lookup("LedgerEntry")}});xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647));xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]);xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]);xdr.union("TransactionMeta", {switchOn:xdr.int(), switchName:"v", switches:[[0, "operations"], [1, "v1"]], arms:{operations:xdr.varArray(xdr.lookup("OperationMeta"), 2147483647), v1:xdr.lookup("TransactionMetaV1")}});xdr["enum"]("ErrorCode", {errMisc:0, errDatum:1, errConf:2, errAuth:3, errLoad:4});xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]);xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]);xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr.int()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]);xdr.struct("Auth", [["unused", xdr.int()]]);xdr["enum"]("IpAddrType", {iPv4:0, iPv6:1});xdr.union("PeerAddressIp", {switchOn:xdr.lookup("IpAddrType"), switchName:"type", switches:[["iPv4", "ipv4"], ["iPv6", "ipv6"]], arms:{ipv4:xdr.opaque(4), ipv6:xdr.opaque(16)}});xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]);xdr["enum"]("MessageType", {errorMsg:0, auth:2, dontHave:3, getPeer:4, peer:5, getTxSet:6, txSet:7, transaction:8, getScpQuorumset:9, scpQuorumset:10, scpMessage:11, getScpState:12, hello:13});xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]);xdr.union("StellarMessage", {switchOn:xdr.lookup("MessageType"), switchName:"type", switches:[["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeer", xdr["void"]()], ["peer", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["transaction", "transaction"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"]], arms:{error:xdr.lookup("Error"), hello:xdr.lookup("Hello"), auth:xdr.lookup("Auth"), dontHave:xdr.lookup("DontHave"), peers:xdr.varArray(xdr.lookup("PeerAddress"), 100), txSetHash:xdr.lookup("Uint256"), txSet:xdr.lookup("TransactionSet"), transaction:xdr.lookup("TransactionEnvelope"), qSetHash:xdr.lookup("Uint256"), qSet:xdr.lookup("ScpQuorumSet"), envelope:xdr.lookup("StellarMessage"), getScpLedgerSeq:xdr.lookup("Uint32")}});xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]);xdr.union("AuthenticatedMessage", {switchOn:xdr.lookup("Uint32"), switchName:"v", switches:[[0, "v0"]], arms:{v0:xdr.lookup("AuthenticatedMessageV0")}});xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]);xdr["enum"]("OperationType", {createAccount:0, payment:1, pathPayment:2, manageOffer:3, createPassiveOffer:4, setOption:5, changeTrust:6, allowTrust:7, accountMerge:8, inflation:9, manageDatum:10, bumpSequence:11});xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]);xdr.struct("PaymentOp", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]);xdr.struct("PathPaymentOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("AccountId")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]);xdr.struct("ManageOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Uint64")]]);xdr.struct("CreatePassiveOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]);xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]);xdr.struct("ChangeTrustOp", [["line", xdr.lookup("Asset")], ["limit", xdr.lookup("Int64")]]);xdr.union("AllowTrustOpAsset", {switchOn:xdr.lookup("AssetType"), switchName:"type", switches:[["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]], arms:{assetCode4:xdr.opaque(4), assetCode12:xdr.opaque(12)}});xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AllowTrustOpAsset")], ["authorize", xdr.bool()]]);xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]);xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]);xdr.union("OperationBody", {switchOn:xdr.lookup("OperationType"), switchName:"type", switches:[["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPayment", "pathPaymentOp"], ["manageOffer", "manageOfferOp"], ["createPassiveOffer", "createPassiveOfferOp"], ["setOption", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr["void"]()], ["manageDatum", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"]], arms:{createAccountOp:xdr.lookup("CreateAccountOp"), paymentOp:xdr.lookup("PaymentOp"), pathPaymentOp:xdr.lookup("PathPaymentOp"), manageOfferOp:xdr.lookup("ManageOfferOp"), createPassiveOfferOp:xdr.lookup("CreatePassiveOfferOp"), setOptionsOp:xdr.lookup("SetOptionsOp"), changeTrustOp:xdr.lookup("ChangeTrustOp"), allowTrustOp:xdr.lookup("AllowTrustOp"), destination:xdr.lookup("AccountId"), manageDataOp:xdr.lookup("ManageDataOp"), bumpSequenceOp:xdr.lookup("BumpSequenceOp")}});xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("AccountId"))], ["body", xdr.lookup("OperationBody")]]);xdr["enum"]("MemoType", {memoNone:0, memoText:1, memoId:2, memoHash:3, memoReturn:4});xdr.union("Memo", {switchOn:xdr.lookup("MemoType"), switchName:"type", switches:[["memoNone", xdr["void"]()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]], arms:{text:xdr.string(28), id:xdr.lookup("Uint64"), hash:xdr.lookup("Hash"), retHash:xdr.lookup("Hash")}});xdr.struct("TimeBounds", [["minTime", xdr.lookup("Uint64")], ["maxTime", xdr.lookup("Uint64")]]);xdr.union("TransactionExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("Transaction", [["sourceAccount", xdr.lookup("AccountId")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), 100)], ["ext", xdr.lookup("TransactionExt")]]);xdr.union("TransactionSignaturePayloadTaggedTransaction", {switchOn:xdr.lookup("EnvelopeType"), switchName:"type", switches:[["envelopeTypeTx", "tx"]], arms:{tx:xdr.lookup("Transaction")}});xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]);xdr.struct("TransactionEnvelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]);xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Uint64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]);xdr["enum"]("CreateAccountResultCode", {createAccountSuccess:0, createAccountMalformed:-1, createAccountUnderfunded:-2, createAccountLowReserve:-3, createAccountAlreadyExist:-4});xdr.union("CreateAccountResult", {switchOn:xdr.lookup("CreateAccountResultCode"), switchName:"code", switches:[["createAccountSuccess", xdr["void"]()]], arms:{}, defaultArm:xdr["void"]()});xdr["enum"]("PaymentResultCode", {paymentSuccess:0, paymentMalformed:-1, paymentUnderfunded:-2, paymentSrcNoTrust:-3, paymentSrcNotAuthorized:-4, paymentNoDestination:-5, paymentNoTrust:-6, paymentNotAuthorized:-7, paymentLineFull:-8, paymentNoIssuer:-9});xdr.union("PaymentResult", {switchOn:xdr.lookup("PaymentResultCode"), switchName:"code", switches:[["paymentSuccess", xdr["void"]()]], arms:{}, defaultArm:xdr["void"]()});xdr["enum"]("PathPaymentResultCode", {pathPaymentSuccess:0, pathPaymentMalformed:-1, pathPaymentUnderfunded:-2, pathPaymentSrcNoTrust:-3, pathPaymentSrcNotAuthorized:-4, pathPaymentNoDestination:-5, pathPaymentNoTrust:-6, pathPaymentNotAuthorized:-7, pathPaymentLineFull:-8, pathPaymentNoIssuer:-9, pathPaymentTooFewOffer:-10, pathPaymentOfferCrossSelf:-11, pathPaymentOverSendmax:-12});xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]);xdr.struct("PathPaymentResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimOfferAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]);xdr.union("PathPaymentResult", {switchOn:xdr.lookup("PathPaymentResultCode"), switchName:"code", switches:[["pathPaymentSuccess", "success"], ["pathPaymentNoIssuer", "noIssuer"]], arms:{success:xdr.lookup("PathPaymentResultSuccess"), noIssuer:xdr.lookup("Asset")}, defaultArm:xdr["void"]()});xdr["enum"]("ManageOfferResultCode", {manageOfferSuccess:0, manageOfferMalformed:-1, manageOfferSellNoTrust:-2, manageOfferBuyNoTrust:-3, manageOfferSellNotAuthorized:-4, manageOfferBuyNotAuthorized:-5, manageOfferLineFull:-6, manageOfferUnderfunded:-7, manageOfferCrossSelf:-8, manageOfferSellNoIssuer:-9, manageOfferBuyNoIssuer:-10, manageOfferNotFound:-11, manageOfferLowReserve:-12});xdr["enum"]("ManageOfferEffect", {manageOfferCreated:0, manageOfferUpdated:1, manageOfferDeleted:2});xdr.union("ManageOfferSuccessResultOffer", {switchOn:xdr.lookup("ManageOfferEffect"), switchName:"effect", switches:[["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"]], arms:{offer:xdr.lookup("OfferEntry")}, defaultArm:xdr["void"]()});xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimOfferAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]);xdr.union("ManageOfferResult", {switchOn:xdr.lookup("ManageOfferResultCode"), switchName:"code", switches:[["manageOfferSuccess", "success"]], arms:{success:xdr.lookup("ManageOfferSuccessResult")}, defaultArm:xdr["void"]()});xdr["enum"]("SetOptionsResultCode", {setOptionsSuccess:0, setOptionsLowReserve:-1, setOptionsTooManySigner:-2, setOptionsBadFlag:-3, setOptionsInvalidInflation:-4, setOptionsCantChange:-5, setOptionsUnknownFlag:-6, setOptionsThresholdOutOfRange:-7, setOptionsBadSigner:-8, setOptionsInvalidHomeDomain:-9});xdr.union("SetOptionsResult", {switchOn:xdr.lookup("SetOptionsResultCode"), switchName:"code", switches:[["setOptionsSuccess", xdr["void"]()]], arms:{}, defaultArm:xdr["void"]()});xdr["enum"]("ChangeTrustResultCode", {changeTrustSuccess:0, changeTrustMalformed:-1, changeTrustNoIssuer:-2, changeTrustInvalidLimit:-3, changeTrustLowReserve:-4, changeTrustSelfNotAllowed:-5});xdr.union("ChangeTrustResult", {switchOn:xdr.lookup("ChangeTrustResultCode"), switchName:"code", switches:[["changeTrustSuccess", xdr["void"]()]], arms:{}, defaultArm:xdr["void"]()});xdr["enum"]("AllowTrustResultCode", {allowTrustSuccess:0, allowTrustMalformed:-1, allowTrustNoTrustLine:-2, allowTrustTrustNotRequired:-3, allowTrustCantRevoke:-4, allowTrustSelfNotAllowed:-5});xdr.union("AllowTrustResult", {switchOn:xdr.lookup("AllowTrustResultCode"), switchName:"code", switches:[["allowTrustSuccess", xdr["void"]()]], arms:{}, defaultArm:xdr["void"]()});xdr["enum"]("AccountMergeResultCode", {accountMergeSuccess:0, accountMergeMalformed:-1, accountMergeNoAccount:-2, accountMergeImmutableSet:-3, accountMergeHasSubEntry:-4, accountMergeSeqnumTooFar:-5, accountMergeDestFull:-6});xdr.union("AccountMergeResult", {switchOn:xdr.lookup("AccountMergeResultCode"), switchName:"code", switches:[["accountMergeSuccess", "sourceAccountBalance"]], arms:{sourceAccountBalance:xdr.lookup("Int64")}, defaultArm:xdr["void"]()});xdr["enum"]("InflationResultCode", {inflationSuccess:0, inflationNotTime:-1});xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]);xdr.union("InflationResult", {switchOn:xdr.lookup("InflationResultCode"), switchName:"code", switches:[["inflationSuccess", "payouts"]], arms:{payouts:xdr.varArray(xdr.lookup("InflationPayout"), 2147483647)}, defaultArm:xdr["void"]()});xdr["enum"]("ManageDataResultCode", {manageDataSuccess:0, manageDataNotSupportedYet:-1, manageDataNameNotFound:-2, manageDataLowReserve:-3, manageDataInvalidName:-4});xdr.union("ManageDataResult", {switchOn:xdr.lookup("ManageDataResultCode"), switchName:"code", switches:[["manageDataSuccess", xdr["void"]()]], arms:{}, defaultArm:xdr["void"]()});xdr["enum"]("BumpSequenceResultCode", {bumpSequenceSuccess:0, bumpSequenceBadSeq:-1});xdr.union("BumpSequenceResult", {switchOn:xdr.lookup("BumpSequenceResultCode"), switchName:"code", switches:[["bumpSequenceSuccess", xdr["void"]()]], arms:{}, defaultArm:xdr["void"]()});xdr["enum"]("OperationResultCode", {opInner:0, opBadAuth:-1, opNoAccount:-2, opNotSupported:-3});xdr.union("OperationResultTr", {switchOn:xdr.lookup("OperationType"), switchName:"type", switches:[["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPayment", "pathPaymentResult"], ["manageOffer", "manageOfferResult"], ["createPassiveOffer", "createPassiveOfferResult"], ["setOption", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageDatum", "manageDataResult"], ["bumpSequence", "bumpSeqResult"]], arms:{createAccountResult:xdr.lookup("CreateAccountResult"), paymentResult:xdr.lookup("PaymentResult"), pathPaymentResult:xdr.lookup("PathPaymentResult"), manageOfferResult:xdr.lookup("ManageOfferResult"), createPassiveOfferResult:xdr.lookup("ManageOfferResult"), setOptionsResult:xdr.lookup("SetOptionsResult"), changeTrustResult:xdr.lookup("ChangeTrustResult"), allowTrustResult:xdr.lookup("AllowTrustResult"), accountMergeResult:xdr.lookup("AccountMergeResult"), inflationResult:xdr.lookup("InflationResult"), manageDataResult:xdr.lookup("ManageDataResult"), bumpSeqResult:xdr.lookup("BumpSequenceResult")}});xdr.union("OperationResult", {switchOn:xdr.lookup("OperationResultCode"), switchName:"code", switches:[["opInner", "tr"]], arms:{tr:xdr.lookup("OperationResultTr")}, defaultArm:xdr["void"]()});xdr["enum"]("TransactionResultCode", {txSuccess:0, txFailed:-1, txTooEarly:-2, txTooLate:-3, txMissingOperation:-4, txBadSeq:-5, txBadAuth:-6, txInsufficientBalance:-7, txNoAccount:-8, txInsufficientFee:-9, txBadAuthExtra:-10, txInternalError:-11});xdr.union("TransactionResultResult", {switchOn:xdr.lookup("TransactionResultCode"), switchName:"code", switches:[["txSuccess", "results"], ["txFailed", "results"]], arms:{results:xdr.varArray(xdr.lookup("OperationResult"), 2147483647)}, defaultArm:xdr["void"]()});xdr.union("TransactionResultExt", {switchOn:xdr.int(), switchName:"v", switches:[[0, xdr["void"]()]], arms:{}});xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]);xdr.typedef("Hash", xdr.opaque(32));xdr.typedef("Uint256", xdr.opaque(32));xdr.typedef("Uint32", xdr.uint());xdr.typedef("Int32", xdr.int());xdr.typedef("Uint64", xdr.uhyper());xdr.typedef("Int64", xdr.hyper());xdr["enum"]("CryptoKeyType", {keyTypeEd25519:0, keyTypePreAuthTx:1, keyTypeHashX:2});xdr["enum"]("PublicKeyType", {publicKeyTypeEd25519:0});xdr["enum"]("SignerKeyType", {signerKeyTypeEd25519:0, signerKeyTypePreAuthTx:1, signerKeyTypeHashX:2});xdr.union("PublicKey", {switchOn:xdr.lookup("PublicKeyType"), switchName:"type", switches:[["publicKeyTypeEd25519", "ed25519"]], arms:{ed25519:xdr.lookup("Uint256")}});xdr.union("SignerKey", {switchOn:xdr.lookup("SignerKeyType"), switchName:"type", switches:[["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"]], arms:{ed25519:xdr.lookup("Uint256"), preAuthTx:xdr.lookup("Uint256"), hashX:xdr.lookup("Uint256")}});xdr.typedef("Signature", xdr.varOpaque(64));xdr.typedef("SignatureHint", xdr.opaque(4));xdr.typedef("NodeId", xdr.lookup("PublicKey"));xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]);xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]);xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]);xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]);});module.exports = types;
35214},{"js-xdr":127}],406:[function(require,module,exports){
35215"use strict";
35216
35217exports.hash = hash;
35218Object.defineProperty(exports, "__esModule", {
35219 value: true
35220});
35221
35222var sha256 = require("sha.js").sha256;
35223
35224function hash(data) {
35225 var hasher = new sha256();
35226 hasher.update(data, "utf8");
35227 return hasher.digest();
35228}
35229},{"sha.js":395}],407:[function(require,module,exports){
35230"use strict";
35231
35232var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
35233
35234var _defaults = function (obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; };
35235
35236var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
35237
35238Object.defineProperty(exports, "__esModule", {
35239 value: true
35240});
35241
35242var xdr = _interopRequire(require("./generated/stellar-xdr_generated"));
35243
35244exports.xdr = xdr;
35245exports.hash = require("./hashing").hash;
35246
35247var _signing = require("./signing");
35248
35249exports.sign = _signing.sign;
35250exports.verify = _signing.verify;
35251exports.FastSigning = _signing.FastSigning;
35252exports.Keypair = require("./keypair").Keypair;
35253
35254var _jsXdr = require("js-xdr");
35255
35256exports.UnsignedHyper = _jsXdr.UnsignedHyper;
35257exports.Hyper = _jsXdr.Hyper;
35258exports.Transaction = require("./transaction").Transaction;
35259
35260var _transaction_builder = require("./transaction_builder");
35261
35262exports.TransactionBuilder = _transaction_builder.TransactionBuilder;
35263exports.TimeoutInfinite = _transaction_builder.TimeoutInfinite;
35264exports.Asset = require("./asset").Asset;
35265
35266var _operation = require("./operation");
35267
35268exports.Operation = _operation.Operation;
35269exports.AuthRequiredFlag = _operation.AuthRequiredFlag;
35270exports.AuthRevocableFlag = _operation.AuthRevocableFlag;
35271exports.AuthImmutableFlag = _operation.AuthImmutableFlag;
35272
35273_defaults(exports, _interopRequireWildcard(require("./memo")));
35274
35275exports.Account = require("./account").Account;
35276
35277var _network = require("./network");
35278
35279exports.Network = _network.Network;
35280exports.Networks = _network.Networks;
35281exports.StrKey = require("./strkey").StrKey;
35282exports["default"] = module.exports;
35283},{"./account":402,"./asset":403,"./generated/stellar-xdr_generated":405,"./hashing":406,"./keypair":408,"./memo":409,"./network":410,"./operation":411,"./signing":425,"./strkey":426,"./transaction":427,"./transaction_builder":428,"js-xdr":127}],408:[function(require,module,exports){
35284(function (Buffer){
35285"use strict";
35286
35287var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
35288
35289var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
35290
35291var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
35292
35293var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
35294
35295Object.defineProperty(exports, "__esModule", {
35296 value: true
35297});
35298
35299var Network = require("./network").Network;
35300
35301var _signing = require("./signing");
35302
35303var sign = _signing.sign;
35304var verify = _signing.verify;
35305
35306var base58 = _interopRequireWildcard(require("./base58"));
35307
35308var StrKey = require("./strkey").StrKey;
35309
35310var xdr = _interopRequire(require("./generated/stellar-xdr_generated"));
35311
35312var nacl = _interopRequire(require("tweetnacl"));
35313
35314/**
35315 * `Keypair` represents public (and secret) keys of the account.
35316 *
35317 * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other
35318 * public-key signature systems.
35319 *
35320 * Use more convenient methods to create `Keypair` object:
35321 * * `{@link Keypair.fromPublicKey}`
35322 * * `{@link Keypair.fromSecret}`
35323 * * `{@link Keypair.random}`
35324 *
35325 * @constructor
35326 * @param {object} keys At least one of keys must be provided.
35327 * @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported)
35328 * @param {Buffer} [keys.publicKey] Raw public key
35329 * @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`)
35330 */
35331
35332var Keypair = exports.Keypair = (function () {
35333 function Keypair(keys) {
35334 _classCallCheck(this, Keypair);
35335
35336 if (keys.type != "ed25519") {
35337 throw new Error("Invalid keys type");
35338 }
35339
35340 this.type = keys.type;
35341
35342 if (keys.secretKey) {
35343 keys.secretKey = Buffer.from(keys.secretKey);
35344
35345 if (keys.secretKey.length != 32) {
35346 throw new Error("secretKey length is invalid");
35347 }
35348
35349 var secretKeyUint8 = new Uint8Array(keys.secretKey);
35350 var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8);
35351
35352 this._secretSeed = keys.secretKey;
35353 this._secretKey = Buffer.from(naclKeys.secretKey);
35354 this._publicKey = Buffer.from(naclKeys.publicKey);
35355
35356 if (keys.publicKey && !this._publicKey.equals(Buffer.from(keys.publicKey))) {
35357 throw new Error("secretKey does not match publicKey");
35358 }
35359 } else {
35360 this._publicKey = Buffer.from(keys.publicKey);
35361
35362 if (this._publicKey.length != 32) {
35363 throw new Error("publicKey length is invalid");
35364 }
35365 }
35366 }
35367
35368 _createClass(Keypair, {
35369 xdrAccountId: {
35370 value: function xdrAccountId() {
35371 return new xdr.AccountId.publicKeyTypeEd25519(this._publicKey);
35372 }
35373 },
35374 xdrPublicKey: {
35375 value: function xdrPublicKey() {
35376 return new xdr.PublicKey.publicKeyTypeEd25519(this._publicKey);
35377 }
35378 },
35379 rawPublicKey: {
35380
35381 /**
35382 * Returns raw public key
35383 * @returns {Buffer}
35384 */
35385
35386 value: function rawPublicKey() {
35387 return this._publicKey;
35388 }
35389 },
35390 signatureHint: {
35391 value: function signatureHint() {
35392 var a = this.xdrAccountId().toXDR();
35393
35394 return a.slice(a.length - 4);
35395 }
35396 },
35397 publicKey: {
35398
35399 /**
35400 * Returns public key associated with this `Keypair` object.
35401 * @returns {string}
35402 */
35403
35404 value: function publicKey() {
35405 return StrKey.encodeEd25519PublicKey(this._publicKey);
35406 }
35407 },
35408 secret: {
35409
35410 /**
35411 * Returns secret key associated with this `Keypair` object
35412 * @returns {string}
35413 */
35414
35415 value: function secret() {
35416 if (!this._secretSeed) {
35417 throw new Error("no secret key available");
35418 }
35419
35420 if (this.type == "ed25519") {
35421 return StrKey.encodeEd25519SecretSeed(this._secretSeed);
35422 }
35423
35424 throw new Error("Invalid Keypair type");
35425 }
35426 },
35427 rawSecretKey: {
35428
35429 /**
35430 * Returns raw secret key.
35431 * @returns {Buffer}
35432 */
35433
35434 value: function rawSecretKey() {
35435 return this._secretSeed;
35436 }
35437 },
35438 canSign: {
35439
35440 /**
35441 * Returns `true` if this `Keypair` object contains secret key and can sign.
35442 * @returns {boolean}
35443 */
35444
35445 value: function canSign() {
35446 return !!this._secretKey;
35447 }
35448 },
35449 sign: {
35450
35451 /**
35452 * Signs data.
35453 * @param {Buffer} data Data to sign
35454 * @returns {Buffer}
35455 */
35456
35457 value: (function (_sign) {
35458 var _signWrapper = function sign(_x) {
35459 return _sign.apply(this, arguments);
35460 };
35461
35462 _signWrapper.toString = function () {
35463 return _sign.toString();
35464 };
35465
35466 return _signWrapper;
35467 })(function (data) {
35468 if (!this.canSign()) {
35469 throw new Error("cannot sign: no secret key available");
35470 }
35471
35472 return sign(data, this._secretKey);
35473 })
35474 },
35475 verify: {
35476
35477 /**
35478 * Verifies if `signature` for `data` is valid.
35479 * @param {Buffer} data Signed data
35480 * @param {Buffer} signature Signature
35481 * @returns {boolean}
35482 */
35483
35484 value: (function (_verify) {
35485 var _verifyWrapper = function verify(_x2, _x3) {
35486 return _verify.apply(this, arguments);
35487 };
35488
35489 _verifyWrapper.toString = function () {
35490 return _verify.toString();
35491 };
35492
35493 return _verifyWrapper;
35494 })(function (data, signature) {
35495 return verify(data, signature, this._publicKey);
35496 })
35497 },
35498 signDecorated: {
35499 value: function signDecorated(data) {
35500 var signature = this.sign(data);
35501 var hint = this.signatureHint();
35502
35503 return new xdr.DecoratedSignature({ hint: hint, signature: signature });
35504 }
35505 }
35506 }, {
35507 fromSecret: {
35508
35509 /**
35510 * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending
35511 * on underlying public-key signature system. Currently `Keypair` only supports ed25519.
35512 * @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`)
35513 * @returns {Keypair}
35514 */
35515
35516 value: function fromSecret(secret) {
35517 var rawSecret = StrKey.decodeEd25519SecretSeed(secret);
35518 return this.fromRawEd25519Seed(rawSecret);
35519 }
35520 },
35521 fromBase58Seed: {
35522
35523 /**
35524 * Base58 address encoding is **DEPRECATED**! Use this method only for transition to strkey encoding.
35525 * @param {string} seed Base58 secret seed
35526 * @deprecated Use {@link Keypair.fromSecret}
35527 * @returns {Keypair}
35528 */
35529
35530 value: function fromBase58Seed(seed) {
35531 var rawSeed = base58.decodeBase58Check("seed", seed);
35532 return this.fromRawEd25519Seed(rawSeed);
35533 }
35534 },
35535 fromRawEd25519Seed: {
35536
35537 /**
35538 * Creates a new `Keypair` object from ed25519 secret key seed raw bytes.
35539 *
35540 * @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed
35541 * @returns {Keypair}
35542 */
35543
35544 value: function fromRawEd25519Seed(rawSeed) {
35545 return new this({ type: "ed25519", secretKey: rawSeed });
35546 }
35547 },
35548 master: {
35549
35550 /**
35551 * Returns `Keypair` object representing network master key.
35552 * @returns {Keypair}
35553 */
35554
35555 value: function master() {
35556 if (Network.current() === null) {
35557 throw new Error("No network selected. Use `Network.use`, `Network.usePublicNetwork` or `Network.useTestNetwork` helper methods to select network.");
35558 }
35559 return this.fromRawEd25519Seed(Network.current().networkId());
35560 }
35561 },
35562 fromPublicKey: {
35563
35564 /**
35565 * Creates a new `Keypair` object from public key.
35566 * @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`)
35567 * @returns {Keypair}
35568 */
35569
35570 value: function fromPublicKey(publicKey) {
35571 publicKey = StrKey.decodeEd25519PublicKey(publicKey);
35572 if (publicKey.length !== 32) {
35573 throw new Error("Invalid Stellar public key");
35574 }
35575 return new this({ type: "ed25519", publicKey: publicKey });
35576 }
35577 },
35578 random: {
35579
35580 /**
35581 * Create a random `Keypair` object.
35582 * @returns {Keypair}
35583 */
35584
35585 value: function random() {
35586 var secret = nacl.randomBytes(32);
35587 return this.fromRawEd25519Seed(secret);
35588 }
35589 }
35590 });
35591
35592 return Keypair;
35593})();
35594}).call(this,require("buffer").Buffer)
35595},{"./base58":404,"./generated/stellar-xdr_generated":405,"./network":410,"./signing":425,"./strkey":426,"buffer":49,"tweetnacl":435}],409:[function(require,module,exports){
35596(function (Buffer){
35597"use strict";
35598
35599var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
35600
35601var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
35602
35603var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
35604
35605Object.defineProperty(exports, "__esModule", {
35606 value: true
35607});
35608
35609var xdr = _interopRequire(require("./generated/stellar-xdr_generated"));
35610
35611var isUndefined = _interopRequire(require("lodash/isUndefined"));
35612
35613var isNull = _interopRequire(require("lodash/isNull"));
35614
35615var isString = _interopRequire(require("lodash/isString"));
35616
35617var clone = _interopRequire(require("lodash/clone"));
35618
35619var UnsignedHyper = require("js-xdr").UnsignedHyper;
35620
35621var BigNumber = _interopRequire(require("bignumber.js"));
35622
35623/**
35624 * Type of {@link Memo}.
35625 */
35626var MemoNone = "none";
35627exports.MemoNone = MemoNone;
35628/**
35629 * Type of {@link Memo}.
35630 */
35631var MemoID = "id";
35632exports.MemoID = MemoID;
35633/**
35634 * Type of {@link Memo}.
35635 */
35636var MemoText = "text";
35637exports.MemoText = MemoText;
35638/**
35639 * Type of {@link Memo}.
35640 */
35641var MemoHash = "hash";
35642exports.MemoHash = MemoHash;
35643/**
35644 * Type of {@link Memo}.
35645 */
35646var MemoReturn = "return";
35647
35648exports.MemoReturn = MemoReturn;
35649/**
35650 * `Memo` represents memos attached to transactions.
35651 *
35652 * @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn`
35653 * @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn`
35654 * @see [Transactions concept](https://www.stellar.org/developers/learn/concepts/transactions.html)
35655 * @class Memo
35656 */
35657
35658var Memo = exports.Memo = (function () {
35659 function Memo(type) {
35660 var value = arguments[1] === undefined ? null : arguments[1];
35661
35662 _classCallCheck(this, Memo);
35663
35664 this._type = type;
35665 this._value = value;
35666
35667 switch (this._type) {
35668 case MemoNone:
35669 break;
35670 case MemoID:
35671 Memo._validateIdValue(value);
35672 break;
35673 case MemoText:
35674 Memo._validateTextValue(value);
35675 break;
35676 case MemoHash:
35677 case MemoReturn:
35678 Memo._validateHashValue(value);
35679 // We want MemoHash and MemoReturn to have Buffer as a value
35680 if (isString(value)) {
35681 this._value = Buffer.from(value, "hex");
35682 }
35683 break;
35684 default:
35685 throw new Error("Invalid memo type");
35686 }
35687 }
35688
35689 _createClass(Memo, {
35690 type: {
35691
35692 /**
35693 * Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn`
35694 */
35695
35696 get: function () {
35697 return clone(this._type);
35698 },
35699 set: function (type) {
35700 throw new Error("Memo is immutable");
35701 }
35702 },
35703 value: {
35704
35705 /**
35706 * Contains memo value:
35707 * * `null` for `MemoNone`,
35708 * * `string` for `MemoID`,
35709 * * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise,
35710 * * `Buffer` for `MemoHash`, `MemoReturn`.
35711 */
35712
35713 get: function () {
35714 switch (this._type) {
35715 case MemoNone:
35716 return null;
35717 case MemoID:
35718 case MemoText:
35719 return clone(this._value);
35720 case MemoHash:
35721 case MemoReturn:
35722 return Buffer.from(this._value);
35723 default:
35724 throw new Error("Invalid memo type");
35725 }
35726 },
35727 set: function (value) {
35728 throw new Error("Memo is immutable");
35729 }
35730 },
35731 toXDRObject: {
35732
35733 /**
35734 * Returns XDR memo object.
35735 * @returns {xdr.Memo}
35736 */
35737
35738 value: function toXDRObject() {
35739 switch (this._type) {
35740 case MemoNone:
35741 return xdr.Memo.memoNone();
35742 case MemoID:
35743 return xdr.Memo.memoId(UnsignedHyper.fromString(this._value));
35744 case MemoText:
35745 return xdr.Memo.memoText(this._value);
35746 case MemoHash:
35747 return xdr.Memo.memoHash(this._value);
35748 case MemoReturn:
35749 return xdr.Memo.memoReturn(this._value);
35750 }
35751 }
35752 }
35753 }, {
35754 _validateIdValue: {
35755 value: function _validateIdValue(value) {
35756 var error = new Error("Expects a int64 as a string. Got " + value);
35757
35758 if (!isString(value)) {
35759 throw error;
35760 }
35761
35762 var number = undefined;
35763 try {
35764 number = new BigNumber(value);
35765 } catch (e) {
35766 throw error;
35767 }
35768
35769 // Infinity
35770 if (!number.isFinite()) {
35771 throw error;
35772 }
35773
35774 // NaN
35775 if (number.isNaN()) {
35776 throw error;
35777 }
35778 }
35779 },
35780 _validateTextValue: {
35781 value: function _validateTextValue(value) {
35782 if (!xdr.Memo.armTypeForArm("text").isValid(value)) {
35783 throw new Error("Expects string, array or buffer, max 28 bytes");
35784 }
35785 }
35786 },
35787 _validateHashValue: {
35788 value: function _validateHashValue(value) {
35789 var error = new Error("Expects a 32 byte hash value or hex encoded string. Got " + value);
35790
35791 if (value === null || isUndefined(value)) {
35792 throw error;
35793 }
35794
35795 var valueBuffer = undefined;
35796 if (isString(value)) {
35797 if (!/^[0-9A-Fa-f]{64}$/g.test(value)) {
35798 throw error;
35799 }
35800 valueBuffer = Buffer.from(value, "hex");
35801 } else if (Buffer.isBuffer(value)) {
35802 valueBuffer = Buffer.from(value);
35803 } else {
35804 throw error;
35805 }
35806
35807 if (!valueBuffer.length || valueBuffer.length != 32) {
35808 throw error;
35809 }
35810 }
35811 },
35812 none: {
35813
35814 /**
35815 * Returns an empty memo (`MemoNone`).
35816 * @returns {Memo}
35817 */
35818
35819 value: function none() {
35820 return new Memo(MemoNone);
35821 }
35822 },
35823 text: {
35824
35825 /**
35826 * Creates and returns a `MemoText` memo.
35827 * @param {string} text - memo text
35828 * @returns {Memo}
35829 */
35830
35831 value: (function (_text) {
35832 var _textWrapper = function text(_x) {
35833 return _text.apply(this, arguments);
35834 };
35835
35836 _textWrapper.toString = function () {
35837 return _text.toString();
35838 };
35839
35840 return _textWrapper;
35841 })(function (text) {
35842 return new Memo(MemoText, text);
35843 })
35844 },
35845 id: {
35846
35847 /**
35848 * Creates and returns a `MemoID` memo.
35849 * @param {string} id - 64-bit number represented as a string
35850 * @returns {Memo}
35851 */
35852
35853 value: (function (_id) {
35854 var _idWrapper = function id(_x2) {
35855 return _id.apply(this, arguments);
35856 };
35857
35858 _idWrapper.toString = function () {
35859 return _id.toString();
35860 };
35861
35862 return _idWrapper;
35863 })(function (id) {
35864 return new Memo(MemoID, id);
35865 })
35866 },
35867 hash: {
35868
35869 /**
35870 * Creates and returns a `MemoHash` memo.
35871 * @param {array|string} hash - 32 byte hash or hex encoded string
35872 * @returns {Memo}
35873 */
35874
35875 value: (function (_hash) {
35876 var _hashWrapper = function hash(_x3) {
35877 return _hash.apply(this, arguments);
35878 };
35879
35880 _hashWrapper.toString = function () {
35881 return _hash.toString();
35882 };
35883
35884 return _hashWrapper;
35885 })(function (hash) {
35886 return new Memo(MemoHash, hash);
35887 })
35888 },
35889 "return": {
35890
35891 /**
35892 * Creates and returns a `MemoReturn` memo.
35893 * @param {array|string} hash - 32 byte hash or hex encoded string
35894 * @returns {Memo}
35895 */
35896
35897 value: function _return(hash) {
35898 return new Memo(MemoReturn, hash);
35899 }
35900 },
35901 fromXDRObject: {
35902
35903 /**
35904 * Returns {@link Memo} from XDR memo object.
35905 * @param {xdr.Memo}
35906 * @returns {Memo}
35907 */
35908
35909 value: function fromXDRObject(object) {
35910 switch (object.arm()) {
35911 case "id":
35912 return Memo.id(object.value().toString());
35913 case "text":
35914 return Memo.text(object.value());
35915 case "hash":
35916 return Memo.hash(object.value());
35917 case "retHash":
35918 return Memo["return"](object.value());
35919 }
35920
35921 if (typeof object.value() === "undefined") {
35922 return Memo.none();
35923 }
35924
35925 throw new Error("Unknown type");
35926 }
35927 }
35928 });
35929
35930 return Memo;
35931})();
35932}).call(this,require("buffer").Buffer)
35933},{"./generated/stellar-xdr_generated":405,"bignumber.js":17,"buffer":49,"js-xdr":127,"lodash/clone":306,"lodash/isNull":327,"lodash/isString":333,"lodash/isUndefined":336}],410:[function(require,module,exports){
35934"use strict";
35935
35936var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
35937
35938var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
35939
35940Object.defineProperty(exports, "__esModule", {
35941 value: true
35942});
35943
35944var hash = require("./hashing").hash;
35945
35946/**
35947 * Contains passphrases for common networks:
35948 * * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015`
35949 * * `Networks.TESTNET`: `Test SDF Network ; September 2015`
35950 * @type {{PUBLIC: string, TESTNET: string}}
35951 */
35952var Networks = {
35953 PUBLIC: "Public Global Stellar Network ; September 2015",
35954 TESTNET: "Test SDF Network ; September 2015"
35955};
35956
35957exports.Networks = Networks;
35958var current = null;
35959
35960/**
35961 * The Network class provides helper methods to get the passphrase or id for different
35962 * stellar networks. It also provides the {@link Network.current} class method that returns the network
35963 * that will be used by this process for the purposes of generating signatures.
35964 *
35965 * You should select network your app will use before adding the first signature. You can use the `use`,
35966 * `usePublicNetwork` and `useTestNetwork` helper methods.
35967 *
35968 * Creates a new `Network` object.
35969 * @constructor
35970 * @param {string} networkPassphrase Network passphrase
35971 */
35972
35973var Network = exports.Network = (function () {
35974 function Network(networkPassphrase) {
35975 _classCallCheck(this, Network);
35976
35977 this._networkPassphrase = networkPassphrase;
35978 }
35979
35980 _createClass(Network, {
35981 networkPassphrase: {
35982
35983 /**
35984 * Returns network passphrase.
35985 * @returns {string}
35986 */
35987
35988 value: function networkPassphrase() {
35989 return this._networkPassphrase;
35990 }
35991 },
35992 networkId: {
35993
35994 /**
35995 * Returns Network ID. Network ID is SHA-256 hash of network passphrase.
35996 * @returns {string}
35997 */
35998
35999 value: function networkId() {
36000 return hash(this.networkPassphrase());
36001 }
36002 }
36003 }, {
36004 usePublicNetwork: {
36005
36006 /**
36007 * Use Stellar Public Network
36008 */
36009
36010 value: function usePublicNetwork() {
36011 this.use(new Network(Networks.PUBLIC));
36012 }
36013 },
36014 useTestNetwork: {
36015
36016 /**
36017 * Use test network.
36018 */
36019
36020 value: function useTestNetwork() {
36021 this.use(new Network(Networks.TESTNET));
36022 }
36023 },
36024 use: {
36025
36026 /**
36027 * Use network defined by Network object.
36028 * @param {Network} network Network to use
36029 */
36030
36031 value: function use(network) {
36032 current = network;
36033 }
36034 },
36035 current: {
36036
36037 /**
36038 * Returns currently selected network.
36039 * @returns {Network}
36040 */
36041
36042 value: (function (_current) {
36043 var _currentWrapper = function current() {
36044 return _current.apply(this, arguments);
36045 };
36046
36047 _currentWrapper.toString = function () {
36048 return _current.toString();
36049 };
36050
36051 return _currentWrapper;
36052 })(function () {
36053 return current;
36054 })
36055 }
36056 });
36057
36058 return Network;
36059})();
36060},{"./hashing":406}],411:[function(require,module,exports){
36061"use strict";
36062
36063var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };
36064
36065var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36066
36067var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
36068
36069var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
36070
36071Object.defineProperty(exports, "__esModule", {
36072 value: true
36073});
36074
36075var xdr = _interopRequire(require("./generated/stellar-xdr_generated"));
36076
36077var Keypair = require("./keypair").Keypair;
36078
36079var hash = require("./hashing").hash;
36080
36081var StrKey = require("./strkey").StrKey;
36082
36083var Hyper = require("js-xdr").Hyper;
36084
36085var Asset = require("./asset").Asset;
36086
36087var BigNumber = _interopRequire(require("bignumber.js"));
36088
36089var best_r = require("./util/continued_fraction").best_r;
36090
36091var trimEnd = _interopRequire(require("lodash/trimEnd"));
36092
36093var isUndefined = _interopRequire(require("lodash/isUndefined"));
36094
36095var isString = _interopRequire(require("lodash/isString"));
36096
36097var isNumber = _interopRequire(require("lodash/isNumber"));
36098
36099var isFinite = _interopRequire(require("lodash/isFinite"));
36100
36101var ops = _interopRequireWildcard(require("./operations/index"));
36102
36103var ONE = 10000000;
36104var MAX_INT64 = "9223372036854775807";
36105
36106/**
36107 * When set using `{@link Operation.setOptions}` option, requires the issuing account to
36108 * give other accounts permission before they can hold the issuing account’s credit.
36109 * @constant
36110 * @see [Account flags](https://www.stellar.org/developers/guides/concepts/accounts.html#flags)
36111 */
36112var AuthRequiredFlag = 1 << 0;
36113exports.AuthRequiredFlag = AuthRequiredFlag;
36114/**
36115 * When set using `{@link Operation.setOptions}` option, allows the issuing account to
36116 * revoke its credit held by other accounts.
36117 * @constant
36118 * @see [Account flags](https://www.stellar.org/developers/guides/concepts/accounts.html#flags)
36119 */
36120var AuthRevocableFlag = 1 << 1;
36121exports.AuthRevocableFlag = AuthRevocableFlag;
36122/**
36123 * When set using `{@link Operation.setOptions}` option, then none of the authorization flags
36124 * can be set and the account can never be deleted.
36125 * @constant
36126 * @see [Account flags](https://www.stellar.org/developers/guides/concepts/accounts.html#flags)
36127 */
36128var AuthImmutableFlag = 1 << 2;
36129
36130exports.AuthImmutableFlag = AuthImmutableFlag;
36131/**
36132 * `Operation` class represents [operations](https://www.stellar.org/developers/learn/concepts/operations.html) in Stellar network.
36133 * Use one of static methods to create operations:
36134 * * `{@link Operation.createAccount}`
36135 * * `{@link Operation.payment}`
36136 * * `{@link Operation.pathPayment}`
36137 * * `{@link Operation.manageOffer}`
36138 * * `{@link Operation.createPassiveOffer}`
36139 * * `{@link Operation.setOptions}`
36140 * * `{@link Operation.changeTrust}`
36141 * * `{@link Operation.allowTrust}`
36142 * * `{@link Operation.accountMerge}`
36143 * * `{@link Operation.inflation}`
36144 * * `{@link Operation.manageData}`
36145 * * `{@link Operation.bumpSequence}`
36146 *
36147 * @class Operation
36148 */
36149
36150var Operation = exports.Operation = (function () {
36151 function Operation() {
36152 _classCallCheck(this, Operation);
36153 }
36154
36155 _createClass(Operation, null, {
36156 setSourceAccount: {
36157 value: function setSourceAccount(opAttributes, opts) {
36158 if (opts.source) {
36159 if (!StrKey.isValidEd25519PublicKey(opts.source)) {
36160 throw new Error("Source address is invalid");
36161 }
36162 opAttributes.sourceAccount = Keypair.fromPublicKey(opts.source).xdrAccountId();
36163 }
36164 }
36165 },
36166 fromXDRObject: {
36167
36168 /**
36169 * Converts the XDR Operation object to the opts object used to create the XDR
36170 * operation.
36171 * @param {xdr.Operation} operation - An XDR Operation.
36172 * @return {Operation}
36173 */
36174
36175 value: function fromXDRObject(operation) {
36176 function accountIdtoAddress(accountId) {
36177 return StrKey.encodeEd25519PublicKey(accountId.ed25519());
36178 }
36179
36180 var result = {};
36181 if (operation.sourceAccount()) {
36182 result.source = accountIdtoAddress(operation.sourceAccount());
36183 }
36184
36185 var attrs = operation.body().value();
36186 switch (operation.body()["switch"]().name) {
36187 case "createAccount":
36188 result.type = "createAccount";
36189 result.destination = accountIdtoAddress(attrs.destination());
36190 result.startingBalance = this._fromXDRAmount(attrs.startingBalance());
36191 break;
36192 case "payment":
36193 result.type = "payment";
36194 result.destination = accountIdtoAddress(attrs.destination());
36195 result.asset = Asset.fromOperation(attrs.asset());
36196 result.amount = this._fromXDRAmount(attrs.amount());
36197 break;
36198 case "pathPayment":
36199 result.type = "pathPayment";
36200 result.sendAsset = Asset.fromOperation(attrs.sendAsset());
36201 result.sendMax = this._fromXDRAmount(attrs.sendMax());
36202 result.destination = accountIdtoAddress(attrs.destination());
36203 result.destAsset = Asset.fromOperation(attrs.destAsset());
36204 result.destAmount = this._fromXDRAmount(attrs.destAmount());
36205 var path = attrs.path();
36206 result.path = [];
36207 for (var i in path) {
36208 result.path.push(Asset.fromOperation(path[i]));
36209 }
36210 break;
36211 case "changeTrust":
36212 result.type = "changeTrust";
36213 result.line = Asset.fromOperation(attrs.line());
36214 result.limit = this._fromXDRAmount(attrs.limit());
36215 break;
36216 case "allowTrust":
36217 result.type = "allowTrust";
36218 result.trustor = accountIdtoAddress(attrs.trustor());
36219 result.assetCode = attrs.asset().value().toString();
36220 result.assetCode = trimEnd(result.assetCode, "\u0000");
36221 result.authorize = attrs.authorize();
36222 break;
36223 case "setOption":
36224 result.type = "setOptions";
36225 if (attrs.inflationDest()) {
36226 result.inflationDest = accountIdtoAddress(attrs.inflationDest());
36227 }
36228
36229 result.clearFlags = attrs.clearFlags();
36230 result.setFlags = attrs.setFlags();
36231 result.masterWeight = attrs.masterWeight();
36232 result.lowThreshold = attrs.lowThreshold();
36233 result.medThreshold = attrs.medThreshold();
36234 result.highThreshold = attrs.highThreshold();
36235 // home_domain is checked by iscntrl in stellar-core
36236 result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString("ascii") : undefined;
36237
36238 if (attrs.signer()) {
36239 var signer = {};
36240 var arm = attrs.signer().key().arm();
36241 if (arm == "ed25519") {
36242 signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key());
36243 } else if (arm == "preAuthTx") {
36244 signer.preAuthTx = attrs.signer().key().preAuthTx();
36245 } else if (arm == "hashX") {
36246 signer.sha256Hash = attrs.signer().key().hashX();
36247 }
36248
36249 signer.weight = attrs.signer().weight();
36250 result.signer = signer;
36251 }
36252 break;
36253 case "manageOffer":
36254 result.type = "manageOffer";
36255 result.selling = Asset.fromOperation(attrs.selling());
36256 result.buying = Asset.fromOperation(attrs.buying());
36257 result.amount = this._fromXDRAmount(attrs.amount());
36258 result.price = this._fromXDRPrice(attrs.price());
36259 result.offerId = attrs.offerId().toString();
36260 break;
36261 case "createPassiveOffer":
36262 result.type = "createPassiveOffer";
36263 result.selling = Asset.fromOperation(attrs.selling());
36264 result.buying = Asset.fromOperation(attrs.buying());
36265 result.amount = this._fromXDRAmount(attrs.amount());
36266 result.price = this._fromXDRPrice(attrs.price());
36267 break;
36268 case "accountMerge":
36269 result.type = "accountMerge";
36270 result.destination = accountIdtoAddress(attrs);
36271 break;
36272 case "manageDatum":
36273 result.type = "manageData";
36274 // manage_data.name is checked by iscntrl in stellar-core
36275 result.name = attrs.dataName().toString("ascii");
36276 result.value = attrs.dataValue();
36277 break;
36278 case "inflation":
36279 result.type = "inflation";
36280 break;
36281 case "bumpSequence":
36282 result.type = "bumpSequence";
36283 result.bumpTo = attrs.bumpTo().toString();
36284 break;
36285 default:
36286 throw new Error("Unknown operation");
36287 }
36288 return result;
36289 }
36290 },
36291 isValidAmount: {
36292 value: function isValidAmount(value) {
36293 var allowZero = arguments[1] === undefined ? false : arguments[1];
36294
36295 if (!isString(value)) {
36296 return false;
36297 }
36298
36299 var amount = undefined;
36300 try {
36301 amount = new BigNumber(value);
36302 } catch (e) {
36303 return false;
36304 }
36305
36306 switch (true) {
36307 // == 0
36308 case !allowZero && amount.isZero():
36309 // < 0
36310 case amount.isNegative():
36311 // > Max value
36312 case amount.times(ONE).greaterThan(new BigNumber(MAX_INT64).toString()):
36313 // Decimal places (max 7)
36314 case amount.decimalPlaces() > 7:
36315 // NaN or Infinity
36316 case amount.isNaN() || !amount.isFinite():
36317 return false;
36318 default:
36319 return true;
36320 }
36321 }
36322 },
36323 constructAmountRequirementsError: {
36324 value: function constructAmountRequirementsError(arg) {
36325 return "" + arg + " argument must be of type String, represent a positive number and have at most 7 digits after the decimal";
36326 }
36327 },
36328 _checkUnsignedIntValue: {
36329
36330 /**
36331 * Returns value converted to uint32 value or undefined.
36332 * If `value` is not `Number`, `String` or `Undefined` then throws an error.
36333 * Used in {@link Operation.setOptions}.
36334 * @private
36335 * @param {string} name Name of the property (used in error message only)
36336 * @param {*} value Value to check
36337 * @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`)
36338 * @returns {undefined|Number}
36339 * @private
36340 */
36341
36342 value: function _checkUnsignedIntValue(name, value) {
36343 var isValidFunction = arguments[2] === undefined ? null : arguments[2];
36344
36345 if (isUndefined(value)) {
36346 return undefined;
36347 }
36348
36349 if (isString(value)) {
36350 value = parseFloat(value);
36351 }
36352
36353 switch (true) {
36354 case !isNumber(value) || !isFinite(value) || value % 1 !== 0:
36355 throw new Error("" + name + " value is invalid");
36356 case value < 0:
36357 throw new Error("" + name + " value must be unsigned");
36358 case !isValidFunction || isValidFunction && isValidFunction(value, name):
36359 return value;
36360 default:
36361 throw new Error("" + name + " value is invalid");
36362 }
36363 }
36364 },
36365 _toXDRAmount: {
36366
36367 /**
36368 * @private
36369 */
36370
36371 value: function _toXDRAmount(value) {
36372 var amount = new BigNumber(value).mul(ONE);
36373 return Hyper.fromString(amount.toString());
36374 }
36375 },
36376 _fromXDRAmount: {
36377
36378 /**
36379 * @private
36380 */
36381
36382 value: function _fromXDRAmount(value) {
36383 return new BigNumber(value).div(ONE).toString();
36384 }
36385 },
36386 _fromXDRPrice: {
36387
36388 /**
36389 * @private
36390 */
36391
36392 value: function _fromXDRPrice(price) {
36393 var n = new BigNumber(price.n());
36394 return n.div(new BigNumber(price.d())).toString();
36395 }
36396 },
36397 _toXDRPrice: {
36398
36399 /**
36400 * @private
36401 */
36402
36403 value: function _toXDRPrice(price) {
36404 var xdrObject = undefined;
36405 if (price.n && price.d) {
36406 xdrObject = new xdr.Price(price);
36407 } else {
36408 price = new BigNumber(price);
36409 var approx = best_r(price);
36410 xdrObject = new xdr.Price({
36411 n: parseInt(approx[0]),
36412 d: parseInt(approx[1])
36413 });
36414 }
36415
36416 if (xdrObject.n() < 0 || xdrObject.d() < 0) {
36417 throw new Error("price must be positive");
36418 }
36419
36420 return xdrObject;
36421 }
36422 }
36423 });
36424
36425 return Operation;
36426})();
36427
36428// Attach all imported operations as static methods on the Operation class
36429Operation.accountMerge = ops.accountMerge;
36430Operation.allowTrust = ops.allowTrust;
36431Operation.bumpSequence = ops.bumpSequence;
36432Operation.changeTrust = ops.changeTrust;
36433Operation.createAccount = ops.createAccount;
36434Operation.createPassiveOffer = ops.createPassiveOffer;
36435Operation.inflation = ops.inflation;
36436Operation.manageData = ops.manageData;
36437Operation.manageOffer = ops.manageOffer;
36438Operation.pathPayment = ops.pathPayment;
36439Operation.payment = ops.payment;
36440Operation.setOptions = ops.setOptions;
36441},{"./asset":403,"./generated/stellar-xdr_generated":405,"./hashing":406,"./keypair":408,"./operations/index":418,"./strkey":426,"./util/continued_fraction":430,"bignumber.js":17,"js-xdr":127,"lodash/isFinite":323,"lodash/isNumber":328,"lodash/isString":333,"lodash/isUndefined":336,"lodash/trimEnd":351}],412:[function(require,module,exports){
36442"use strict";
36443
36444var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36445
36446Object.defineProperty(exports, "__esModule", {
36447 value: true
36448});
36449
36450var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36451
36452var Keypair = require("../keypair").Keypair;
36453
36454var StrKey = require("../strkey").StrKey;
36455
36456/**
36457 * Transfers native balance to destination account.
36458 * @function
36459 * @alias Operation.accountMerge
36460 * @param {object} opts
36461 * @param {string} opts.destination - Destination to merge the source account into.
36462 * @param {string} [opts.source] - The source account (defaults to transaction source).
36463 * @returns {xdr.AccountMergeOp}
36464 */
36465var accountMerge = function accountMerge(opts) {
36466 var opAttributes = {};
36467 if (!StrKey.isValidEd25519PublicKey(opts.destination)) {
36468 throw new Error("destination is invalid");
36469 }
36470 opAttributes.body = xdr.OperationBody.accountMerge(Keypair.fromPublicKey(opts.destination).xdrAccountId());
36471 this.setSourceAccount(opAttributes, opts);
36472
36473 return new xdr.Operation(opAttributes);
36474};
36475exports.accountMerge = accountMerge;
36476},{"../generated/stellar-xdr_generated":405,"../keypair":408,"../strkey":426}],413:[function(require,module,exports){
36477"use strict";
36478
36479var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36480
36481Object.defineProperty(exports, "__esModule", {
36482 value: true
36483});
36484
36485var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36486
36487var Keypair = require("../keypair").Keypair;
36488
36489var StrKey = require("../strkey").StrKey;
36490
36491var padEnd = _interopRequire(require("lodash/padEnd"));
36492
36493/**
36494 * Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another
36495 * account to hold your account's credit for a given asset.
36496 * @function
36497 * @alias Operation.allowTrust
36498 * @param {object} opts
36499 * @param {string} opts.trustor - The trusting account (the one being authorized)
36500 * @param {string} opts.assetCode - The asset code being authorized.
36501 * @param {boolean} opts.authorize - True to authorize the line, false to deauthorize.
36502 * @param {string} [opts.source] - The source account (defaults to transaction source).
36503 * @returns {xdr.AllowTrustOp}
36504 */
36505var allowTrust = function allowTrust(opts) {
36506 if (!StrKey.isValidEd25519PublicKey(opts.trustor)) {
36507 throw new Error("trustor is invalid");
36508 }
36509 var attributes = {};
36510 attributes.trustor = Keypair.fromPublicKey(opts.trustor).xdrAccountId();
36511 if (opts.assetCode.length <= 4) {
36512 var code = padEnd(opts.assetCode, 4, "\u0000");
36513 attributes.asset = xdr.AllowTrustOpAsset.assetTypeCreditAlphanum4(code);
36514 } else if (opts.assetCode.length <= 12) {
36515 var code = padEnd(opts.assetCode, 12, "\u0000");
36516 attributes.asset = xdr.AllowTrustOpAsset.assetTypeCreditAlphanum12(code);
36517 } else {
36518 throw new Error("Asset code must be 12 characters at max.");
36519 }
36520 attributes.authorize = opts.authorize;
36521 var allowTrustOp = new xdr.AllowTrustOp(attributes);
36522
36523 var opAttributes = {};
36524 opAttributes.body = xdr.OperationBody.allowTrust(allowTrustOp);
36525 this.setSourceAccount(opAttributes, opts);
36526
36527 return new xdr.Operation(opAttributes);
36528};
36529exports.allowTrust = allowTrust;
36530},{"../generated/stellar-xdr_generated":405,"../keypair":408,"../strkey":426,"lodash/padEnd":341}],414:[function(require,module,exports){
36531"use strict";
36532
36533var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36534
36535Object.defineProperty(exports, "__esModule", {
36536 value: true
36537});
36538
36539var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36540
36541var Hyper = require("js-xdr").Hyper;
36542
36543var BigNumber = _interopRequire(require("bignumber.js"));
36544
36545var isString = _interopRequire(require("lodash/isString"));
36546
36547/**
36548 * This operation bumps sequence number.
36549 * @function
36550 * @alias Operation.bumpSequence
36551 * @param {object} opts
36552 * @param {string} opts.bumpTo - Sequence number to bump to.
36553 * @param {string} [opts.source] - The optional source account.
36554 * @returns {xdr.BumpSequenceOp}
36555 */
36556var bumpSequence = function bumpSequence(opts) {
36557 var attributes = {};
36558
36559 if (!isString(opts.bumpTo)) {
36560 throw new Error("bumpTo must be a string");
36561 }
36562
36563 try {
36564 new BigNumber(opts.bumpTo);
36565 } catch (e) {
36566 throw new Error("bumpTo must be a stringified number");
36567 }
36568
36569 attributes.bumpTo = Hyper.fromString(opts.bumpTo);
36570
36571 var bumpSequenceOp = new xdr.BumpSequenceOp(attributes);
36572
36573 var opAttributes = {};
36574 opAttributes.body = xdr.OperationBody.bumpSequence(bumpSequenceOp);
36575 this.setSourceAccount(opAttributes, opts);
36576
36577 return new xdr.Operation(opAttributes);
36578};
36579exports.bumpSequence = bumpSequence;
36580},{"../generated/stellar-xdr_generated":405,"bignumber.js":17,"js-xdr":127,"lodash/isString":333}],415:[function(require,module,exports){
36581"use strict";
36582
36583var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36584
36585Object.defineProperty(exports, "__esModule", {
36586 value: true
36587});
36588
36589var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36590
36591var Keypair = require("../keypair").Keypair;
36592
36593var isUndefined = _interopRequire(require("lodash/isUndefined"));
36594
36595var Hyper = require("js-xdr").Hyper;
36596
36597var BigNumber = _interopRequire(require("bignumber.js"));
36598
36599var MAX_INT64 = "9223372036854775807";
36600
36601/**
36602 * Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a
36603 * trust line for a given asset from the source account to another. The issuer being
36604 * trusted and the asset code are in the given Asset object.
36605 * @function
36606 * @alias Operation.changeTrust
36607 * @param {object} opts
36608 * @param {Asset} opts.asset - The asset for the trust line.
36609 * @param {string} [opts.limit] - The limit for the asset, defaults to max int64.
36610 * If the limit is set to "0" it deletes the trustline.
36611 * @param {string} [opts.source] - The source account (defaults to transaction source).
36612 * @returns {xdr.ChangeTrustOp}
36613 */
36614var changeTrust = function changeTrust(opts) {
36615 var attributes = {};
36616 attributes.line = opts.asset.toXDRObject();
36617 if (!isUndefined(opts.limit) && !this.isValidAmount(opts.limit, true)) {
36618 throw new TypeError(this.constructAmountRequirementsError("limit"));
36619 }
36620
36621 if (opts.limit) {
36622 attributes.limit = this._toXDRAmount(opts.limit);
36623 } else {
36624 attributes.limit = Hyper.fromString(new BigNumber(MAX_INT64).toString());
36625 }
36626
36627 if (opts.source) {
36628 attributes.source = opts.source.masterKeypair;
36629 }
36630 var changeTrustOP = new xdr.ChangeTrustOp(attributes);
36631
36632 var opAttributes = {};
36633 opAttributes.body = xdr.OperationBody.changeTrust(changeTrustOP);
36634 this.setSourceAccount(opAttributes, opts);
36635
36636 return new xdr.Operation(opAttributes);
36637};
36638exports.changeTrust = changeTrust;
36639},{"../generated/stellar-xdr_generated":405,"../keypair":408,"bignumber.js":17,"js-xdr":127,"lodash/isUndefined":336}],416:[function(require,module,exports){
36640"use strict";
36641
36642var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36643
36644Object.defineProperty(exports, "__esModule", {
36645 value: true
36646});
36647
36648var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36649
36650var Keypair = require("../keypair").Keypair;
36651
36652var StrKey = require("../strkey").StrKey;
36653
36654/**
36655 * Create and fund a non existent account.
36656 * @function
36657 * @alias Operation.createAccount
36658 * @param {object} opts
36659 * @param {string} opts.destination - Destination account ID to create an account for.
36660 * @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater
36661 * than the [reserve balance amount](https://www.stellar.org/developers/learn/concepts/fees.html).
36662 * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account.
36663 * @returns {xdr.CreateAccountOp}
36664 */
36665var createAccount = (function (_createAccount) {
36666 var _createAccountWrapper = function createAccount(_x) {
36667 return _createAccount.apply(this, arguments);
36668 };
36669
36670 _createAccountWrapper.toString = function () {
36671 return _createAccount.toString();
36672 };
36673
36674 return _createAccountWrapper;
36675})(function (opts) {
36676 if (!StrKey.isValidEd25519PublicKey(opts.destination)) {
36677 throw new Error("destination is invalid");
36678 }
36679 if (!this.isValidAmount(opts.startingBalance)) {
36680 throw new TypeError(this.constructAmountRequirementsError("startingBalance"));
36681 }
36682 var attributes = {};
36683 attributes.destination = Keypair.fromPublicKey(opts.destination).xdrAccountId();
36684 attributes.startingBalance = this._toXDRAmount(opts.startingBalance);
36685 var createAccount = new xdr.CreateAccountOp(attributes);
36686
36687 var opAttributes = {};
36688 opAttributes.body = xdr.OperationBody.createAccount(createAccount);
36689 this.setSourceAccount(opAttributes, opts);
36690
36691 return new xdr.Operation(opAttributes);
36692});
36693exports.createAccount = createAccount;
36694},{"../generated/stellar-xdr_generated":405,"../keypair":408,"../strkey":426}],417:[function(require,module,exports){
36695"use strict";
36696
36697var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36698
36699Object.defineProperty(exports, "__esModule", {
36700 value: true
36701});
36702
36703var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36704
36705var isUndefined = _interopRequire(require("lodash/isUndefined"));
36706
36707/**
36708 * Returns a XDR CreatePasiveOfferOp. A "create passive offer" operation creates an
36709 * offer that won't consume a counter offer that exactly matches this offer. This is
36710 * useful for offers just used as 1:1 exchanges for path payments. Use manage offer
36711 * to manage this offer after using this operation to create it.
36712 * @function
36713 * @alias Operation.createPassiveOffer
36714 * @param {object} opts
36715 * @param {Asset} opts.selling - What you're selling.
36716 * @param {Asset} opts.buying - What you're buying.
36717 * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer.
36718 * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`.
36719 * @param {number} opts.price.n - If `opts.price` is an object: the price numerator
36720 * @param {number} opts.price.d - If `opts.price` is an object: the price denominator
36721 * @param {string} [opts.source] - The source account (defaults to transaction source).
36722 * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found.
36723 * @returns {xdr.CreatePassiveOfferOp}
36724 */
36725var createPassiveOffer = function createPassiveOffer(opts) {
36726 var attributes = {};
36727 attributes.selling = opts.selling.toXDRObject();
36728 attributes.buying = opts.buying.toXDRObject();
36729 if (!this.isValidAmount(opts.amount)) {
36730 throw new TypeError(this.constructAmountRequirementsError("amount"));
36731 }
36732 attributes.amount = this._toXDRAmount(opts.amount);
36733 if (isUndefined(opts.price)) {
36734 throw new TypeError("price argument is required");
36735 }
36736 attributes.price = this._toXDRPrice(opts.price);
36737 var createPassiveOfferOp = new xdr.CreatePassiveOfferOp(attributes);
36738
36739 var opAttributes = {};
36740 opAttributes.body = xdr.OperationBody.createPassiveOffer(createPassiveOfferOp);
36741 this.setSourceAccount(opAttributes, opts);
36742
36743 return new xdr.Operation(opAttributes);
36744};
36745exports.createPassiveOffer = createPassiveOffer;
36746},{"../generated/stellar-xdr_generated":405,"lodash/isUndefined":336}],418:[function(require,module,exports){
36747"use strict";
36748
36749Object.defineProperty(exports, "__esModule", {
36750 value: true
36751});
36752exports.accountMerge = require("./account_merge").accountMerge;
36753exports.allowTrust = require("./allow_trust").allowTrust;
36754exports.bumpSequence = require("./bump_sequence").bumpSequence;
36755exports.changeTrust = require("./change_trust").changeTrust;
36756exports.createAccount = require("./create_account").createAccount;
36757exports.createPassiveOffer = require("./create_passive_offer").createPassiveOffer;
36758exports.inflation = require("./inflation").inflation;
36759exports.manageData = require("./manage_data").manageData;
36760exports.manageOffer = require("./manage_offer").manageOffer;
36761exports.pathPayment = require("./path_payment").pathPayment;
36762exports.payment = require("./payment").payment;
36763exports.setOptions = require("./set_options").setOptions;
36764},{"./account_merge":412,"./allow_trust":413,"./bump_sequence":414,"./change_trust":415,"./create_account":416,"./create_passive_offer":417,"./inflation":419,"./manage_data":420,"./manage_offer":421,"./path_payment":422,"./payment":423,"./set_options":424}],419:[function(require,module,exports){
36765"use strict";
36766
36767var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36768
36769Object.defineProperty(exports, "__esModule", {
36770 value: true
36771});
36772
36773var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36774
36775/**
36776 * This operation generates the inflation.
36777 * @function
36778 * @alias Operation.inflation
36779 * @param {object} [opts]
36780 * @param {string} [opts.source] - The optional source account.
36781 * @returns {xdr.InflationOp}
36782 */
36783var inflation = function inflation() {
36784 var opts = arguments[0] === undefined ? {} : arguments[0];
36785
36786 var opAttributes = {};
36787 opAttributes.body = xdr.OperationBody.inflation();
36788 this.setSourceAccount(opAttributes, opts);
36789 return new xdr.Operation(opAttributes);
36790};
36791exports.inflation = inflation;
36792},{"../generated/stellar-xdr_generated":405}],420:[function(require,module,exports){
36793(function (Buffer){
36794"use strict";
36795
36796var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36797
36798Object.defineProperty(exports, "__esModule", {
36799 value: true
36800});
36801
36802var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36803
36804var isString = _interopRequire(require("lodash/isString"));
36805
36806/**
36807 * This operation adds data entry to the ledger.
36808 * @function
36809 * @alias Operation.manageData
36810 * @param {object} opts
36811 * @param {string} opts.name - The name of the data entry.
36812 * @param {string|Buffer} opts.value - The value of the data entry.
36813 * @param {string} [opts.source] - The optional source account.
36814 * @returns {xdr.ManageDataOp}
36815 */
36816var manageData = function manageData(opts) {
36817 var attributes = {};
36818
36819 if (!(isString(opts.name) && opts.name.length <= 64)) {
36820 throw new Error("name must be a string, up to 64 characters");
36821 }
36822 attributes.dataName = opts.name;
36823
36824 if (!isString(opts.value) && !Buffer.isBuffer(opts.value) && opts.value !== null) {
36825 throw new Error("value must be a string, Buffer or null");
36826 }
36827
36828 if (isString(opts.value)) {
36829 attributes.dataValue = Buffer.from(opts.value);
36830 } else {
36831 attributes.dataValue = opts.value;
36832 }
36833
36834 if (attributes.dataValue !== null && attributes.dataValue.length > 64) {
36835 throw new Error("value cannot be longer that 64 bytes");
36836 }
36837
36838 var manageDataOp = new xdr.ManageDataOp(attributes);
36839
36840 var opAttributes = {};
36841 opAttributes.body = xdr.OperationBody.manageDatum(manageDataOp);
36842 this.setSourceAccount(opAttributes, opts);
36843
36844 return new xdr.Operation(opAttributes);
36845};
36846exports.manageData = manageData;
36847}).call(this,require("buffer").Buffer)
36848},{"../generated/stellar-xdr_generated":405,"buffer":49,"lodash/isString":333}],421:[function(require,module,exports){
36849"use strict";
36850
36851var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36852
36853Object.defineProperty(exports, "__esModule", {
36854 value: true
36855});
36856
36857var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36858
36859var isUndefined = _interopRequire(require("lodash/isUndefined"));
36860
36861var UnsignedHyper = require("js-xdr").UnsignedHyper;
36862
36863/**
36864 * Returns a XDR ManageOfferOp. A "manage offer" operation creates, updates, or
36865 * deletes an offer.
36866 * @function
36867 * @alias Operation.manageOffer
36868 * @param {object} opts
36869 * @param {Asset} opts.selling - What you're selling.
36870 * @param {Asset} opts.buying - What you're buying.
36871 * @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer.
36872 * @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`.
36873 * @param {number} opts.price.n - If `opts.price` is an object: the price numerator
36874 * @param {number} opts.price.d - If `opts.price` is an object: the price denominator
36875 * @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer.
36876 * @param {string} [opts.source] - The source account (defaults to transaction source).
36877 * @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found.
36878 * @returns {xdr.ManageOfferOp}
36879 */
36880var manageOffer = function manageOffer(opts) {
36881 var attributes = {};
36882 attributes.selling = opts.selling.toXDRObject();
36883 attributes.buying = opts.buying.toXDRObject();
36884 if (!this.isValidAmount(opts.amount, true)) {
36885 throw new TypeError(this.constructAmountRequirementsError("amount"));
36886 }
36887 attributes.amount = this._toXDRAmount(opts.amount);
36888 if (isUndefined(opts.price)) {
36889 throw new TypeError("price argument is required");
36890 }
36891 attributes.price = this._toXDRPrice(opts.price);
36892
36893 if (!isUndefined(opts.offerId)) {
36894 opts.offerId = opts.offerId.toString();
36895 } else {
36896 opts.offerId = "0";
36897 }
36898 attributes.offerId = UnsignedHyper.fromString(opts.offerId);
36899 var manageOfferOp = new xdr.ManageOfferOp(attributes);
36900
36901 var opAttributes = {};
36902 opAttributes.body = xdr.OperationBody.manageOffer(manageOfferOp);
36903 this.setSourceAccount(opAttributes, opts);
36904
36905 return new xdr.Operation(opAttributes);
36906};
36907exports.manageOffer = manageOffer;
36908},{"../generated/stellar-xdr_generated":405,"js-xdr":127,"lodash/isUndefined":336}],422:[function(require,module,exports){
36909"use strict";
36910
36911var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36912
36913Object.defineProperty(exports, "__esModule", {
36914 value: true
36915});
36916
36917var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36918
36919var Keypair = require("../keypair").Keypair;
36920
36921var StrKey = require("../strkey").StrKey;
36922
36923/**
36924 * Returns a XDR PaymentOp. A "payment" operation send the specified amount to the
36925 * destination account, optionally through a path. XLM payments create the destination
36926 * account if it does not exist.
36927 * @function
36928 * @alias Operation.pathPayment
36929 * @param {object} opts
36930 * @param {Asset} opts.sendAsset - The asset to pay with.
36931 * @param {string} opts.sendMax - The maximum amount of sendAsset to send.
36932 * @param {string} opts.destination - The destination account to send to.
36933 * @param {Asset} opts.destAsset - The asset the destination will receive.
36934 * @param {string} opts.destAmount - The amount the destination receives.
36935 * @param {Asset[]} opts.path - An array of Asset objects to use as the path.
36936 * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account.
36937 * @returns {xdr.PathPaymentOp}
36938 */
36939var pathPayment = function pathPayment(opts) {
36940 switch (true) {
36941 case !opts.sendAsset:
36942 throw new Error("Must specify a send asset");
36943 case !this.isValidAmount(opts.sendMax):
36944 throw new TypeError(this.constructAmountRequirementsError("sendMax"));
36945 case !StrKey.isValidEd25519PublicKey(opts.destination):
36946 throw new Error("destination is invalid");
36947 case !opts.destAsset:
36948 throw new Error("Must provide a destAsset for a payment operation");
36949 case !this.isValidAmount(opts.destAmount):
36950 throw new TypeError(this.constructAmountRequirementsError("destAmount"));
36951 }
36952
36953 var attributes = {};
36954 attributes.sendAsset = opts.sendAsset.toXDRObject();
36955 attributes.sendMax = this._toXDRAmount(opts.sendMax);
36956 attributes.destination = Keypair.fromPublicKey(opts.destination).xdrAccountId();
36957 attributes.destAsset = opts.destAsset.toXDRObject();
36958 attributes.destAmount = this._toXDRAmount(opts.destAmount);
36959
36960 var path = opts.path ? opts.path : [];
36961 attributes.path = path.map(function (x) {
36962 return x.toXDRObject();
36963 });
36964
36965 var payment = new xdr.PathPaymentOp(attributes);
36966
36967 var opAttributes = {};
36968 opAttributes.body = xdr.OperationBody.pathPayment(payment);
36969 this.setSourceAccount(opAttributes, opts);
36970
36971 return new xdr.Operation(opAttributes);
36972};
36973exports.pathPayment = pathPayment;
36974},{"../generated/stellar-xdr_generated":405,"../keypair":408,"../strkey":426}],423:[function(require,module,exports){
36975"use strict";
36976
36977var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
36978
36979Object.defineProperty(exports, "__esModule", {
36980 value: true
36981});
36982
36983var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
36984
36985var Keypair = require("../keypair").Keypair;
36986
36987var StrKey = require("../strkey").StrKey;
36988
36989/**
36990 * Create a payment operation.
36991 * @function
36992 * @alias Operation.payment
36993 * @param {object} opts
36994 * @param {string} opts.destination - The destination account ID.
36995 * @param {Asset} opts.asset - The asset to send.
36996 * @param {string} opts.amount - The amount to send.
36997 * @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account.
36998 * @returns {xdr.PaymentOp}
36999 */
37000var payment = (function (_payment) {
37001 var _paymentWrapper = function payment(_x) {
37002 return _payment.apply(this, arguments);
37003 };
37004
37005 _paymentWrapper.toString = function () {
37006 return _payment.toString();
37007 };
37008
37009 return _paymentWrapper;
37010})(function (opts) {
37011 if (!StrKey.isValidEd25519PublicKey(opts.destination)) {
37012 throw new Error("destination is invalid");
37013 }
37014 if (!opts.asset) {
37015 throw new Error("Must provide an asset for a payment operation");
37016 }
37017 if (!this.isValidAmount(opts.amount)) {
37018 throw new TypeError(this.constructAmountRequirementsError("amount"));
37019 }
37020
37021 var attributes = {};
37022 attributes.destination = Keypair.fromPublicKey(opts.destination).xdrAccountId();
37023 attributes.asset = opts.asset.toXDRObject();
37024 attributes.amount = this._toXDRAmount(opts.amount);
37025 var payment = new xdr.PaymentOp(attributes);
37026
37027 var opAttributes = {};
37028 opAttributes.body = xdr.OperationBody.payment(payment);
37029 this.setSourceAccount(opAttributes, opts);
37030
37031 return new xdr.Operation(opAttributes);
37032});
37033exports.payment = payment;
37034},{"../generated/stellar-xdr_generated":405,"../keypair":408,"../strkey":426}],424:[function(require,module,exports){
37035(function (Buffer){
37036"use strict";
37037
37038var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
37039
37040Object.defineProperty(exports, "__esModule", {
37041 value: true
37042});
37043
37044var xdr = _interopRequire(require("../generated/stellar-xdr_generated"));
37045
37046var Keypair = require("../keypair").Keypair;
37047
37048var StrKey = require("../strkey").StrKey;
37049
37050var isUndefined = _interopRequire(require("lodash/isUndefined"));
37051
37052var isString = _interopRequire(require("lodash/isString"));
37053
37054/**
37055 * Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags,
37056 * set the account's inflation destination, and/or add new signers to the account.
37057 * The flags used in `opts.clearFlags` and `opts.setFlags` can be the following:
37058 * - `{@link AuthRequiredFlag}`
37059 * - `{@link AuthRevocableFlag}`
37060 * - `{@link AuthImmutableFlag}`
37061 *
37062 * It's possible to set/clear multiple flags at once using logical or.
37063 * @function
37064 * @alias Operation.setOptions
37065 * @param {object} opts
37066 * @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination.
37067 * @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear.
37068 * @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set.
37069 * @param {number|string} [opts.masterWeight] - The master key weight.
37070 * @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold.
37071 * @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold.
37072 * @param {number|string} [opts.highThreshold] - The sum weight for the high threshold.
37073 * @param {object} [opts.signer] - Add or remove a signer from the account. The signer is
37074 * deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined.
37075 * @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer.
37076 * @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction.
37077 * @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds.
37078 * @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255)
37079 * @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup.
37080 * @param {string} [opts.source] - The source account (defaults to transaction source).
37081 * @returns {xdr.SetOptionsOp}
37082 * @see [Account flags](https://www.stellar.org/developers/guides/concepts/accounts.html#flags)
37083 */
37084var setOptions = function setOptions(opts) {
37085 var attributes = {};
37086
37087 if (opts.inflationDest) {
37088 if (!StrKey.isValidEd25519PublicKey(opts.inflationDest)) {
37089 throw new Error("inflationDest is invalid");
37090 }
37091 attributes.inflationDest = Keypair.fromPublicKey(opts.inflationDest).xdrAccountId();
37092 }
37093
37094 var weightCheckFunction = function (value, name) {
37095 if (value >= 0 && value <= 255) {
37096 return true;
37097 } else {
37098 throw new Error("" + name + " value must be between 0 and 255");
37099 }
37100 };
37101
37102 attributes.clearFlags = this._checkUnsignedIntValue("clearFlags", opts.clearFlags);
37103 attributes.setFlags = this._checkUnsignedIntValue("setFlags", opts.setFlags);
37104 attributes.masterWeight = this._checkUnsignedIntValue("masterWeight", opts.masterWeight, weightCheckFunction);
37105 attributes.lowThreshold = this._checkUnsignedIntValue("lowThreshold", opts.lowThreshold, weightCheckFunction);
37106 attributes.medThreshold = this._checkUnsignedIntValue("medThreshold", opts.medThreshold, weightCheckFunction);
37107 attributes.highThreshold = this._checkUnsignedIntValue("highThreshold", opts.highThreshold, weightCheckFunction);
37108
37109 if (!isUndefined(opts.homeDomain) && !isString(opts.homeDomain)) {
37110 throw new TypeError("homeDomain argument must be of type String");
37111 }
37112 attributes.homeDomain = opts.homeDomain;
37113
37114 if (opts.signer) {
37115 var weight = this._checkUnsignedIntValue("signer.weight", opts.signer.weight, weightCheckFunction);
37116 var key = undefined;
37117
37118 var setValues = 0;
37119
37120 if (opts.signer.ed25519PublicKey) {
37121 if (!StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) {
37122 throw new Error("signer.ed25519PublicKey is invalid.");
37123 }
37124 var rawKey = StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey);
37125 key = new xdr.SignerKey.signerKeyTypeEd25519(rawKey);
37126 setValues++;
37127 }
37128
37129 if (opts.signer.preAuthTx) {
37130 if (isString(opts.signer.preAuthTx)) {
37131 opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, "hex");
37132 }
37133
37134 if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length == 32)) {
37135 throw new Error("signer.preAuthTx must be 32 bytes Buffer.");
37136 }
37137 key = new xdr.SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx);
37138 setValues++;
37139 }
37140
37141 if (opts.signer.sha256Hash) {
37142 if (isString(opts.signer.sha256Hash)) {
37143 opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, "hex");
37144 }
37145
37146 if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length == 32)) {
37147 throw new Error("signer.sha256Hash must be 32 bytes Buffer.");
37148 }
37149 key = new xdr.SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash);
37150 setValues++;
37151 }
37152
37153 if (setValues != 1) {
37154 throw new Error("Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.");
37155 }
37156
37157 attributes.signer = new xdr.Signer({ key: key, weight: weight });
37158 }
37159
37160 var setOptionsOp = new xdr.SetOptionsOp(attributes);
37161
37162 var opAttributes = {};
37163 opAttributes.body = xdr.OperationBody.setOption(setOptionsOp);
37164 this.setSourceAccount(opAttributes, opts);
37165
37166 return new xdr.Operation(opAttributes);
37167};
37168exports.setOptions = setOptions;
37169}).call(this,require("buffer").Buffer)
37170},{"../generated/stellar-xdr_generated":405,"../keypair":408,"../strkey":426,"buffer":49,"lodash/isString":333,"lodash/isUndefined":336}],425:[function(require,module,exports){
37171(function (Buffer){
37172"use strict";
37173
37174exports.sign = sign;
37175exports.verify = verify;
37176Object.defineProperty(exports, "__esModule", {
37177 value: true
37178});
37179// This module provides the signing functionality used by the stellar network
37180// The code below may look a little strange... this is because we try to provide
37181// the most efficient signing method possible. First, we try to load the
37182// native ed25519 package for node.js environments, and if that fails we
37183// fallback to tweetnacl.js
37184
37185var actualMethods = {};
37186
37187/**
37188 * Use this flag to check if fast signing (provided by `ed25519` package) is available.
37189 * If your app is signing a large number of transaction or verifying a large number
37190 * of signatures make sure `ed25519` package is installed.
37191 */
37192var FastSigning = checkFastSigning();
37193
37194exports.FastSigning = FastSigning;
37195
37196function sign(data, secretKey) {
37197 return actualMethods.sign(data, secretKey);
37198}
37199
37200function verify(data, signature, publicKey) {
37201 return actualMethods.verify(data, signature, publicKey);
37202}
37203
37204function checkFastSigning() {
37205 return typeof window === "undefined" ? checkFastSigningNode() : checkFastSigningBrowser();
37206}
37207
37208function checkFastSigningNode() {
37209 // NOTE: we use commonjs style require here because es6 imports
37210 // can only occur at the top level. thanks, obama.
37211 var ed25519 = undefined;
37212 try {
37213 ed25519 = require("ed25519");
37214 } catch (err) {
37215 return checkFastSigningBrowser();
37216 }
37217
37218 actualMethods.sign = function (data, secretKey) {
37219 return ed25519.Sign(Buffer.from(data), secretKey);
37220 };
37221
37222 actualMethods.verify = function (data, signature, publicKey) {
37223 data = Buffer.from(data);
37224 try {
37225 return ed25519.Verify(data, signature, publicKey);
37226 } catch (e) {
37227 return false;
37228 }
37229 };
37230
37231 return true;
37232}
37233
37234function checkFastSigningBrowser() {
37235 // fallback to tweetnacl.js if we're in the browser or
37236 // if there was a failure installing ed25519
37237 var nacl = require("tweetnacl");
37238
37239 actualMethods.sign = function (data, secretKey) {
37240 data = Buffer.from(data);
37241 data = new Uint8Array(data.toJSON().data);
37242 secretKey = new Uint8Array(secretKey.toJSON().data);
37243
37244 var signature = nacl.sign.detached(data, secretKey);
37245
37246 return Buffer.from(signature);
37247 };
37248
37249 actualMethods.verify = function (data, signature, publicKey) {
37250 data = Buffer.from(data);
37251 data = new Uint8Array(data.toJSON().data);
37252 signature = new Uint8Array(signature.toJSON().data);
37253 publicKey = new Uint8Array(publicKey.toJSON().data);
37254
37255 return nacl.sign.detached.verify(data, signature, publicKey);
37256 };
37257
37258 return false;
37259}
37260}).call(this,require("buffer").Buffer)
37261},{"buffer":49,"ed25519":20,"tweetnacl":435}],426:[function(require,module,exports){
37262(function (Buffer){
37263"use strict";
37264
37265var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
37266
37267var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
37268
37269var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
37270
37271exports.decodeCheck = decodeCheck;
37272exports.encodeCheck = encodeCheck;
37273Object.defineProperty(exports, "__esModule", {
37274 value: true
37275});
37276
37277var base32 = _interopRequire(require("base32.js"));
37278
37279var crc = _interopRequire(require("crc"));
37280
37281var isUndefined = _interopRequire(require("lodash/isUndefined"));
37282
37283var isNull = _interopRequire(require("lodash/isNull"));
37284
37285var isString = _interopRequire(require("lodash/isString"));
37286
37287var verifyChecksum = require("./util/checksum").verifyChecksum;
37288
37289var versionBytes = {
37290 ed25519PublicKey: 6 << 3, // G
37291 ed25519SecretSeed: 18 << 3, // S
37292 preAuthTx: 19 << 3, // T
37293 sha256Hash: 23 << 3 // X
37294};
37295
37296/**
37297 * StrKey is a helper class that allows encoding and decoding strkey.
37298 */
37299
37300var StrKey = exports.StrKey = (function () {
37301 function StrKey() {
37302 _classCallCheck(this, StrKey);
37303 }
37304
37305 _createClass(StrKey, null, {
37306 encodeEd25519PublicKey: {
37307 /**
37308 * Encodes data to strkey ed25519 public key.
37309 * @param {Buffer} data data to encode
37310 * @returns {string}
37311 */
37312
37313 value: function encodeEd25519PublicKey(data) {
37314 return encodeCheck("ed25519PublicKey", data);
37315 }
37316 },
37317 decodeEd25519PublicKey: {
37318
37319 /**
37320 * Decodes strkey ed25519 public key to raw data.
37321 * @param {string} data data to decode
37322 * @returns {Buffer}
37323 */
37324
37325 value: function decodeEd25519PublicKey(data) {
37326 return decodeCheck("ed25519PublicKey", data);
37327 }
37328 },
37329 isValidEd25519PublicKey: {
37330
37331 /**
37332 * Returns true if the given Stellar public key is a valid ed25519 public key.
37333 * @param {string} publicKey public key to check
37334 * @returns {boolean}
37335 */
37336
37337 value: function isValidEd25519PublicKey(publicKey) {
37338 return isValid("ed25519PublicKey", publicKey);
37339 }
37340 },
37341 encodeEd25519SecretSeed: {
37342
37343 /**
37344 * Encodes data to strkey ed25519 seed.
37345 * @param {Buffer} data data to encode
37346 * @returns {string}
37347 */
37348
37349 value: function encodeEd25519SecretSeed(data) {
37350 return encodeCheck("ed25519SecretSeed", data);
37351 }
37352 },
37353 decodeEd25519SecretSeed: {
37354
37355 /**
37356 * Decodes strkey ed25519 seed to raw data.
37357 * @param {string} data data to decode
37358 * @returns {Buffer}
37359 */
37360
37361 value: function decodeEd25519SecretSeed(data) {
37362 return decodeCheck("ed25519SecretSeed", data);
37363 }
37364 },
37365 isValidEd25519SecretSeed: {
37366
37367 /**
37368 * Returns true if the given Stellar secret key is a valid ed25519 secret seed.
37369 * @param {string} seed seed to check
37370 * @returns {boolean}
37371 */
37372
37373 value: function isValidEd25519SecretSeed(seed) {
37374 return isValid("ed25519SecretSeed", seed);
37375 }
37376 },
37377 encodePreAuthTx: {
37378
37379 /**
37380 * Encodes data to strkey preAuthTx.
37381 * @param {Buffer} data data to encode
37382 * @returns {string}
37383 */
37384
37385 value: function encodePreAuthTx(data) {
37386 return encodeCheck("preAuthTx", data);
37387 }
37388 },
37389 decodePreAuthTx: {
37390
37391 /**
37392 * Decodes strkey PreAuthTx to raw data.
37393 * @param {string} data data to decode
37394 * @returns {Buffer}
37395 */
37396
37397 value: function decodePreAuthTx(data) {
37398 return decodeCheck("preAuthTx", data);
37399 }
37400 },
37401 encodeSha256Hash: {
37402
37403 /**
37404 * Encodes data to strkey sha256 hash.
37405 * @param {Buffer} data data to encode
37406 * @returns {string}
37407 */
37408
37409 value: function encodeSha256Hash(data) {
37410 return encodeCheck("sha256Hash", data);
37411 }
37412 },
37413 decodeSha256Hash: {
37414
37415 /**
37416 * Decodes strkey sha256 hash to raw data.
37417 * @param {string} data data to decode
37418 * @returns {Buffer}
37419 */
37420
37421 value: function decodeSha256Hash(data) {
37422 return decodeCheck("sha256Hash", data);
37423 }
37424 }
37425 });
37426
37427 return StrKey;
37428})();
37429
37430function isValid(versionByteName, encoded) {
37431 if (encoded && encoded.length != 56) {
37432 return false;
37433 }
37434
37435 try {
37436 var decoded = decodeCheck(versionByteName, encoded);
37437 if (decoded.length !== 32) {
37438 return false;
37439 }
37440 } catch (err) {
37441 return false;
37442 }
37443 return true;
37444}
37445
37446function decodeCheck(versionByteName, encoded) {
37447 if (!isString(encoded)) {
37448 throw new TypeError("encoded argument must be of type String");
37449 }
37450
37451 var decoded = base32.decode(encoded);
37452 var versionByte = decoded[0];
37453 var payload = decoded.slice(0, -2);
37454 var data = payload.slice(1);
37455 var checksum = decoded.slice(-2);
37456
37457 if (encoded != base32.encode(decoded)) {
37458 throw new Error("invalid encoded string");
37459 }
37460
37461 var expectedVersion = versionBytes[versionByteName];
37462
37463 if (isUndefined(expectedVersion)) {
37464 throw new Error("" + versionByteName + " is not a valid version byte name. expected one of \"accountId\" or \"seed\"");
37465 }
37466
37467 if (versionByte !== expectedVersion) {
37468 throw new Error("invalid version byte. expected " + expectedVersion + ", got " + versionByte);
37469 }
37470
37471 var expectedChecksum = calculateChecksum(payload);
37472
37473 if (!verifyChecksum(expectedChecksum, checksum)) {
37474 throw new Error("invalid checksum");
37475 }
37476
37477 return Buffer.from(data);
37478}
37479
37480function encodeCheck(versionByteName, data) {
37481 if (isNull(data) || isUndefined(data)) {
37482 throw new Error("cannot encode null data");
37483 }
37484
37485 var versionByte = versionBytes[versionByteName];
37486
37487 if (isUndefined(versionByte)) {
37488 throw new Error("" + versionByteName + " is not a valid version byte name. expected one of \"ed25519PublicKey\", \"ed25519SecretSeed\", \"preAuthTx\", \"sha256Hash\"");
37489 }
37490
37491 data = Buffer.from(data);
37492 var versionBuffer = Buffer.from([versionByte]);
37493 var payload = Buffer.concat([versionBuffer, data]);
37494 var checksum = calculateChecksum(payload);
37495 var unencoded = Buffer.concat([payload, checksum]);
37496
37497 return base32.encode(unencoded);
37498}
37499
37500function calculateChecksum(payload) {
37501 // This code calculates CRC16-XModem checksum of payload
37502 // and returns it as Buffer in little-endian order.
37503 var checksum = Buffer.alloc(2);
37504 checksum.writeUInt16LE(crc.crc16xmodem(payload), 0);
37505 return checksum;
37506}
37507}).call(this,require("buffer").Buffer)
37508},{"./util/checksum":429,"base32.js":15,"buffer":49,"crc":65,"lodash/isNull":327,"lodash/isString":333,"lodash/isUndefined":336}],427:[function(require,module,exports){
37509(function (Buffer){
37510"use strict";
37511
37512var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
37513
37514var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
37515
37516var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
37517
37518Object.defineProperty(exports, "__esModule", {
37519 value: true
37520});
37521
37522var _index = require("./index");
37523
37524var xdr = _index.xdr;
37525var hash = _index.hash;
37526
37527var StrKey = require("./strkey").StrKey;
37528
37529var Operation = require("./operation").Operation;
37530
37531var Network = require("./network").Network;
37532
37533var Memo = require("./memo").Memo;
37534
37535var map = _interopRequire(require("lodash/map"));
37536
37537var each = _interopRequire(require("lodash/each"));
37538
37539var isString = _interopRequire(require("lodash/isString"));
37540
37541var crypto = _interopRequire(require("crypto"));
37542
37543/**
37544 * A new Transaction object is created from a transaction envelope or via {@link TransactionBuilder}.
37545 * Once a Transaction has been created from an envelope, its attributes and operations
37546 * should not be changed. You should only add signers (using {@link Transaction#sign}) to a Transaction object before
37547 * submitting to the network or forwarding on to additional signers.
37548 * @constructor
37549 * @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope object or base64 encoded string.
37550 */
37551
37552var Transaction = exports.Transaction = (function () {
37553 function Transaction(envelope) {
37554 _classCallCheck(this, Transaction);
37555
37556 if (typeof envelope === "string") {
37557 var buffer = Buffer.from(envelope, "base64");
37558 envelope = xdr.TransactionEnvelope.fromXDR(buffer);
37559 }
37560 // since this transaction is immutable, save the tx
37561 this.tx = envelope.tx();
37562 this.source = StrKey.encodeEd25519PublicKey(envelope.tx().sourceAccount().ed25519());
37563 this.fee = this.tx.fee();
37564 this._memo = this.tx.memo();
37565 this.sequence = this.tx.seqNum().toString();
37566
37567 var timeBounds = this.tx.timeBounds();
37568 if (timeBounds) {
37569 this.timeBounds = {
37570 minTime: timeBounds.minTime().toString(),
37571 maxTime: timeBounds.maxTime().toString()
37572 };
37573 }
37574
37575 var operations = this.tx.operations() || [];
37576 this.operations = map(operations, function (op) {
37577 return Operation.fromXDRObject(op);
37578 });
37579
37580 var signatures = envelope.signatures() || [];
37581 this.signatures = map(signatures, function (s) {
37582 return s;
37583 });
37584 }
37585
37586 _createClass(Transaction, {
37587 memo: {
37588 get: function () {
37589 return Memo.fromXDRObject(this._memo);
37590 },
37591 set: function (value) {
37592 throw new Error("Transaction is immutable");
37593 }
37594 },
37595 sign: {
37596
37597 /**
37598 * Signs the transaction with the given {@link Keypair}.
37599 * @param {...Keypair} keypairs Keypairs of signers
37600 * @returns {void}
37601 */
37602
37603 value: function sign() {
37604 var _this = this;
37605
37606 for (var _len = arguments.length, keypairs = Array(_len), _key = 0; _key < _len; _key++) {
37607 keypairs[_key] = arguments[_key];
37608 }
37609
37610 var txHash = this.hash();
37611 var newSigs = each(keypairs, function (kp) {
37612 var sig = kp.signDecorated(txHash);
37613 _this.signatures.push(sig);
37614 });
37615 }
37616 },
37617 signHashX: {
37618
37619 /**
37620 * Add `hashX` signer preimage as signature.
37621 * @param {Buffer|String} preimage Preimage of hash used as signer
37622 * @returns {void}
37623 */
37624
37625 value: function signHashX(preimage) {
37626 if (isString(preimage)) {
37627 preimage = Buffer.from(preimage, "hex");
37628 }
37629
37630 if (preimage.length > 64) {
37631 throw new Error("preimage cannnot be longer than 64 bytes");
37632 }
37633
37634 var signature = preimage;
37635 var hash = crypto.createHash("sha256").update(preimage).digest();
37636 var hint = hash.slice(hash.length - 4);
37637 this.signatures.push(new xdr.DecoratedSignature({ hint: hint, signature: signature }));
37638 }
37639 },
37640 hash: {
37641
37642 /**
37643 * Returns a hash for this transaction, suitable for signing.
37644 * @returns {Buffer}
37645 */
37646
37647 value: (function (_hash) {
37648 var _hashWrapper = function hash() {
37649 return _hash.apply(this, arguments);
37650 };
37651
37652 _hashWrapper.toString = function () {
37653 return _hash.toString();
37654 };
37655
37656 return _hashWrapper;
37657 })(function () {
37658 return hash(this.signatureBase());
37659 })
37660 },
37661 signatureBase: {
37662
37663 /**
37664 * Returns the "signature base" of this transaction, which is the value
37665 * that, when hashed, should be signed to create a signature that
37666 * validators on the Stellar Network will accept.
37667 *
37668 * It is composed of a 4 prefix bytes followed by the xdr-encoded form
37669 * of this transaction.
37670 * @returns {Buffer}
37671 */
37672
37673 value: function signatureBase() {
37674 if (Network.current() === null) {
37675 throw new Error("No network selected. Use `Network.use`, `Network.usePublicNetwork` or `Network.useTestNetwork` helper methods to select network.");
37676 }
37677
37678 return Buffer.concat([Network.current().networkId(), xdr.EnvelopeType.envelopeTypeTx().toXDR(), this.tx.toXDR()]);
37679 }
37680 },
37681 toEnvelope: {
37682
37683 /**
37684 * To envelope returns a xdr.TransactionEnvelope which can be submitted to the network.
37685 * @returns {xdr.TransactionEnvelope}
37686 */
37687
37688 value: function toEnvelope() {
37689 var tx = this.tx;
37690 var signatures = this.signatures;
37691 var envelope = new xdr.TransactionEnvelope({ tx: tx, signatures: signatures });
37692
37693 return envelope;
37694 }
37695 }
37696 });
37697
37698 return Transaction;
37699})();
37700}).call(this,require("buffer").Buffer)
37701},{"./index":407,"./memo":409,"./network":410,"./operation":411,"./strkey":426,"buffer":49,"crypto":71,"lodash/each":308,"lodash/isString":333,"lodash/map":339}],428:[function(require,module,exports){
37702"use strict";
37703
37704var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
37705
37706var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
37707
37708var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
37709
37710Object.defineProperty(exports, "__esModule", {
37711 value: true
37712});
37713
37714var xdr = _interopRequire(require("./generated/stellar-xdr_generated"));
37715
37716var UnsignedHyper = require("js-xdr").UnsignedHyper;
37717
37718var hash = require("./hashing").hash;
37719
37720var Keypair = require("./keypair").Keypair;
37721
37722var Account = require("./account").Account;
37723
37724var Operation = require("./operation").Operation;
37725
37726var Transaction = require("./transaction").Transaction;
37727
37728var Memo = require("./memo").Memo;
37729
37730var BigNumber = _interopRequire(require("bignumber.js"));
37731
37732var clone = _interopRequire(require("lodash/clone"));
37733
37734var map = _interopRequire(require("lodash/map"));
37735
37736var isUndefined = _interopRequire(require("lodash/isUndefined"));
37737
37738var BASE_FEE = 100; // Stroops
37739
37740/**
37741 * @constant
37742 * @see {@link TransactionBuilder#setTimeout}
37743 * @see [Timeout](https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html#timeout)
37744 */
37745var TimeoutInfinite = 0;
37746
37747exports.TimeoutInfinite = TimeoutInfinite;
37748/**
37749 * <p>Transaction builder helps constructs a new `{@link Transaction}` using the given {@link Account}
37750 * as the transaction's "source account". The transaction will use the current sequence
37751 * number of the given account as its sequence number and increment the given account's
37752 * sequence number by one. The given source account must include a private key for signing
37753 * the transaction or an error will be thrown.</p>
37754 *
37755 * <p>Operations can be added to the transaction via their corresponding builder methods, and
37756 * each returns the TransactionBuilder object so they can be chained together. After adding
37757 * the desired operations, call the `build()` method on the `TransactionBuilder` to return a fully
37758 * constructed `{@link Transaction}` that can be signed. The returned transaction will contain the
37759 * sequence number of the source account and include the signature from the source account.</p>
37760 *
37761 * <p>The following code example creates a new transaction with {@link Operation.createAccount} and
37762 * {@link Operation.payment} operations.
37763 * The Transaction's source account first funds `destinationA`, then sends
37764 * a payment to `destinationB`. The built transaction is then signed by `sourceKeypair`.</p>
37765 *
37766 * ```
37767 * var transaction = new TransactionBuilder(source)
37768 * .addOperation(Operation.createAccount({
37769 destination: destinationA,
37770 startingBalance: "20"
37771 }) // <- funds and creates destinationA
37772 .addOperation(Operation.payment({
37773 destination: destinationB,
37774 amount: "100"
37775 asset: Asset.native()
37776 }) // <- sends 100 XLM to destinationB
37777 * .setTimeout(30)
37778 * .build();
37779 *
37780 * transaction.sign(sourceKeypair);
37781 * ```
37782 * @constructor
37783 * @param {Account} sourceAccount - The source account for this transaction.
37784 * @param {object} [opts]
37785 * @param {number} [opts.fee] - The max fee willing to pay per operation in this transaction (**in stroops**).
37786 * @param {object} [opts.timebounds] - The timebounds for the validity of this transaction.
37787 * @param {number|string} [opts.timebounds.minTime] - 64 bit unix timestamp
37788 * @param {number|string} [opts.timebounds.maxTime] - 64 bit unix timestamp
37789 * @param {Memo} [opts.memo] - The memo for the transaction
37790 */
37791
37792var TransactionBuilder = exports.TransactionBuilder = (function () {
37793 function TransactionBuilder(sourceAccount) {
37794 var opts = arguments[1] === undefined ? {} : arguments[1];
37795
37796 _classCallCheck(this, TransactionBuilder);
37797
37798 if (!sourceAccount) {
37799 throw new Error("must specify source account for the transaction");
37800 }
37801 this.source = sourceAccount;
37802 this.operations = [];
37803 this.baseFee = isUndefined(opts.fee) ? BASE_FEE : opts.fee;
37804 this.timebounds = clone(opts.timebounds);
37805 this.memo = opts.memo || Memo.none();
37806 this.timeoutSet = false;
37807 }
37808
37809 _createClass(TransactionBuilder, {
37810 addOperation: {
37811
37812 /**
37813 * Adds an operation to the transaction.
37814 * @param {xdr.Operation} operation The xdr operation object, use {@link Operation} static methods.
37815 * @returns {TransactionBuilder}
37816 */
37817
37818 value: function addOperation(operation) {
37819 this.operations.push(operation);
37820 return this;
37821 }
37822 },
37823 addMemo: {
37824
37825 /**
37826 * Adds a memo to the transaction.
37827 * @param {Memo} memo {@link Memo} object
37828 * @returns {TransactionBuilder}
37829 */
37830
37831 value: function addMemo(memo) {
37832 this.memo = memo;
37833 return this;
37834 }
37835 },
37836 setTimeout: {
37837
37838 /**
37839 * Because of the distributed nature of the Stellar network it is possible that the status of your transaction
37840 * will be determined after a long time if the network is highly congested.
37841 * If you want to be sure to receive the status of the transaction within a given period you should set the
37842 * {@link TimeBounds} with <code>maxTime</code> on the transaction (this is what <code>setTimeout</code> does
37843 * internally; if there's <code>minTime</code> set but no <code>maxTime</code> it will be added).
37844 * Call to <code>TransactionBuilder.setTimeout</code> is required if Transaction does not have <code>max_time</code> set.
37845 * If you don't want to set timeout, use <code>{@link TimeoutInfinite}</code>. In general you should set
37846 * <code>{@link TimeoutInfinite}</code> only in smart contracts.
37847 *
37848 * Please note that Horizon may still return <code>504 Gateway Timeout</code> error, even for short timeouts.
37849 * In such case you need to resubmit the same transaction again without making any changes to receive a status.
37850 * This method is using the machine system time (UTC), make sure it is set correctly.
37851 * @param {timeout} Timeout in seconds.
37852 * @return {TransactionBuilder}
37853 * @see TimeoutInfinite
37854 */
37855
37856 value: function setTimeout(timeout) {
37857 if (this.timebounds != null && this.timebounds.maxTime > 0) {
37858 throw new Error("TimeBounds.max_time has been already set - setting timeout would overwrite it.");
37859 }
37860
37861 if (timeout < 0) {
37862 throw new Error("timeout cannot be negative");
37863 }
37864
37865 this.timeoutSet = true;
37866 if (timeout > 0) {
37867 var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeout;
37868 if (this.timebounds == null) {
37869 this.timebounds = { minTime: 0, maxTime: timeoutTimestamp };
37870 } else {
37871 this.timebounds = { minTime: this.timebounds.minTime, maxTime: timeoutTimestamp };
37872 }
37873 }
37874
37875 return this;
37876 }
37877 },
37878 build: {
37879
37880 /**
37881 * This will build the transaction.
37882 * It will also increment the source account's sequence number by 1.
37883 * @returns {Transaction} This method will return the built {@link Transaction}.
37884 */
37885
37886 value: function build() {
37887 // Ensure setTimeout called or maxTime is set
37888 if ((this.timebounds == null || this.timebounds != null && this.timebounds.maxTime == 0) && !this.timeoutSet) {
37889 throw new Error("TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).");
37890 }
37891
37892 var sequenceNumber = new BigNumber(this.source.sequenceNumber()).add(1);
37893
37894 var attrs = {
37895 sourceAccount: Keypair.fromPublicKey(this.source.accountId()).xdrAccountId(),
37896 fee: this.baseFee * this.operations.length,
37897 seqNum: xdr.SequenceNumber.fromString(sequenceNumber.toString()),
37898 memo: this.memo ? this.memo.toXDRObject() : null,
37899 ext: new xdr.TransactionExt(0)
37900 };
37901
37902 if (this.timebounds) {
37903 this.timebounds.minTime = UnsignedHyper.fromString(this.timebounds.minTime.toString());
37904 this.timebounds.maxTime = UnsignedHyper.fromString(this.timebounds.maxTime.toString());
37905 attrs.timeBounds = new xdr.TimeBounds(this.timebounds);
37906 }
37907
37908 var xtx = new xdr.Transaction(attrs);
37909 xtx.operations(this.operations);
37910
37911 var xenv = new xdr.TransactionEnvelope({ tx: xtx });
37912 var tx = new Transaction(xenv);
37913
37914 this.source.incrementSequenceNumber();
37915
37916 return tx;
37917 }
37918 }
37919 });
37920
37921 return TransactionBuilder;
37922})();
37923},{"./account":402,"./generated/stellar-xdr_generated":405,"./hashing":406,"./keypair":408,"./memo":409,"./operation":411,"./transaction":427,"bignumber.js":17,"js-xdr":127,"lodash/clone":306,"lodash/isUndefined":336,"lodash/map":339}],429:[function(require,module,exports){
37924"use strict";
37925
37926exports.verifyChecksum = verifyChecksum;
37927Object.defineProperty(exports, "__esModule", {
37928 value: true
37929});
37930
37931function verifyChecksum(expected, actual) {
37932 if (expected.length !== actual.length) {
37933 return false;
37934 }
37935
37936 if (expected.length === 0) {
37937 return true;
37938 }
37939
37940 for (var i = 0; i < expected.length; i++) {
37941 if (expected[i] !== actual[i]) {
37942 return false;
37943 }
37944 }
37945
37946 return true;
37947}
37948},{}],430:[function(require,module,exports){
37949"use strict";
37950
37951var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
37952
37953var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
37954
37955/**
37956 * Calculates and returns the best rational approximation of the given real number.
37957 * @private
37958 * @param {string|number|BigNumber} number
37959 * @throws Error Throws `Error` when the best rational approximation cannot be found.
37960 * @returns {array} first element is n (numerator), second element is d (denominator)
37961 */
37962exports.best_r = best_r;
37963Object.defineProperty(exports, "__esModule", {
37964 value: true
37965});
37966
37967var BigNumber = _interopRequire(require("bignumber.js"));
37968
37969var MAX_INT = (1 << 31 >>> 0) - 1;
37970function best_r(number) {
37971 number = new BigNumber(number);
37972 var a;
37973 var f;
37974 var fractions = [[new BigNumber(0), new BigNumber(1)], [new BigNumber(1), new BigNumber(0)]];
37975 var i = 2;
37976 while (true) {
37977 if (number.gt(MAX_INT)) {
37978 break;
37979 }
37980 a = number.floor();
37981 f = number.sub(a);
37982 var h = a.mul(fractions[i - 1][0]).add(fractions[i - 2][0]);
37983 var k = a.mul(fractions[i - 1][1]).add(fractions[i - 2][1]);
37984 if (h.gt(MAX_INT) || k.gt(MAX_INT)) {
37985 break;
37986 }
37987 fractions.push([h, k]);
37988 if (f.eq(0)) {
37989 break;
37990 }
37991 number = new BigNumber(1).div(f);
37992 i++;
37993 }
37994
37995 var _fractions = _slicedToArray(fractions[fractions.length - 1], 2);
37996
37997 var n = _fractions[0];
37998 var d = _fractions[1];
37999
38000 if (n.isZero() || d.isZero()) {
38001 throw new Error("Couldn't find approximation");
38002 }
38003
38004 return [n.toNumber(), d.toNumber()];
38005}
38006},{"bignumber.js":17}],431:[function(require,module,exports){
38007// vendored from http://cryptocoinjs.com/modules/misc/bs58/
38008
38009// Base58 encoding/decoding
38010// Originally written by Mike Hearn for BitcoinJ
38011// Copyright (c) 2011 Google Inc
38012// Ported to JavaScript by Stefan Thomas
38013// Merged Buffer refactorings from base58-native by Stephen Pair
38014// Copyright (c) 2013 BitPay Inc
38015
38016"use strict";
38017
38018var ALPHABET = "gsphnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCr65jkm8oFqi1tuvAxyz";
38019var ALPHABET_MAP = {};
38020for (var i = 0; i < ALPHABET.length; ++i) {
38021 ALPHABET_MAP[ALPHABET.charAt(i)] = i;
38022}
38023var BASE = 58;
38024
38025function decode(string) {
38026 if (string.length === 0) {
38027 return [];
38028 }var i,
38029 j,
38030 bytes = [0];
38031 for (i = 0; i < string.length; ++i) {
38032 var c = string[i];
38033 if (!(c in ALPHABET_MAP)) throw new Error("Non-base58 character");
38034
38035 for (j = 0; j < bytes.length; ++j) bytes[j] *= BASE;
38036 bytes[0] += ALPHABET_MAP[c];
38037
38038 var carry = 0;
38039 for (j = 0; j < bytes.length; ++j) {
38040 bytes[j] += carry;
38041
38042 carry = bytes[j] >> 8;
38043 bytes[j] &= 255;
38044 }
38045
38046 while (carry) {
38047 bytes.push(carry & 255);
38048
38049 carry >>= 8;
38050 }
38051 }
38052
38053 // deal with leading zeros
38054 for (i = 0; string[i] === "g" && i < string.length - 1; ++i) bytes.push(0);
38055
38056 return bytes.reverse();
38057}
38058
38059module.exports = { decode: decode };
38060},{}],432:[function(require,module,exports){
38061// Copyright Joyent, Inc. and other Node contributors.
38062//
38063// Permission is hereby granted, free of charge, to any person obtaining a
38064// copy of this software and associated documentation files (the
38065// "Software"), to deal in the Software without restriction, including
38066// without limitation the rights to use, copy, modify, merge, publish,
38067// distribute, sublicense, and/or sell copies of the Software, and to permit
38068// persons to whom the Software is furnished to do so, subject to the
38069// following conditions:
38070//
38071// The above copyright notice and this permission notice shall be included
38072// in all copies or substantial portions of the Software.
38073//
38074// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
38075// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
38076// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
38077// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
38078// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
38079// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
38080// USE OR OTHER DEALINGS IN THE SOFTWARE.
38081
38082module.exports = Stream;
38083
38084var EE = require('events').EventEmitter;
38085var inherits = require('inherits');
38086
38087inherits(Stream, EE);
38088Stream.Readable = require('readable-stream/readable.js');
38089Stream.Writable = require('readable-stream/writable.js');
38090Stream.Duplex = require('readable-stream/duplex.js');
38091Stream.Transform = require('readable-stream/transform.js');
38092Stream.PassThrough = require('readable-stream/passthrough.js');
38093
38094// Backwards-compat with node 0.4.x
38095Stream.Stream = Stream;
38096
38097
38098
38099// old-style streams. Note that the pipe method (the only relevant
38100// part of this class) is overridden in the Readable class.
38101
38102function Stream() {
38103 EE.call(this);
38104}
38105
38106Stream.prototype.pipe = function(dest, options) {
38107 var source = this;
38108
38109 function ondata(chunk) {
38110 if (dest.writable) {
38111 if (false === dest.write(chunk) && source.pause) {
38112 source.pause();
38113 }
38114 }
38115 }
38116
38117 source.on('data', ondata);
38118
38119 function ondrain() {
38120 if (source.readable && source.resume) {
38121 source.resume();
38122 }
38123 }
38124
38125 dest.on('drain', ondrain);
38126
38127 // If the 'end' option is not supplied, dest.end() will be called when
38128 // source gets the 'end' or 'close' events. Only dest.end() once.
38129 if (!dest._isStdio && (!options || options.end !== false)) {
38130 source.on('end', onend);
38131 source.on('close', onclose);
38132 }
38133
38134 var didOnEnd = false;
38135 function onend() {
38136 if (didOnEnd) return;
38137 didOnEnd = true;
38138
38139 dest.end();
38140 }
38141
38142
38143 function onclose() {
38144 if (didOnEnd) return;
38145 didOnEnd = true;
38146
38147 if (typeof dest.destroy === 'function') dest.destroy();
38148 }
38149
38150 // don't leave dangling pipes when there are errors.
38151 function onerror(er) {
38152 cleanup();
38153 if (EE.listenerCount(this, 'error') === 0) {
38154 throw er; // Unhandled stream error in pipe.
38155 }
38156 }
38157
38158 source.on('error', onerror);
38159 dest.on('error', onerror);
38160
38161 // remove all the event listeners that were added.
38162 function cleanup() {
38163 source.removeListener('data', ondata);
38164 dest.removeListener('drain', ondrain);
38165
38166 source.removeListener('end', onend);
38167 source.removeListener('close', onclose);
38168
38169 source.removeListener('error', onerror);
38170 dest.removeListener('error', onerror);
38171
38172 source.removeListener('end', cleanup);
38173 source.removeListener('close', cleanup);
38174
38175 dest.removeListener('close', cleanup);
38176 }
38177
38178 source.on('end', cleanup);
38179 source.on('close', cleanup);
38180
38181 dest.on('close', cleanup);
38182
38183 dest.emit('pipe', source);
38184
38185 // Allow for unix-like usage: A.pipe(B).pipe(C)
38186 return dest;
38187};
38188
38189},{"events":99,"inherits":116,"readable-stream/duplex.js":378,"readable-stream/passthrough.js":388,"readable-stream/readable.js":389,"readable-stream/transform.js":390,"readable-stream/writable.js":391}],433:[function(require,module,exports){
38190arguments[4][387][0].apply(exports,arguments)
38191},{"dup":387,"safe-buffer":393}],434:[function(require,module,exports){
38192(function (setImmediate,clearImmediate){
38193var nextTick = require('process/browser.js').nextTick;
38194var apply = Function.prototype.apply;
38195var slice = Array.prototype.slice;
38196var immediateIds = {};
38197var nextImmediateId = 0;
38198
38199// DOM APIs, for completeness
38200
38201exports.setTimeout = function() {
38202 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
38203};
38204exports.setInterval = function() {
38205 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
38206};
38207exports.clearTimeout =
38208exports.clearInterval = function(timeout) { timeout.close(); };
38209
38210function Timeout(id, clearFn) {
38211 this._id = id;
38212 this._clearFn = clearFn;
38213}
38214Timeout.prototype.unref = Timeout.prototype.ref = function() {};
38215Timeout.prototype.close = function() {
38216 this._clearFn.call(window, this._id);
38217};
38218
38219// Does not start the time, just sets up the members needed.
38220exports.enroll = function(item, msecs) {
38221 clearTimeout(item._idleTimeoutId);
38222 item._idleTimeout = msecs;
38223};
38224
38225exports.unenroll = function(item) {
38226 clearTimeout(item._idleTimeoutId);
38227 item._idleTimeout = -1;
38228};
38229
38230exports._unrefActive = exports.active = function(item) {
38231 clearTimeout(item._idleTimeoutId);
38232
38233 var msecs = item._idleTimeout;
38234 if (msecs >= 0) {
38235 item._idleTimeoutId = setTimeout(function onTimeout() {
38236 if (item._onTimeout)
38237 item._onTimeout();
38238 }, msecs);
38239 }
38240};
38241
38242// That's not how node.js implements it but the exposed api is the same.
38243exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
38244 var id = nextImmediateId++;
38245 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
38246
38247 immediateIds[id] = true;
38248
38249 nextTick(function onNextTick() {
38250 if (immediateIds[id]) {
38251 // fn.call() is faster so we optimize for the common use-case
38252 // @see http://jsperf.com/call-apply-segu
38253 if (args) {
38254 fn.apply(null, args);
38255 } else {
38256 fn.call(null);
38257 }
38258 // Prevent ids from leaking
38259 exports.clearImmediate(id);
38260 }
38261 });
38262
38263 return id;
38264};
38265
38266exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
38267 delete immediateIds[id];
38268};
38269}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
38270},{"process/browser.js":369,"timers":434}],435:[function(require,module,exports){
38271(function(nacl) {
38272'use strict';
38273
38274// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
38275// Public domain.
38276//
38277// Implementation derived from TweetNaCl version 20140427.
38278// See for details: http://tweetnacl.cr.yp.to/
38279
38280var gf = function(init) {
38281 var i, r = new Float64Array(16);
38282 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
38283 return r;
38284};
38285
38286// Pluggable, initialized in high-level API below.
38287var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
38288
38289var _0 = new Uint8Array(16);
38290var _9 = new Uint8Array(32); _9[0] = 9;
38291
38292var gf0 = gf(),
38293 gf1 = gf([1]),
38294 _121665 = gf([0xdb41, 1]),
38295 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
38296 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
38297 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
38298 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
38299 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
38300
38301function ts64(x, i, h, l) {
38302 x[i] = (h >> 24) & 0xff;
38303 x[i+1] = (h >> 16) & 0xff;
38304 x[i+2] = (h >> 8) & 0xff;
38305 x[i+3] = h & 0xff;
38306 x[i+4] = (l >> 24) & 0xff;
38307 x[i+5] = (l >> 16) & 0xff;
38308 x[i+6] = (l >> 8) & 0xff;
38309 x[i+7] = l & 0xff;
38310}
38311
38312function vn(x, xi, y, yi, n) {
38313 var i,d = 0;
38314 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
38315 return (1 & ((d - 1) >>> 8)) - 1;
38316}
38317
38318function crypto_verify_16(x, xi, y, yi) {
38319 return vn(x,xi,y,yi,16);
38320}
38321
38322function crypto_verify_32(x, xi, y, yi) {
38323 return vn(x,xi,y,yi,32);
38324}
38325
38326function core_salsa20(o, p, k, c) {
38327 var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
38328 j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
38329 j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
38330 j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
38331 j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
38332 j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
38333 j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
38334 j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
38335 j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
38336 j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
38337 j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
38338 j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
38339 j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
38340 j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
38341 j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
38342 j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
38343
38344 var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
38345 x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
38346 x15 = j15, u;
38347
38348 for (var i = 0; i < 20; i += 2) {
38349 u = x0 + x12 | 0;
38350 x4 ^= u<<7 | u>>>(32-7);
38351 u = x4 + x0 | 0;
38352 x8 ^= u<<9 | u>>>(32-9);
38353 u = x8 + x4 | 0;
38354 x12 ^= u<<13 | u>>>(32-13);
38355 u = x12 + x8 | 0;
38356 x0 ^= u<<18 | u>>>(32-18);
38357
38358 u = x5 + x1 | 0;
38359 x9 ^= u<<7 | u>>>(32-7);
38360 u = x9 + x5 | 0;
38361 x13 ^= u<<9 | u>>>(32-9);
38362 u = x13 + x9 | 0;
38363 x1 ^= u<<13 | u>>>(32-13);
38364 u = x1 + x13 | 0;
38365 x5 ^= u<<18 | u>>>(32-18);
38366
38367 u = x10 + x6 | 0;
38368 x14 ^= u<<7 | u>>>(32-7);
38369 u = x14 + x10 | 0;
38370 x2 ^= u<<9 | u>>>(32-9);
38371 u = x2 + x14 | 0;
38372 x6 ^= u<<13 | u>>>(32-13);
38373 u = x6 + x2 | 0;
38374 x10 ^= u<<18 | u>>>(32-18);
38375
38376 u = x15 + x11 | 0;
38377 x3 ^= u<<7 | u>>>(32-7);
38378 u = x3 + x15 | 0;
38379 x7 ^= u<<9 | u>>>(32-9);
38380 u = x7 + x3 | 0;
38381 x11 ^= u<<13 | u>>>(32-13);
38382 u = x11 + x7 | 0;
38383 x15 ^= u<<18 | u>>>(32-18);
38384
38385 u = x0 + x3 | 0;
38386 x1 ^= u<<7 | u>>>(32-7);
38387 u = x1 + x0 | 0;
38388 x2 ^= u<<9 | u>>>(32-9);
38389 u = x2 + x1 | 0;
38390 x3 ^= u<<13 | u>>>(32-13);
38391 u = x3 + x2 | 0;
38392 x0 ^= u<<18 | u>>>(32-18);
38393
38394 u = x5 + x4 | 0;
38395 x6 ^= u<<7 | u>>>(32-7);
38396 u = x6 + x5 | 0;
38397 x7 ^= u<<9 | u>>>(32-9);
38398 u = x7 + x6 | 0;
38399 x4 ^= u<<13 | u>>>(32-13);
38400 u = x4 + x7 | 0;
38401 x5 ^= u<<18 | u>>>(32-18);
38402
38403 u = x10 + x9 | 0;
38404 x11 ^= u<<7 | u>>>(32-7);
38405 u = x11 + x10 | 0;
38406 x8 ^= u<<9 | u>>>(32-9);
38407 u = x8 + x11 | 0;
38408 x9 ^= u<<13 | u>>>(32-13);
38409 u = x9 + x8 | 0;
38410 x10 ^= u<<18 | u>>>(32-18);
38411
38412 u = x15 + x14 | 0;
38413 x12 ^= u<<7 | u>>>(32-7);
38414 u = x12 + x15 | 0;
38415 x13 ^= u<<9 | u>>>(32-9);
38416 u = x13 + x12 | 0;
38417 x14 ^= u<<13 | u>>>(32-13);
38418 u = x14 + x13 | 0;
38419 x15 ^= u<<18 | u>>>(32-18);
38420 }
38421 x0 = x0 + j0 | 0;
38422 x1 = x1 + j1 | 0;
38423 x2 = x2 + j2 | 0;
38424 x3 = x3 + j3 | 0;
38425 x4 = x4 + j4 | 0;
38426 x5 = x5 + j5 | 0;
38427 x6 = x6 + j6 | 0;
38428 x7 = x7 + j7 | 0;
38429 x8 = x8 + j8 | 0;
38430 x9 = x9 + j9 | 0;
38431 x10 = x10 + j10 | 0;
38432 x11 = x11 + j11 | 0;
38433 x12 = x12 + j12 | 0;
38434 x13 = x13 + j13 | 0;
38435 x14 = x14 + j14 | 0;
38436 x15 = x15 + j15 | 0;
38437
38438 o[ 0] = x0 >>> 0 & 0xff;
38439 o[ 1] = x0 >>> 8 & 0xff;
38440 o[ 2] = x0 >>> 16 & 0xff;
38441 o[ 3] = x0 >>> 24 & 0xff;
38442
38443 o[ 4] = x1 >>> 0 & 0xff;
38444 o[ 5] = x1 >>> 8 & 0xff;
38445 o[ 6] = x1 >>> 16 & 0xff;
38446 o[ 7] = x1 >>> 24 & 0xff;
38447
38448 o[ 8] = x2 >>> 0 & 0xff;
38449 o[ 9] = x2 >>> 8 & 0xff;
38450 o[10] = x2 >>> 16 & 0xff;
38451 o[11] = x2 >>> 24 & 0xff;
38452
38453 o[12] = x3 >>> 0 & 0xff;
38454 o[13] = x3 >>> 8 & 0xff;
38455 o[14] = x3 >>> 16 & 0xff;
38456 o[15] = x3 >>> 24 & 0xff;
38457
38458 o[16] = x4 >>> 0 & 0xff;
38459 o[17] = x4 >>> 8 & 0xff;
38460 o[18] = x4 >>> 16 & 0xff;
38461 o[19] = x4 >>> 24 & 0xff;
38462
38463 o[20] = x5 >>> 0 & 0xff;
38464 o[21] = x5 >>> 8 & 0xff;
38465 o[22] = x5 >>> 16 & 0xff;
38466 o[23] = x5 >>> 24 & 0xff;
38467
38468 o[24] = x6 >>> 0 & 0xff;
38469 o[25] = x6 >>> 8 & 0xff;
38470 o[26] = x6 >>> 16 & 0xff;
38471 o[27] = x6 >>> 24 & 0xff;
38472
38473 o[28] = x7 >>> 0 & 0xff;
38474 o[29] = x7 >>> 8 & 0xff;
38475 o[30] = x7 >>> 16 & 0xff;
38476 o[31] = x7 >>> 24 & 0xff;
38477
38478 o[32] = x8 >>> 0 & 0xff;
38479 o[33] = x8 >>> 8 & 0xff;
38480 o[34] = x8 >>> 16 & 0xff;
38481 o[35] = x8 >>> 24 & 0xff;
38482
38483 o[36] = x9 >>> 0 & 0xff;
38484 o[37] = x9 >>> 8 & 0xff;
38485 o[38] = x9 >>> 16 & 0xff;
38486 o[39] = x9 >>> 24 & 0xff;
38487
38488 o[40] = x10 >>> 0 & 0xff;
38489 o[41] = x10 >>> 8 & 0xff;
38490 o[42] = x10 >>> 16 & 0xff;
38491 o[43] = x10 >>> 24 & 0xff;
38492
38493 o[44] = x11 >>> 0 & 0xff;
38494 o[45] = x11 >>> 8 & 0xff;
38495 o[46] = x11 >>> 16 & 0xff;
38496 o[47] = x11 >>> 24 & 0xff;
38497
38498 o[48] = x12 >>> 0 & 0xff;
38499 o[49] = x12 >>> 8 & 0xff;
38500 o[50] = x12 >>> 16 & 0xff;
38501 o[51] = x12 >>> 24 & 0xff;
38502
38503 o[52] = x13 >>> 0 & 0xff;
38504 o[53] = x13 >>> 8 & 0xff;
38505 o[54] = x13 >>> 16 & 0xff;
38506 o[55] = x13 >>> 24 & 0xff;
38507
38508 o[56] = x14 >>> 0 & 0xff;
38509 o[57] = x14 >>> 8 & 0xff;
38510 o[58] = x14 >>> 16 & 0xff;
38511 o[59] = x14 >>> 24 & 0xff;
38512
38513 o[60] = x15 >>> 0 & 0xff;
38514 o[61] = x15 >>> 8 & 0xff;
38515 o[62] = x15 >>> 16 & 0xff;
38516 o[63] = x15 >>> 24 & 0xff;
38517}
38518
38519function core_hsalsa20(o,p,k,c) {
38520 var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
38521 j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
38522 j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
38523 j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
38524 j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
38525 j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
38526 j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
38527 j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
38528 j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
38529 j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
38530 j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
38531 j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
38532 j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
38533 j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
38534 j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
38535 j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
38536
38537 var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
38538 x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
38539 x15 = j15, u;
38540
38541 for (var i = 0; i < 20; i += 2) {
38542 u = x0 + x12 | 0;
38543 x4 ^= u<<7 | u>>>(32-7);
38544 u = x4 + x0 | 0;
38545 x8 ^= u<<9 | u>>>(32-9);
38546 u = x8 + x4 | 0;
38547 x12 ^= u<<13 | u>>>(32-13);
38548 u = x12 + x8 | 0;
38549 x0 ^= u<<18 | u>>>(32-18);
38550
38551 u = x5 + x1 | 0;
38552 x9 ^= u<<7 | u>>>(32-7);
38553 u = x9 + x5 | 0;
38554 x13 ^= u<<9 | u>>>(32-9);
38555 u = x13 + x9 | 0;
38556 x1 ^= u<<13 | u>>>(32-13);
38557 u = x1 + x13 | 0;
38558 x5 ^= u<<18 | u>>>(32-18);
38559
38560 u = x10 + x6 | 0;
38561 x14 ^= u<<7 | u>>>(32-7);
38562 u = x14 + x10 | 0;
38563 x2 ^= u<<9 | u>>>(32-9);
38564 u = x2 + x14 | 0;
38565 x6 ^= u<<13 | u>>>(32-13);
38566 u = x6 + x2 | 0;
38567 x10 ^= u<<18 | u>>>(32-18);
38568
38569 u = x15 + x11 | 0;
38570 x3 ^= u<<7 | u>>>(32-7);
38571 u = x3 + x15 | 0;
38572 x7 ^= u<<9 | u>>>(32-9);
38573 u = x7 + x3 | 0;
38574 x11 ^= u<<13 | u>>>(32-13);
38575 u = x11 + x7 | 0;
38576 x15 ^= u<<18 | u>>>(32-18);
38577
38578 u = x0 + x3 | 0;
38579 x1 ^= u<<7 | u>>>(32-7);
38580 u = x1 + x0 | 0;
38581 x2 ^= u<<9 | u>>>(32-9);
38582 u = x2 + x1 | 0;
38583 x3 ^= u<<13 | u>>>(32-13);
38584 u = x3 + x2 | 0;
38585 x0 ^= u<<18 | u>>>(32-18);
38586
38587 u = x5 + x4 | 0;
38588 x6 ^= u<<7 | u>>>(32-7);
38589 u = x6 + x5 | 0;
38590 x7 ^= u<<9 | u>>>(32-9);
38591 u = x7 + x6 | 0;
38592 x4 ^= u<<13 | u>>>(32-13);
38593 u = x4 + x7 | 0;
38594 x5 ^= u<<18 | u>>>(32-18);
38595
38596 u = x10 + x9 | 0;
38597 x11 ^= u<<7 | u>>>(32-7);
38598 u = x11 + x10 | 0;
38599 x8 ^= u<<9 | u>>>(32-9);
38600 u = x8 + x11 | 0;
38601 x9 ^= u<<13 | u>>>(32-13);
38602 u = x9 + x8 | 0;
38603 x10 ^= u<<18 | u>>>(32-18);
38604
38605 u = x15 + x14 | 0;
38606 x12 ^= u<<7 | u>>>(32-7);
38607 u = x12 + x15 | 0;
38608 x13 ^= u<<9 | u>>>(32-9);
38609 u = x13 + x12 | 0;
38610 x14 ^= u<<13 | u>>>(32-13);
38611 u = x14 + x13 | 0;
38612 x15 ^= u<<18 | u>>>(32-18);
38613 }
38614
38615 o[ 0] = x0 >>> 0 & 0xff;
38616 o[ 1] = x0 >>> 8 & 0xff;
38617 o[ 2] = x0 >>> 16 & 0xff;
38618 o[ 3] = x0 >>> 24 & 0xff;
38619
38620 o[ 4] = x5 >>> 0 & 0xff;
38621 o[ 5] = x5 >>> 8 & 0xff;
38622 o[ 6] = x5 >>> 16 & 0xff;
38623 o[ 7] = x5 >>> 24 & 0xff;
38624
38625 o[ 8] = x10 >>> 0 & 0xff;
38626 o[ 9] = x10 >>> 8 & 0xff;
38627 o[10] = x10 >>> 16 & 0xff;
38628 o[11] = x10 >>> 24 & 0xff;
38629
38630 o[12] = x15 >>> 0 & 0xff;
38631 o[13] = x15 >>> 8 & 0xff;
38632 o[14] = x15 >>> 16 & 0xff;
38633 o[15] = x15 >>> 24 & 0xff;
38634
38635 o[16] = x6 >>> 0 & 0xff;
38636 o[17] = x6 >>> 8 & 0xff;
38637 o[18] = x6 >>> 16 & 0xff;
38638 o[19] = x6 >>> 24 & 0xff;
38639
38640 o[20] = x7 >>> 0 & 0xff;
38641 o[21] = x7 >>> 8 & 0xff;
38642 o[22] = x7 >>> 16 & 0xff;
38643 o[23] = x7 >>> 24 & 0xff;
38644
38645 o[24] = x8 >>> 0 & 0xff;
38646 o[25] = x8 >>> 8 & 0xff;
38647 o[26] = x8 >>> 16 & 0xff;
38648 o[27] = x8 >>> 24 & 0xff;
38649
38650 o[28] = x9 >>> 0 & 0xff;
38651 o[29] = x9 >>> 8 & 0xff;
38652 o[30] = x9 >>> 16 & 0xff;
38653 o[31] = x9 >>> 24 & 0xff;
38654}
38655
38656function crypto_core_salsa20(out,inp,k,c) {
38657 core_salsa20(out,inp,k,c);
38658}
38659
38660function crypto_core_hsalsa20(out,inp,k,c) {
38661 core_hsalsa20(out,inp,k,c);
38662}
38663
38664var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
38665 // "expand 32-byte k"
38666
38667function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
38668 var z = new Uint8Array(16), x = new Uint8Array(64);
38669 var u, i;
38670 for (i = 0; i < 16; i++) z[i] = 0;
38671 for (i = 0; i < 8; i++) z[i] = n[i];
38672 while (b >= 64) {
38673 crypto_core_salsa20(x,z,k,sigma);
38674 for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
38675 u = 1;
38676 for (i = 8; i < 16; i++) {
38677 u = u + (z[i] & 0xff) | 0;
38678 z[i] = u & 0xff;
38679 u >>>= 8;
38680 }
38681 b -= 64;
38682 cpos += 64;
38683 mpos += 64;
38684 }
38685 if (b > 0) {
38686 crypto_core_salsa20(x,z,k,sigma);
38687 for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
38688 }
38689 return 0;
38690}
38691
38692function crypto_stream_salsa20(c,cpos,b,n,k) {
38693 var z = new Uint8Array(16), x = new Uint8Array(64);
38694 var u, i;
38695 for (i = 0; i < 16; i++) z[i] = 0;
38696 for (i = 0; i < 8; i++) z[i] = n[i];
38697 while (b >= 64) {
38698 crypto_core_salsa20(x,z,k,sigma);
38699 for (i = 0; i < 64; i++) c[cpos+i] = x[i];
38700 u = 1;
38701 for (i = 8; i < 16; i++) {
38702 u = u + (z[i] & 0xff) | 0;
38703 z[i] = u & 0xff;
38704 u >>>= 8;
38705 }
38706 b -= 64;
38707 cpos += 64;
38708 }
38709 if (b > 0) {
38710 crypto_core_salsa20(x,z,k,sigma);
38711 for (i = 0; i < b; i++) c[cpos+i] = x[i];
38712 }
38713 return 0;
38714}
38715
38716function crypto_stream(c,cpos,d,n,k) {
38717 var s = new Uint8Array(32);
38718 crypto_core_hsalsa20(s,n,k,sigma);
38719 var sn = new Uint8Array(8);
38720 for (var i = 0; i < 8; i++) sn[i] = n[i+16];
38721 return crypto_stream_salsa20(c,cpos,d,sn,s);
38722}
38723
38724function crypto_stream_xor(c,cpos,m,mpos,d,n,k) {
38725 var s = new Uint8Array(32);
38726 crypto_core_hsalsa20(s,n,k,sigma);
38727 var sn = new Uint8Array(8);
38728 for (var i = 0; i < 8; i++) sn[i] = n[i+16];
38729 return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
38730}
38731
38732/*
38733* Port of Andrew Moon's Poly1305-donna-16. Public domain.
38734* https://github.com/floodyberry/poly1305-donna
38735*/
38736
38737var poly1305 = function(key) {
38738 this.buffer = new Uint8Array(16);
38739 this.r = new Uint16Array(10);
38740 this.h = new Uint16Array(10);
38741 this.pad = new Uint16Array(8);
38742 this.leftover = 0;
38743 this.fin = 0;
38744
38745 var t0, t1, t2, t3, t4, t5, t6, t7;
38746
38747 t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
38748 t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
38749 t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
38750 t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
38751 t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
38752 this.r[5] = ((t4 >>> 1)) & 0x1ffe;
38753 t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
38754 t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
38755 t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
38756 this.r[9] = ((t7 >>> 5)) & 0x007f;
38757
38758 this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
38759 this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
38760 this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
38761 this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
38762 this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
38763 this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
38764 this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
38765 this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
38766};
38767
38768poly1305.prototype.blocks = function(m, mpos, bytes) {
38769 var hibit = this.fin ? 0 : (1 << 11);
38770 var t0, t1, t2, t3, t4, t5, t6, t7, c;
38771 var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
38772
38773 var h0 = this.h[0],
38774 h1 = this.h[1],
38775 h2 = this.h[2],
38776 h3 = this.h[3],
38777 h4 = this.h[4],
38778 h5 = this.h[5],
38779 h6 = this.h[6],
38780 h7 = this.h[7],
38781 h8 = this.h[8],
38782 h9 = this.h[9];
38783
38784 var r0 = this.r[0],
38785 r1 = this.r[1],
38786 r2 = this.r[2],
38787 r3 = this.r[3],
38788 r4 = this.r[4],
38789 r5 = this.r[5],
38790 r6 = this.r[6],
38791 r7 = this.r[7],
38792 r8 = this.r[8],
38793 r9 = this.r[9];
38794
38795 while (bytes >= 16) {
38796 t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
38797 t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
38798 t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
38799 t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
38800 t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
38801 h5 += ((t4 >>> 1)) & 0x1fff;
38802 t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
38803 t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
38804 t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
38805 h9 += ((t7 >>> 5)) | hibit;
38806
38807 c = 0;
38808
38809 d0 = c;
38810 d0 += h0 * r0;
38811 d0 += h1 * (5 * r9);
38812 d0 += h2 * (5 * r8);
38813 d0 += h3 * (5 * r7);
38814 d0 += h4 * (5 * r6);
38815 c = (d0 >>> 13); d0 &= 0x1fff;
38816 d0 += h5 * (5 * r5);
38817 d0 += h6 * (5 * r4);
38818 d0 += h7 * (5 * r3);
38819 d0 += h8 * (5 * r2);
38820 d0 += h9 * (5 * r1);
38821 c += (d0 >>> 13); d0 &= 0x1fff;
38822
38823 d1 = c;
38824 d1 += h0 * r1;
38825 d1 += h1 * r0;
38826 d1 += h2 * (5 * r9);
38827 d1 += h3 * (5 * r8);
38828 d1 += h4 * (5 * r7);
38829 c = (d1 >>> 13); d1 &= 0x1fff;
38830 d1 += h5 * (5 * r6);
38831 d1 += h6 * (5 * r5);
38832 d1 += h7 * (5 * r4);
38833 d1 += h8 * (5 * r3);
38834 d1 += h9 * (5 * r2);
38835 c += (d1 >>> 13); d1 &= 0x1fff;
38836
38837 d2 = c;
38838 d2 += h0 * r2;
38839 d2 += h1 * r1;
38840 d2 += h2 * r0;
38841 d2 += h3 * (5 * r9);
38842 d2 += h4 * (5 * r8);
38843 c = (d2 >>> 13); d2 &= 0x1fff;
38844 d2 += h5 * (5 * r7);
38845 d2 += h6 * (5 * r6);
38846 d2 += h7 * (5 * r5);
38847 d2 += h8 * (5 * r4);
38848 d2 += h9 * (5 * r3);
38849 c += (d2 >>> 13); d2 &= 0x1fff;
38850
38851 d3 = c;
38852 d3 += h0 * r3;
38853 d3 += h1 * r2;
38854 d3 += h2 * r1;
38855 d3 += h3 * r0;
38856 d3 += h4 * (5 * r9);
38857 c = (d3 >>> 13); d3 &= 0x1fff;
38858 d3 += h5 * (5 * r8);
38859 d3 += h6 * (5 * r7);
38860 d3 += h7 * (5 * r6);
38861 d3 += h8 * (5 * r5);
38862 d3 += h9 * (5 * r4);
38863 c += (d3 >>> 13); d3 &= 0x1fff;
38864
38865 d4 = c;
38866 d4 += h0 * r4;
38867 d4 += h1 * r3;
38868 d4 += h2 * r2;
38869 d4 += h3 * r1;
38870 d4 += h4 * r0;
38871 c = (d4 >>> 13); d4 &= 0x1fff;
38872 d4 += h5 * (5 * r9);
38873 d4 += h6 * (5 * r8);
38874 d4 += h7 * (5 * r7);
38875 d4 += h8 * (5 * r6);
38876 d4 += h9 * (5 * r5);
38877 c += (d4 >>> 13); d4 &= 0x1fff;
38878
38879 d5 = c;
38880 d5 += h0 * r5;
38881 d5 += h1 * r4;
38882 d5 += h2 * r3;
38883 d5 += h3 * r2;
38884 d5 += h4 * r1;
38885 c = (d5 >>> 13); d5 &= 0x1fff;
38886 d5 += h5 * r0;
38887 d5 += h6 * (5 * r9);
38888 d5 += h7 * (5 * r8);
38889 d5 += h8 * (5 * r7);
38890 d5 += h9 * (5 * r6);
38891 c += (d5 >>> 13); d5 &= 0x1fff;
38892
38893 d6 = c;
38894 d6 += h0 * r6;
38895 d6 += h1 * r5;
38896 d6 += h2 * r4;
38897 d6 += h3 * r3;
38898 d6 += h4 * r2;
38899 c = (d6 >>> 13); d6 &= 0x1fff;
38900 d6 += h5 * r1;
38901 d6 += h6 * r0;
38902 d6 += h7 * (5 * r9);
38903 d6 += h8 * (5 * r8);
38904 d6 += h9 * (5 * r7);
38905 c += (d6 >>> 13); d6 &= 0x1fff;
38906
38907 d7 = c;
38908 d7 += h0 * r7;
38909 d7 += h1 * r6;
38910 d7 += h2 * r5;
38911 d7 += h3 * r4;
38912 d7 += h4 * r3;
38913 c = (d7 >>> 13); d7 &= 0x1fff;
38914 d7 += h5 * r2;
38915 d7 += h6 * r1;
38916 d7 += h7 * r0;
38917 d7 += h8 * (5 * r9);
38918 d7 += h9 * (5 * r8);
38919 c += (d7 >>> 13); d7 &= 0x1fff;
38920
38921 d8 = c;
38922 d8 += h0 * r8;
38923 d8 += h1 * r7;
38924 d8 += h2 * r6;
38925 d8 += h3 * r5;
38926 d8 += h4 * r4;
38927 c = (d8 >>> 13); d8 &= 0x1fff;
38928 d8 += h5 * r3;
38929 d8 += h6 * r2;
38930 d8 += h7 * r1;
38931 d8 += h8 * r0;
38932 d8 += h9 * (5 * r9);
38933 c += (d8 >>> 13); d8 &= 0x1fff;
38934
38935 d9 = c;
38936 d9 += h0 * r9;
38937 d9 += h1 * r8;
38938 d9 += h2 * r7;
38939 d9 += h3 * r6;
38940 d9 += h4 * r5;
38941 c = (d9 >>> 13); d9 &= 0x1fff;
38942 d9 += h5 * r4;
38943 d9 += h6 * r3;
38944 d9 += h7 * r2;
38945 d9 += h8 * r1;
38946 d9 += h9 * r0;
38947 c += (d9 >>> 13); d9 &= 0x1fff;
38948
38949 c = (((c << 2) + c)) | 0;
38950 c = (c + d0) | 0;
38951 d0 = c & 0x1fff;
38952 c = (c >>> 13);
38953 d1 += c;
38954
38955 h0 = d0;
38956 h1 = d1;
38957 h2 = d2;
38958 h3 = d3;
38959 h4 = d4;
38960 h5 = d5;
38961 h6 = d6;
38962 h7 = d7;
38963 h8 = d8;
38964 h9 = d9;
38965
38966 mpos += 16;
38967 bytes -= 16;
38968 }
38969 this.h[0] = h0;
38970 this.h[1] = h1;
38971 this.h[2] = h2;
38972 this.h[3] = h3;
38973 this.h[4] = h4;
38974 this.h[5] = h5;
38975 this.h[6] = h6;
38976 this.h[7] = h7;
38977 this.h[8] = h8;
38978 this.h[9] = h9;
38979};
38980
38981poly1305.prototype.finish = function(mac, macpos) {
38982 var g = new Uint16Array(10);
38983 var c, mask, f, i;
38984
38985 if (this.leftover) {
38986 i = this.leftover;
38987 this.buffer[i++] = 1;
38988 for (; i < 16; i++) this.buffer[i] = 0;
38989 this.fin = 1;
38990 this.blocks(this.buffer, 0, 16);
38991 }
38992
38993 c = this.h[1] >>> 13;
38994 this.h[1] &= 0x1fff;
38995 for (i = 2; i < 10; i++) {
38996 this.h[i] += c;
38997 c = this.h[i] >>> 13;
38998 this.h[i] &= 0x1fff;
38999 }
39000 this.h[0] += (c * 5);
39001 c = this.h[0] >>> 13;
39002 this.h[0] &= 0x1fff;
39003 this.h[1] += c;
39004 c = this.h[1] >>> 13;
39005 this.h[1] &= 0x1fff;
39006 this.h[2] += c;
39007
39008 g[0] = this.h[0] + 5;
39009 c = g[0] >>> 13;
39010 g[0] &= 0x1fff;
39011 for (i = 1; i < 10; i++) {
39012 g[i] = this.h[i] + c;
39013 c = g[i] >>> 13;
39014 g[i] &= 0x1fff;
39015 }
39016 g[9] -= (1 << 13);
39017
39018 mask = (c ^ 1) - 1;
39019 for (i = 0; i < 10; i++) g[i] &= mask;
39020 mask = ~mask;
39021 for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
39022
39023 this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
39024 this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
39025 this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
39026 this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
39027 this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
39028 this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
39029 this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
39030 this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
39031
39032 f = this.h[0] + this.pad[0];
39033 this.h[0] = f & 0xffff;
39034 for (i = 1; i < 8; i++) {
39035 f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
39036 this.h[i] = f & 0xffff;
39037 }
39038
39039 mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;
39040 mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;
39041 mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;
39042 mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;
39043 mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;
39044 mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;
39045 mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;
39046 mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;
39047 mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;
39048 mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;
39049 mac[macpos+10] = (this.h[5] >>> 0) & 0xff;
39050 mac[macpos+11] = (this.h[5] >>> 8) & 0xff;
39051 mac[macpos+12] = (this.h[6] >>> 0) & 0xff;
39052 mac[macpos+13] = (this.h[6] >>> 8) & 0xff;
39053 mac[macpos+14] = (this.h[7] >>> 0) & 0xff;
39054 mac[macpos+15] = (this.h[7] >>> 8) & 0xff;
39055};
39056
39057poly1305.prototype.update = function(m, mpos, bytes) {
39058 var i, want;
39059
39060 if (this.leftover) {
39061 want = (16 - this.leftover);
39062 if (want > bytes)
39063 want = bytes;
39064 for (i = 0; i < want; i++)
39065 this.buffer[this.leftover + i] = m[mpos+i];
39066 bytes -= want;
39067 mpos += want;
39068 this.leftover += want;
39069 if (this.leftover < 16)
39070 return;
39071 this.blocks(this.buffer, 0, 16);
39072 this.leftover = 0;
39073 }
39074
39075 if (bytes >= 16) {
39076 want = bytes - (bytes % 16);
39077 this.blocks(m, mpos, want);
39078 mpos += want;
39079 bytes -= want;
39080 }
39081
39082 if (bytes) {
39083 for (i = 0; i < bytes; i++)
39084 this.buffer[this.leftover + i] = m[mpos+i];
39085 this.leftover += bytes;
39086 }
39087};
39088
39089function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
39090 var s = new poly1305(k);
39091 s.update(m, mpos, n);
39092 s.finish(out, outpos);
39093 return 0;
39094}
39095
39096function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
39097 var x = new Uint8Array(16);
39098 crypto_onetimeauth(x,0,m,mpos,n,k);
39099 return crypto_verify_16(h,hpos,x,0);
39100}
39101
39102function crypto_secretbox(c,m,d,n,k) {
39103 var i;
39104 if (d < 32) return -1;
39105 crypto_stream_xor(c,0,m,0,d,n,k);
39106 crypto_onetimeauth(c, 16, c, 32, d - 32, c);
39107 for (i = 0; i < 16; i++) c[i] = 0;
39108 return 0;
39109}
39110
39111function crypto_secretbox_open(m,c,d,n,k) {
39112 var i;
39113 var x = new Uint8Array(32);
39114 if (d < 32) return -1;
39115 crypto_stream(x,0,32,n,k);
39116 if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;
39117 crypto_stream_xor(m,0,c,0,d,n,k);
39118 for (i = 0; i < 32; i++) m[i] = 0;
39119 return 0;
39120}
39121
39122function set25519(r, a) {
39123 var i;
39124 for (i = 0; i < 16; i++) r[i] = a[i]|0;
39125}
39126
39127function car25519(o) {
39128 var i, v, c = 1;
39129 for (i = 0; i < 16; i++) {
39130 v = o[i] + c + 65535;
39131 c = Math.floor(v / 65536);
39132 o[i] = v - c * 65536;
39133 }
39134 o[0] += c-1 + 37 * (c-1);
39135}
39136
39137function sel25519(p, q, b) {
39138 var t, c = ~(b-1);
39139 for (var i = 0; i < 16; i++) {
39140 t = c & (p[i] ^ q[i]);
39141 p[i] ^= t;
39142 q[i] ^= t;
39143 }
39144}
39145
39146function pack25519(o, n) {
39147 var i, j, b;
39148 var m = gf(), t = gf();
39149 for (i = 0; i < 16; i++) t[i] = n[i];
39150 car25519(t);
39151 car25519(t);
39152 car25519(t);
39153 for (j = 0; j < 2; j++) {
39154 m[0] = t[0] - 0xffed;
39155 for (i = 1; i < 15; i++) {
39156 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
39157 m[i-1] &= 0xffff;
39158 }
39159 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
39160 b = (m[15]>>16) & 1;
39161 m[14] &= 0xffff;
39162 sel25519(t, m, 1-b);
39163 }
39164 for (i = 0; i < 16; i++) {
39165 o[2*i] = t[i] & 0xff;
39166 o[2*i+1] = t[i]>>8;
39167 }
39168}
39169
39170function neq25519(a, b) {
39171 var c = new Uint8Array(32), d = new Uint8Array(32);
39172 pack25519(c, a);
39173 pack25519(d, b);
39174 return crypto_verify_32(c, 0, d, 0);
39175}
39176
39177function par25519(a) {
39178 var d = new Uint8Array(32);
39179 pack25519(d, a);
39180 return d[0] & 1;
39181}
39182
39183function unpack25519(o, n) {
39184 var i;
39185 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
39186 o[15] &= 0x7fff;
39187}
39188
39189function A(o, a, b) {
39190 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
39191}
39192
39193function Z(o, a, b) {
39194 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
39195}
39196
39197function M(o, a, b) {
39198 var v, c,
39199 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
39200 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
39201 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
39202 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
39203 b0 = b[0],
39204 b1 = b[1],
39205 b2 = b[2],
39206 b3 = b[3],
39207 b4 = b[4],
39208 b5 = b[5],
39209 b6 = b[6],
39210 b7 = b[7],
39211 b8 = b[8],
39212 b9 = b[9],
39213 b10 = b[10],
39214 b11 = b[11],
39215 b12 = b[12],
39216 b13 = b[13],
39217 b14 = b[14],
39218 b15 = b[15];
39219
39220 v = a[0];
39221 t0 += v * b0;
39222 t1 += v * b1;
39223 t2 += v * b2;
39224 t3 += v * b3;
39225 t4 += v * b4;
39226 t5 += v * b5;
39227 t6 += v * b6;
39228 t7 += v * b7;
39229 t8 += v * b8;
39230 t9 += v * b9;
39231 t10 += v * b10;
39232 t11 += v * b11;
39233 t12 += v * b12;
39234 t13 += v * b13;
39235 t14 += v * b14;
39236 t15 += v * b15;
39237 v = a[1];
39238 t1 += v * b0;
39239 t2 += v * b1;
39240 t3 += v * b2;
39241 t4 += v * b3;
39242 t5 += v * b4;
39243 t6 += v * b5;
39244 t7 += v * b6;
39245 t8 += v * b7;
39246 t9 += v * b8;
39247 t10 += v * b9;
39248 t11 += v * b10;
39249 t12 += v * b11;
39250 t13 += v * b12;
39251 t14 += v * b13;
39252 t15 += v * b14;
39253 t16 += v * b15;
39254 v = a[2];
39255 t2 += v * b0;
39256 t3 += v * b1;
39257 t4 += v * b2;
39258 t5 += v * b3;
39259 t6 += v * b4;
39260 t7 += v * b5;
39261 t8 += v * b6;
39262 t9 += v * b7;
39263 t10 += v * b8;
39264 t11 += v * b9;
39265 t12 += v * b10;
39266 t13 += v * b11;
39267 t14 += v * b12;
39268 t15 += v * b13;
39269 t16 += v * b14;
39270 t17 += v * b15;
39271 v = a[3];
39272 t3 += v * b0;
39273 t4 += v * b1;
39274 t5 += v * b2;
39275 t6 += v * b3;
39276 t7 += v * b4;
39277 t8 += v * b5;
39278 t9 += v * b6;
39279 t10 += v * b7;
39280 t11 += v * b8;
39281 t12 += v * b9;
39282 t13 += v * b10;
39283 t14 += v * b11;
39284 t15 += v * b12;
39285 t16 += v * b13;
39286 t17 += v * b14;
39287 t18 += v * b15;
39288 v = a[4];
39289 t4 += v * b0;
39290 t5 += v * b1;
39291 t6 += v * b2;
39292 t7 += v * b3;
39293 t8 += v * b4;
39294 t9 += v * b5;
39295 t10 += v * b6;
39296 t11 += v * b7;
39297 t12 += v * b8;
39298 t13 += v * b9;
39299 t14 += v * b10;
39300 t15 += v * b11;
39301 t16 += v * b12;
39302 t17 += v * b13;
39303 t18 += v * b14;
39304 t19 += v * b15;
39305 v = a[5];
39306 t5 += v * b0;
39307 t6 += v * b1;
39308 t7 += v * b2;
39309 t8 += v * b3;
39310 t9 += v * b4;
39311 t10 += v * b5;
39312 t11 += v * b6;
39313 t12 += v * b7;
39314 t13 += v * b8;
39315 t14 += v * b9;
39316 t15 += v * b10;
39317 t16 += v * b11;
39318 t17 += v * b12;
39319 t18 += v * b13;
39320 t19 += v * b14;
39321 t20 += v * b15;
39322 v = a[6];
39323 t6 += v * b0;
39324 t7 += v * b1;
39325 t8 += v * b2;
39326 t9 += v * b3;
39327 t10 += v * b4;
39328 t11 += v * b5;
39329 t12 += v * b6;
39330 t13 += v * b7;
39331 t14 += v * b8;
39332 t15 += v * b9;
39333 t16 += v * b10;
39334 t17 += v * b11;
39335 t18 += v * b12;
39336 t19 += v * b13;
39337 t20 += v * b14;
39338 t21 += v * b15;
39339 v = a[7];
39340 t7 += v * b0;
39341 t8 += v * b1;
39342 t9 += v * b2;
39343 t10 += v * b3;
39344 t11 += v * b4;
39345 t12 += v * b5;
39346 t13 += v * b6;
39347 t14 += v * b7;
39348 t15 += v * b8;
39349 t16 += v * b9;
39350 t17 += v * b10;
39351 t18 += v * b11;
39352 t19 += v * b12;
39353 t20 += v * b13;
39354 t21 += v * b14;
39355 t22 += v * b15;
39356 v = a[8];
39357 t8 += v * b0;
39358 t9 += v * b1;
39359 t10 += v * b2;
39360 t11 += v * b3;
39361 t12 += v * b4;
39362 t13 += v * b5;
39363 t14 += v * b6;
39364 t15 += v * b7;
39365 t16 += v * b8;
39366 t17 += v * b9;
39367 t18 += v * b10;
39368 t19 += v * b11;
39369 t20 += v * b12;
39370 t21 += v * b13;
39371 t22 += v * b14;
39372 t23 += v * b15;
39373 v = a[9];
39374 t9 += v * b0;
39375 t10 += v * b1;
39376 t11 += v * b2;
39377 t12 += v * b3;
39378 t13 += v * b4;
39379 t14 += v * b5;
39380 t15 += v * b6;
39381 t16 += v * b7;
39382 t17 += v * b8;
39383 t18 += v * b9;
39384 t19 += v * b10;
39385 t20 += v * b11;
39386 t21 += v * b12;
39387 t22 += v * b13;
39388 t23 += v * b14;
39389 t24 += v * b15;
39390 v = a[10];
39391 t10 += v * b0;
39392 t11 += v * b1;
39393 t12 += v * b2;
39394 t13 += v * b3;
39395 t14 += v * b4;
39396 t15 += v * b5;
39397 t16 += v * b6;
39398 t17 += v * b7;
39399 t18 += v * b8;
39400 t19 += v * b9;
39401 t20 += v * b10;
39402 t21 += v * b11;
39403 t22 += v * b12;
39404 t23 += v * b13;
39405 t24 += v * b14;
39406 t25 += v * b15;
39407 v = a[11];
39408 t11 += v * b0;
39409 t12 += v * b1;
39410 t13 += v * b2;
39411 t14 += v * b3;
39412 t15 += v * b4;
39413 t16 += v * b5;
39414 t17 += v * b6;
39415 t18 += v * b7;
39416 t19 += v * b8;
39417 t20 += v * b9;
39418 t21 += v * b10;
39419 t22 += v * b11;
39420 t23 += v * b12;
39421 t24 += v * b13;
39422 t25 += v * b14;
39423 t26 += v * b15;
39424 v = a[12];
39425 t12 += v * b0;
39426 t13 += v * b1;
39427 t14 += v * b2;
39428 t15 += v * b3;
39429 t16 += v * b4;
39430 t17 += v * b5;
39431 t18 += v * b6;
39432 t19 += v * b7;
39433 t20 += v * b8;
39434 t21 += v * b9;
39435 t22 += v * b10;
39436 t23 += v * b11;
39437 t24 += v * b12;
39438 t25 += v * b13;
39439 t26 += v * b14;
39440 t27 += v * b15;
39441 v = a[13];
39442 t13 += v * b0;
39443 t14 += v * b1;
39444 t15 += v * b2;
39445 t16 += v * b3;
39446 t17 += v * b4;
39447 t18 += v * b5;
39448 t19 += v * b6;
39449 t20 += v * b7;
39450 t21 += v * b8;
39451 t22 += v * b9;
39452 t23 += v * b10;
39453 t24 += v * b11;
39454 t25 += v * b12;
39455 t26 += v * b13;
39456 t27 += v * b14;
39457 t28 += v * b15;
39458 v = a[14];
39459 t14 += v * b0;
39460 t15 += v * b1;
39461 t16 += v * b2;
39462 t17 += v * b3;
39463 t18 += v * b4;
39464 t19 += v * b5;
39465 t20 += v * b6;
39466 t21 += v * b7;
39467 t22 += v * b8;
39468 t23 += v * b9;
39469 t24 += v * b10;
39470 t25 += v * b11;
39471 t26 += v * b12;
39472 t27 += v * b13;
39473 t28 += v * b14;
39474 t29 += v * b15;
39475 v = a[15];
39476 t15 += v * b0;
39477 t16 += v * b1;
39478 t17 += v * b2;
39479 t18 += v * b3;
39480 t19 += v * b4;
39481 t20 += v * b5;
39482 t21 += v * b6;
39483 t22 += v * b7;
39484 t23 += v * b8;
39485 t24 += v * b9;
39486 t25 += v * b10;
39487 t26 += v * b11;
39488 t27 += v * b12;
39489 t28 += v * b13;
39490 t29 += v * b14;
39491 t30 += v * b15;
39492
39493 t0 += 38 * t16;
39494 t1 += 38 * t17;
39495 t2 += 38 * t18;
39496 t3 += 38 * t19;
39497 t4 += 38 * t20;
39498 t5 += 38 * t21;
39499 t6 += 38 * t22;
39500 t7 += 38 * t23;
39501 t8 += 38 * t24;
39502 t9 += 38 * t25;
39503 t10 += 38 * t26;
39504 t11 += 38 * t27;
39505 t12 += 38 * t28;
39506 t13 += 38 * t29;
39507 t14 += 38 * t30;
39508 // t15 left as is
39509
39510 // first car
39511 c = 1;
39512 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
39513 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
39514 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
39515 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
39516 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
39517 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
39518 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
39519 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
39520 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
39521 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
39522 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
39523 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
39524 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
39525 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
39526 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
39527 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
39528 t0 += c-1 + 37 * (c-1);
39529
39530 // second car
39531 c = 1;
39532 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
39533 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
39534 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
39535 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
39536 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
39537 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
39538 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
39539 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
39540 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
39541 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
39542 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
39543 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
39544 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
39545 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
39546 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
39547 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
39548 t0 += c-1 + 37 * (c-1);
39549
39550 o[ 0] = t0;
39551 o[ 1] = t1;
39552 o[ 2] = t2;
39553 o[ 3] = t3;
39554 o[ 4] = t4;
39555 o[ 5] = t5;
39556 o[ 6] = t6;
39557 o[ 7] = t7;
39558 o[ 8] = t8;
39559 o[ 9] = t9;
39560 o[10] = t10;
39561 o[11] = t11;
39562 o[12] = t12;
39563 o[13] = t13;
39564 o[14] = t14;
39565 o[15] = t15;
39566}
39567
39568function S(o, a) {
39569 M(o, a, a);
39570}
39571
39572function inv25519(o, i) {
39573 var c = gf();
39574 var a;
39575 for (a = 0; a < 16; a++) c[a] = i[a];
39576 for (a = 253; a >= 0; a--) {
39577 S(c, c);
39578 if(a !== 2 && a !== 4) M(c, c, i);
39579 }
39580 for (a = 0; a < 16; a++) o[a] = c[a];
39581}
39582
39583function pow2523(o, i) {
39584 var c = gf();
39585 var a;
39586 for (a = 0; a < 16; a++) c[a] = i[a];
39587 for (a = 250; a >= 0; a--) {
39588 S(c, c);
39589 if(a !== 1) M(c, c, i);
39590 }
39591 for (a = 0; a < 16; a++) o[a] = c[a];
39592}
39593
39594function crypto_scalarmult(q, n, p) {
39595 var z = new Uint8Array(32);
39596 var x = new Float64Array(80), r, i;
39597 var a = gf(), b = gf(), c = gf(),
39598 d = gf(), e = gf(), f = gf();
39599 for (i = 0; i < 31; i++) z[i] = n[i];
39600 z[31]=(n[31]&127)|64;
39601 z[0]&=248;
39602 unpack25519(x,p);
39603 for (i = 0; i < 16; i++) {
39604 b[i]=x[i];
39605 d[i]=a[i]=c[i]=0;
39606 }
39607 a[0]=d[0]=1;
39608 for (i=254; i>=0; --i) {
39609 r=(z[i>>>3]>>>(i&7))&1;
39610 sel25519(a,b,r);
39611 sel25519(c,d,r);
39612 A(e,a,c);
39613 Z(a,a,c);
39614 A(c,b,d);
39615 Z(b,b,d);
39616 S(d,e);
39617 S(f,a);
39618 M(a,c,a);
39619 M(c,b,e);
39620 A(e,a,c);
39621 Z(a,a,c);
39622 S(b,a);
39623 Z(c,d,f);
39624 M(a,c,_121665);
39625 A(a,a,d);
39626 M(c,c,a);
39627 M(a,d,f);
39628 M(d,b,x);
39629 S(b,e);
39630 sel25519(a,b,r);
39631 sel25519(c,d,r);
39632 }
39633 for (i = 0; i < 16; i++) {
39634 x[i+16]=a[i];
39635 x[i+32]=c[i];
39636 x[i+48]=b[i];
39637 x[i+64]=d[i];
39638 }
39639 var x32 = x.subarray(32);
39640 var x16 = x.subarray(16);
39641 inv25519(x32,x32);
39642 M(x16,x16,x32);
39643 pack25519(q,x16);
39644 return 0;
39645}
39646
39647function crypto_scalarmult_base(q, n) {
39648 return crypto_scalarmult(q, n, _9);
39649}
39650
39651function crypto_box_keypair(y, x) {
39652 randombytes(x, 32);
39653 return crypto_scalarmult_base(y, x);
39654}
39655
39656function crypto_box_beforenm(k, y, x) {
39657 var s = new Uint8Array(32);
39658 crypto_scalarmult(s, x, y);
39659 return crypto_core_hsalsa20(k, _0, s, sigma);
39660}
39661
39662var crypto_box_afternm = crypto_secretbox;
39663var crypto_box_open_afternm = crypto_secretbox_open;
39664
39665function crypto_box(c, m, d, n, y, x) {
39666 var k = new Uint8Array(32);
39667 crypto_box_beforenm(k, y, x);
39668 return crypto_box_afternm(c, m, d, n, k);
39669}
39670
39671function crypto_box_open(m, c, d, n, y, x) {
39672 var k = new Uint8Array(32);
39673 crypto_box_beforenm(k, y, x);
39674 return crypto_box_open_afternm(m, c, d, n, k);
39675}
39676
39677var K = [
39678 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
39679 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
39680 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
39681 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
39682 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
39683 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
39684 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
39685 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
39686 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
39687 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
39688 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
39689 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
39690 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
39691 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
39692 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
39693 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
39694 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
39695 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
39696 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
39697 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
39698 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
39699 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
39700 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
39701 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
39702 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
39703 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
39704 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
39705 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
39706 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
39707 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
39708 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
39709 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
39710 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
39711 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
39712 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
39713 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
39714 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
39715 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
39716 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
39717 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
39718];
39719
39720function crypto_hashblocks_hl(hh, hl, m, n) {
39721 var wh = new Int32Array(16), wl = new Int32Array(16),
39722 bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
39723 bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
39724 th, tl, i, j, h, l, a, b, c, d;
39725
39726 var ah0 = hh[0],
39727 ah1 = hh[1],
39728 ah2 = hh[2],
39729 ah3 = hh[3],
39730 ah4 = hh[4],
39731 ah5 = hh[5],
39732 ah6 = hh[6],
39733 ah7 = hh[7],
39734
39735 al0 = hl[0],
39736 al1 = hl[1],
39737 al2 = hl[2],
39738 al3 = hl[3],
39739 al4 = hl[4],
39740 al5 = hl[5],
39741 al6 = hl[6],
39742 al7 = hl[7];
39743
39744 var pos = 0;
39745 while (n >= 128) {
39746 for (i = 0; i < 16; i++) {
39747 j = 8 * i + pos;
39748 wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
39749 wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
39750 }
39751 for (i = 0; i < 80; i++) {
39752 bh0 = ah0;
39753 bh1 = ah1;
39754 bh2 = ah2;
39755 bh3 = ah3;
39756 bh4 = ah4;
39757 bh5 = ah5;
39758 bh6 = ah6;
39759 bh7 = ah7;
39760
39761 bl0 = al0;
39762 bl1 = al1;
39763 bl2 = al2;
39764 bl3 = al3;
39765 bl4 = al4;
39766 bl5 = al5;
39767 bl6 = al6;
39768 bl7 = al7;
39769
39770 // add
39771 h = ah7;
39772 l = al7;
39773
39774 a = l & 0xffff; b = l >>> 16;
39775 c = h & 0xffff; d = h >>> 16;
39776
39777 // Sigma1
39778 h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
39779 l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
39780
39781 a += l & 0xffff; b += l >>> 16;
39782 c += h & 0xffff; d += h >>> 16;
39783
39784 // Ch
39785 h = (ah4 & ah5) ^ (~ah4 & ah6);
39786 l = (al4 & al5) ^ (~al4 & al6);
39787
39788 a += l & 0xffff; b += l >>> 16;
39789 c += h & 0xffff; d += h >>> 16;
39790
39791 // K
39792 h = K[i*2];
39793 l = K[i*2+1];
39794
39795 a += l & 0xffff; b += l >>> 16;
39796 c += h & 0xffff; d += h >>> 16;
39797
39798 // w
39799 h = wh[i%16];
39800 l = wl[i%16];
39801
39802 a += l & 0xffff; b += l >>> 16;
39803 c += h & 0xffff; d += h >>> 16;
39804
39805 b += a >>> 16;
39806 c += b >>> 16;
39807 d += c >>> 16;
39808
39809 th = c & 0xffff | d << 16;
39810 tl = a & 0xffff | b << 16;
39811
39812 // add
39813 h = th;
39814 l = tl;
39815
39816 a = l & 0xffff; b = l >>> 16;
39817 c = h & 0xffff; d = h >>> 16;
39818
39819 // Sigma0
39820 h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
39821 l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
39822
39823 a += l & 0xffff; b += l >>> 16;
39824 c += h & 0xffff; d += h >>> 16;
39825
39826 // Maj
39827 h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
39828 l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
39829
39830 a += l & 0xffff; b += l >>> 16;
39831 c += h & 0xffff; d += h >>> 16;
39832
39833 b += a >>> 16;
39834 c += b >>> 16;
39835 d += c >>> 16;
39836
39837 bh7 = (c & 0xffff) | (d << 16);
39838 bl7 = (a & 0xffff) | (b << 16);
39839
39840 // add
39841 h = bh3;
39842 l = bl3;
39843
39844 a = l & 0xffff; b = l >>> 16;
39845 c = h & 0xffff; d = h >>> 16;
39846
39847 h = th;
39848 l = tl;
39849
39850 a += l & 0xffff; b += l >>> 16;
39851 c += h & 0xffff; d += h >>> 16;
39852
39853 b += a >>> 16;
39854 c += b >>> 16;
39855 d += c >>> 16;
39856
39857 bh3 = (c & 0xffff) | (d << 16);
39858 bl3 = (a & 0xffff) | (b << 16);
39859
39860 ah1 = bh0;
39861 ah2 = bh1;
39862 ah3 = bh2;
39863 ah4 = bh3;
39864 ah5 = bh4;
39865 ah6 = bh5;
39866 ah7 = bh6;
39867 ah0 = bh7;
39868
39869 al1 = bl0;
39870 al2 = bl1;
39871 al3 = bl2;
39872 al4 = bl3;
39873 al5 = bl4;
39874 al6 = bl5;
39875 al7 = bl6;
39876 al0 = bl7;
39877
39878 if (i%16 === 15) {
39879 for (j = 0; j < 16; j++) {
39880 // add
39881 h = wh[j];
39882 l = wl[j];
39883
39884 a = l & 0xffff; b = l >>> 16;
39885 c = h & 0xffff; d = h >>> 16;
39886
39887 h = wh[(j+9)%16];
39888 l = wl[(j+9)%16];
39889
39890 a += l & 0xffff; b += l >>> 16;
39891 c += h & 0xffff; d += h >>> 16;
39892
39893 // sigma0
39894 th = wh[(j+1)%16];
39895 tl = wl[(j+1)%16];
39896 h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
39897 l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
39898
39899 a += l & 0xffff; b += l >>> 16;
39900 c += h & 0xffff; d += h >>> 16;
39901
39902 // sigma1
39903 th = wh[(j+14)%16];
39904 tl = wl[(j+14)%16];
39905 h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
39906 l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
39907
39908 a += l & 0xffff; b += l >>> 16;
39909 c += h & 0xffff; d += h >>> 16;
39910
39911 b += a >>> 16;
39912 c += b >>> 16;
39913 d += c >>> 16;
39914
39915 wh[j] = (c & 0xffff) | (d << 16);
39916 wl[j] = (a & 0xffff) | (b << 16);
39917 }
39918 }
39919 }
39920
39921 // add
39922 h = ah0;
39923 l = al0;
39924
39925 a = l & 0xffff; b = l >>> 16;
39926 c = h & 0xffff; d = h >>> 16;
39927
39928 h = hh[0];
39929 l = hl[0];
39930
39931 a += l & 0xffff; b += l >>> 16;
39932 c += h & 0xffff; d += h >>> 16;
39933
39934 b += a >>> 16;
39935 c += b >>> 16;
39936 d += c >>> 16;
39937
39938 hh[0] = ah0 = (c & 0xffff) | (d << 16);
39939 hl[0] = al0 = (a & 0xffff) | (b << 16);
39940
39941 h = ah1;
39942 l = al1;
39943
39944 a = l & 0xffff; b = l >>> 16;
39945 c = h & 0xffff; d = h >>> 16;
39946
39947 h = hh[1];
39948 l = hl[1];
39949
39950 a += l & 0xffff; b += l >>> 16;
39951 c += h & 0xffff; d += h >>> 16;
39952
39953 b += a >>> 16;
39954 c += b >>> 16;
39955 d += c >>> 16;
39956
39957 hh[1] = ah1 = (c & 0xffff) | (d << 16);
39958 hl[1] = al1 = (a & 0xffff) | (b << 16);
39959
39960 h = ah2;
39961 l = al2;
39962
39963 a = l & 0xffff; b = l >>> 16;
39964 c = h & 0xffff; d = h >>> 16;
39965
39966 h = hh[2];
39967 l = hl[2];
39968
39969 a += l & 0xffff; b += l >>> 16;
39970 c += h & 0xffff; d += h >>> 16;
39971
39972 b += a >>> 16;
39973 c += b >>> 16;
39974 d += c >>> 16;
39975
39976 hh[2] = ah2 = (c & 0xffff) | (d << 16);
39977 hl[2] = al2 = (a & 0xffff) | (b << 16);
39978
39979 h = ah3;
39980 l = al3;
39981
39982 a = l & 0xffff; b = l >>> 16;
39983 c = h & 0xffff; d = h >>> 16;
39984
39985 h = hh[3];
39986 l = hl[3];
39987
39988 a += l & 0xffff; b += l >>> 16;
39989 c += h & 0xffff; d += h >>> 16;
39990
39991 b += a >>> 16;
39992 c += b >>> 16;
39993 d += c >>> 16;
39994
39995 hh[3] = ah3 = (c & 0xffff) | (d << 16);
39996 hl[3] = al3 = (a & 0xffff) | (b << 16);
39997
39998 h = ah4;
39999 l = al4;
40000
40001 a = l & 0xffff; b = l >>> 16;
40002 c = h & 0xffff; d = h >>> 16;
40003
40004 h = hh[4];
40005 l = hl[4];
40006
40007 a += l & 0xffff; b += l >>> 16;
40008 c += h & 0xffff; d += h >>> 16;
40009
40010 b += a >>> 16;
40011 c += b >>> 16;
40012 d += c >>> 16;
40013
40014 hh[4] = ah4 = (c & 0xffff) | (d << 16);
40015 hl[4] = al4 = (a & 0xffff) | (b << 16);
40016
40017 h = ah5;
40018 l = al5;
40019
40020 a = l & 0xffff; b = l >>> 16;
40021 c = h & 0xffff; d = h >>> 16;
40022
40023 h = hh[5];
40024 l = hl[5];
40025
40026 a += l & 0xffff; b += l >>> 16;
40027 c += h & 0xffff; d += h >>> 16;
40028
40029 b += a >>> 16;
40030 c += b >>> 16;
40031 d += c >>> 16;
40032
40033 hh[5] = ah5 = (c & 0xffff) | (d << 16);
40034 hl[5] = al5 = (a & 0xffff) | (b << 16);
40035
40036 h = ah6;
40037 l = al6;
40038
40039 a = l & 0xffff; b = l >>> 16;
40040 c = h & 0xffff; d = h >>> 16;
40041
40042 h = hh[6];
40043 l = hl[6];
40044
40045 a += l & 0xffff; b += l >>> 16;
40046 c += h & 0xffff; d += h >>> 16;
40047
40048 b += a >>> 16;
40049 c += b >>> 16;
40050 d += c >>> 16;
40051
40052 hh[6] = ah6 = (c & 0xffff) | (d << 16);
40053 hl[6] = al6 = (a & 0xffff) | (b << 16);
40054
40055 h = ah7;
40056 l = al7;
40057
40058 a = l & 0xffff; b = l >>> 16;
40059 c = h & 0xffff; d = h >>> 16;
40060
40061 h = hh[7];
40062 l = hl[7];
40063
40064 a += l & 0xffff; b += l >>> 16;
40065 c += h & 0xffff; d += h >>> 16;
40066
40067 b += a >>> 16;
40068 c += b >>> 16;
40069 d += c >>> 16;
40070
40071 hh[7] = ah7 = (c & 0xffff) | (d << 16);
40072 hl[7] = al7 = (a & 0xffff) | (b << 16);
40073
40074 pos += 128;
40075 n -= 128;
40076 }
40077
40078 return n;
40079}
40080
40081function crypto_hash(out, m, n) {
40082 var hh = new Int32Array(8),
40083 hl = new Int32Array(8),
40084 x = new Uint8Array(256),
40085 i, b = n;
40086
40087 hh[0] = 0x6a09e667;
40088 hh[1] = 0xbb67ae85;
40089 hh[2] = 0x3c6ef372;
40090 hh[3] = 0xa54ff53a;
40091 hh[4] = 0x510e527f;
40092 hh[5] = 0x9b05688c;
40093 hh[6] = 0x1f83d9ab;
40094 hh[7] = 0x5be0cd19;
40095
40096 hl[0] = 0xf3bcc908;
40097 hl[1] = 0x84caa73b;
40098 hl[2] = 0xfe94f82b;
40099 hl[3] = 0x5f1d36f1;
40100 hl[4] = 0xade682d1;
40101 hl[5] = 0x2b3e6c1f;
40102 hl[6] = 0xfb41bd6b;
40103 hl[7] = 0x137e2179;
40104
40105 crypto_hashblocks_hl(hh, hl, m, n);
40106 n %= 128;
40107
40108 for (i = 0; i < n; i++) x[i] = m[b-n+i];
40109 x[n] = 128;
40110
40111 n = 256-128*(n<112?1:0);
40112 x[n-9] = 0;
40113 ts64(x, n-8, (b / 0x20000000) | 0, b << 3);
40114 crypto_hashblocks_hl(hh, hl, x, n);
40115
40116 for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);
40117
40118 return 0;
40119}
40120
40121function add(p, q) {
40122 var a = gf(), b = gf(), c = gf(),
40123 d = gf(), e = gf(), f = gf(),
40124 g = gf(), h = gf(), t = gf();
40125
40126 Z(a, p[1], p[0]);
40127 Z(t, q[1], q[0]);
40128 M(a, a, t);
40129 A(b, p[0], p[1]);
40130 A(t, q[0], q[1]);
40131 M(b, b, t);
40132 M(c, p[3], q[3]);
40133 M(c, c, D2);
40134 M(d, p[2], q[2]);
40135 A(d, d, d);
40136 Z(e, b, a);
40137 Z(f, d, c);
40138 A(g, d, c);
40139 A(h, b, a);
40140
40141 M(p[0], e, f);
40142 M(p[1], h, g);
40143 M(p[2], g, f);
40144 M(p[3], e, h);
40145}
40146
40147function cswap(p, q, b) {
40148 var i;
40149 for (i = 0; i < 4; i++) {
40150 sel25519(p[i], q[i], b);
40151 }
40152}
40153
40154function pack(r, p) {
40155 var tx = gf(), ty = gf(), zi = gf();
40156 inv25519(zi, p[2]);
40157 M(tx, p[0], zi);
40158 M(ty, p[1], zi);
40159 pack25519(r, ty);
40160 r[31] ^= par25519(tx) << 7;
40161}
40162
40163function scalarmult(p, q, s) {
40164 var b, i;
40165 set25519(p[0], gf0);
40166 set25519(p[1], gf1);
40167 set25519(p[2], gf1);
40168 set25519(p[3], gf0);
40169 for (i = 255; i >= 0; --i) {
40170 b = (s[(i/8)|0] >> (i&7)) & 1;
40171 cswap(p, q, b);
40172 add(q, p);
40173 add(p, p);
40174 cswap(p, q, b);
40175 }
40176}
40177
40178function scalarbase(p, s) {
40179 var q = [gf(), gf(), gf(), gf()];
40180 set25519(q[0], X);
40181 set25519(q[1], Y);
40182 set25519(q[2], gf1);
40183 M(q[3], X, Y);
40184 scalarmult(p, q, s);
40185}
40186
40187function crypto_sign_keypair(pk, sk, seeded) {
40188 var d = new Uint8Array(64);
40189 var p = [gf(), gf(), gf(), gf()];
40190 var i;
40191
40192 if (!seeded) randombytes(sk, 32);
40193 crypto_hash(d, sk, 32);
40194 d[0] &= 248;
40195 d[31] &= 127;
40196 d[31] |= 64;
40197
40198 scalarbase(p, d);
40199 pack(pk, p);
40200
40201 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
40202 return 0;
40203}
40204
40205var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
40206
40207function modL(r, x) {
40208 var carry, i, j, k;
40209 for (i = 63; i >= 32; --i) {
40210 carry = 0;
40211 for (j = i - 32, k = i - 12; j < k; ++j) {
40212 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
40213 carry = (x[j] + 128) >> 8;
40214 x[j] -= carry * 256;
40215 }
40216 x[j] += carry;
40217 x[i] = 0;
40218 }
40219 carry = 0;
40220 for (j = 0; j < 32; j++) {
40221 x[j] += carry - (x[31] >> 4) * L[j];
40222 carry = x[j] >> 8;
40223 x[j] &= 255;
40224 }
40225 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
40226 for (i = 0; i < 32; i++) {
40227 x[i+1] += x[i] >> 8;
40228 r[i] = x[i] & 255;
40229 }
40230}
40231
40232function reduce(r) {
40233 var x = new Float64Array(64), i;
40234 for (i = 0; i < 64; i++) x[i] = r[i];
40235 for (i = 0; i < 64; i++) r[i] = 0;
40236 modL(r, x);
40237}
40238
40239// Note: difference from C - smlen returned, not passed as argument.
40240function crypto_sign(sm, m, n, sk) {
40241 var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
40242 var i, j, x = new Float64Array(64);
40243 var p = [gf(), gf(), gf(), gf()];
40244
40245 crypto_hash(d, sk, 32);
40246 d[0] &= 248;
40247 d[31] &= 127;
40248 d[31] |= 64;
40249
40250 var smlen = n + 64;
40251 for (i = 0; i < n; i++) sm[64 + i] = m[i];
40252 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
40253
40254 crypto_hash(r, sm.subarray(32), n+32);
40255 reduce(r);
40256 scalarbase(p, r);
40257 pack(sm, p);
40258
40259 for (i = 32; i < 64; i++) sm[i] = sk[i];
40260 crypto_hash(h, sm, n + 64);
40261 reduce(h);
40262
40263 for (i = 0; i < 64; i++) x[i] = 0;
40264 for (i = 0; i < 32; i++) x[i] = r[i];
40265 for (i = 0; i < 32; i++) {
40266 for (j = 0; j < 32; j++) {
40267 x[i+j] += h[i] * d[j];
40268 }
40269 }
40270
40271 modL(sm.subarray(32), x);
40272 return smlen;
40273}
40274
40275function unpackneg(r, p) {
40276 var t = gf(), chk = gf(), num = gf(),
40277 den = gf(), den2 = gf(), den4 = gf(),
40278 den6 = gf();
40279
40280 set25519(r[2], gf1);
40281 unpack25519(r[1], p);
40282 S(num, r[1]);
40283 M(den, num, D);
40284 Z(num, num, r[2]);
40285 A(den, r[2], den);
40286
40287 S(den2, den);
40288 S(den4, den2);
40289 M(den6, den4, den2);
40290 M(t, den6, num);
40291 M(t, t, den);
40292
40293 pow2523(t, t);
40294 M(t, t, num);
40295 M(t, t, den);
40296 M(t, t, den);
40297 M(r[0], t, den);
40298
40299 S(chk, r[0]);
40300 M(chk, chk, den);
40301 if (neq25519(chk, num)) M(r[0], r[0], I);
40302
40303 S(chk, r[0]);
40304 M(chk, chk, den);
40305 if (neq25519(chk, num)) return -1;
40306
40307 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
40308
40309 M(r[3], r[0], r[1]);
40310 return 0;
40311}
40312
40313function crypto_sign_open(m, sm, n, pk) {
40314 var i, mlen;
40315 var t = new Uint8Array(32), h = new Uint8Array(64);
40316 var p = [gf(), gf(), gf(), gf()],
40317 q = [gf(), gf(), gf(), gf()];
40318
40319 mlen = -1;
40320 if (n < 64) return -1;
40321
40322 if (unpackneg(q, pk)) return -1;
40323
40324 for (i = 0; i < n; i++) m[i] = sm[i];
40325 for (i = 0; i < 32; i++) m[i+32] = pk[i];
40326 crypto_hash(h, m, n);
40327 reduce(h);
40328 scalarmult(p, q, h);
40329
40330 scalarbase(q, sm.subarray(32));
40331 add(p, q);
40332 pack(t, p);
40333
40334 n -= 64;
40335 if (crypto_verify_32(sm, 0, t, 0)) {
40336 for (i = 0; i < n; i++) m[i] = 0;
40337 return -1;
40338 }
40339
40340 for (i = 0; i < n; i++) m[i] = sm[i + 64];
40341 mlen = n;
40342 return mlen;
40343}
40344
40345var crypto_secretbox_KEYBYTES = 32,
40346 crypto_secretbox_NONCEBYTES = 24,
40347 crypto_secretbox_ZEROBYTES = 32,
40348 crypto_secretbox_BOXZEROBYTES = 16,
40349 crypto_scalarmult_BYTES = 32,
40350 crypto_scalarmult_SCALARBYTES = 32,
40351 crypto_box_PUBLICKEYBYTES = 32,
40352 crypto_box_SECRETKEYBYTES = 32,
40353 crypto_box_BEFORENMBYTES = 32,
40354 crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
40355 crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
40356 crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
40357 crypto_sign_BYTES = 64,
40358 crypto_sign_PUBLICKEYBYTES = 32,
40359 crypto_sign_SECRETKEYBYTES = 64,
40360 crypto_sign_SEEDBYTES = 32,
40361 crypto_hash_BYTES = 64;
40362
40363nacl.lowlevel = {
40364 crypto_core_hsalsa20: crypto_core_hsalsa20,
40365 crypto_stream_xor: crypto_stream_xor,
40366 crypto_stream: crypto_stream,
40367 crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
40368 crypto_stream_salsa20: crypto_stream_salsa20,
40369 crypto_onetimeauth: crypto_onetimeauth,
40370 crypto_onetimeauth_verify: crypto_onetimeauth_verify,
40371 crypto_verify_16: crypto_verify_16,
40372 crypto_verify_32: crypto_verify_32,
40373 crypto_secretbox: crypto_secretbox,
40374 crypto_secretbox_open: crypto_secretbox_open,
40375 crypto_scalarmult: crypto_scalarmult,
40376 crypto_scalarmult_base: crypto_scalarmult_base,
40377 crypto_box_beforenm: crypto_box_beforenm,
40378 crypto_box_afternm: crypto_box_afternm,
40379 crypto_box: crypto_box,
40380 crypto_box_open: crypto_box_open,
40381 crypto_box_keypair: crypto_box_keypair,
40382 crypto_hash: crypto_hash,
40383 crypto_sign: crypto_sign,
40384 crypto_sign_keypair: crypto_sign_keypair,
40385 crypto_sign_open: crypto_sign_open,
40386
40387 crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
40388 crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
40389 crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
40390 crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
40391 crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
40392 crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
40393 crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
40394 crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
40395 crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
40396 crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
40397 crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
40398 crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
40399 crypto_sign_BYTES: crypto_sign_BYTES,
40400 crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
40401 crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
40402 crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
40403 crypto_hash_BYTES: crypto_hash_BYTES
40404};
40405
40406/* High-level API */
40407
40408function checkLengths(k, n) {
40409 if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
40410 if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
40411}
40412
40413function checkBoxLengths(pk, sk) {
40414 if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');
40415 if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');
40416}
40417
40418function checkArrayTypes() {
40419 for (var i = 0; i < arguments.length; i++) {
40420 if (!(arguments[i] instanceof Uint8Array))
40421 throw new TypeError('unexpected type, use Uint8Array');
40422 }
40423}
40424
40425function cleanup(arr) {
40426 for (var i = 0; i < arr.length; i++) arr[i] = 0;
40427}
40428
40429nacl.randomBytes = function(n) {
40430 var b = new Uint8Array(n);
40431 randombytes(b, n);
40432 return b;
40433};
40434
40435nacl.secretbox = function(msg, nonce, key) {
40436 checkArrayTypes(msg, nonce, key);
40437 checkLengths(key, nonce);
40438 var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
40439 var c = new Uint8Array(m.length);
40440 for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];
40441 crypto_secretbox(c, m, m.length, nonce, key);
40442 return c.subarray(crypto_secretbox_BOXZEROBYTES);
40443};
40444
40445nacl.secretbox.open = function(box, nonce, key) {
40446 checkArrayTypes(box, nonce, key);
40447 checkLengths(key, nonce);
40448 var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
40449 var m = new Uint8Array(c.length);
40450 for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];
40451 if (c.length < 32) return null;
40452 if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;
40453 return m.subarray(crypto_secretbox_ZEROBYTES);
40454};
40455
40456nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
40457nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
40458nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
40459
40460nacl.scalarMult = function(n, p) {
40461 checkArrayTypes(n, p);
40462 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
40463 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
40464 var q = new Uint8Array(crypto_scalarmult_BYTES);
40465 crypto_scalarmult(q, n, p);
40466 return q;
40467};
40468
40469nacl.scalarMult.base = function(n) {
40470 checkArrayTypes(n);
40471 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
40472 var q = new Uint8Array(crypto_scalarmult_BYTES);
40473 crypto_scalarmult_base(q, n);
40474 return q;
40475};
40476
40477nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
40478nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
40479
40480nacl.box = function(msg, nonce, publicKey, secretKey) {
40481 var k = nacl.box.before(publicKey, secretKey);
40482 return nacl.secretbox(msg, nonce, k);
40483};
40484
40485nacl.box.before = function(publicKey, secretKey) {
40486 checkArrayTypes(publicKey, secretKey);
40487 checkBoxLengths(publicKey, secretKey);
40488 var k = new Uint8Array(crypto_box_BEFORENMBYTES);
40489 crypto_box_beforenm(k, publicKey, secretKey);
40490 return k;
40491};
40492
40493nacl.box.after = nacl.secretbox;
40494
40495nacl.box.open = function(msg, nonce, publicKey, secretKey) {
40496 var k = nacl.box.before(publicKey, secretKey);
40497 return nacl.secretbox.open(msg, nonce, k);
40498};
40499
40500nacl.box.open.after = nacl.secretbox.open;
40501
40502nacl.box.keyPair = function() {
40503 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
40504 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
40505 crypto_box_keypair(pk, sk);
40506 return {publicKey: pk, secretKey: sk};
40507};
40508
40509nacl.box.keyPair.fromSecretKey = function(secretKey) {
40510 checkArrayTypes(secretKey);
40511 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
40512 throw new Error('bad secret key size');
40513 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
40514 crypto_scalarmult_base(pk, secretKey);
40515 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
40516};
40517
40518nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
40519nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
40520nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
40521nacl.box.nonceLength = crypto_box_NONCEBYTES;
40522nacl.box.overheadLength = nacl.secretbox.overheadLength;
40523
40524nacl.sign = function(msg, secretKey) {
40525 checkArrayTypes(msg, secretKey);
40526 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
40527 throw new Error('bad secret key size');
40528 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
40529 crypto_sign(signedMsg, msg, msg.length, secretKey);
40530 return signedMsg;
40531};
40532
40533nacl.sign.open = function(signedMsg, publicKey) {
40534 checkArrayTypes(signedMsg, publicKey);
40535 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
40536 throw new Error('bad public key size');
40537 var tmp = new Uint8Array(signedMsg.length);
40538 var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
40539 if (mlen < 0) return null;
40540 var m = new Uint8Array(mlen);
40541 for (var i = 0; i < m.length; i++) m[i] = tmp[i];
40542 return m;
40543};
40544
40545nacl.sign.detached = function(msg, secretKey) {
40546 var signedMsg = nacl.sign(msg, secretKey);
40547 var sig = new Uint8Array(crypto_sign_BYTES);
40548 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
40549 return sig;
40550};
40551
40552nacl.sign.detached.verify = function(msg, sig, publicKey) {
40553 checkArrayTypes(msg, sig, publicKey);
40554 if (sig.length !== crypto_sign_BYTES)
40555 throw new Error('bad signature size');
40556 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
40557 throw new Error('bad public key size');
40558 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
40559 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
40560 var i;
40561 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
40562 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
40563 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
40564};
40565
40566nacl.sign.keyPair = function() {
40567 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
40568 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
40569 crypto_sign_keypair(pk, sk);
40570 return {publicKey: pk, secretKey: sk};
40571};
40572
40573nacl.sign.keyPair.fromSecretKey = function(secretKey) {
40574 checkArrayTypes(secretKey);
40575 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
40576 throw new Error('bad secret key size');
40577 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
40578 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
40579 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
40580};
40581
40582nacl.sign.keyPair.fromSeed = function(seed) {
40583 checkArrayTypes(seed);
40584 if (seed.length !== crypto_sign_SEEDBYTES)
40585 throw new Error('bad seed size');
40586 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
40587 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
40588 for (var i = 0; i < 32; i++) sk[i] = seed[i];
40589 crypto_sign_keypair(pk, sk, true);
40590 return {publicKey: pk, secretKey: sk};
40591};
40592
40593nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
40594nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
40595nacl.sign.seedLength = crypto_sign_SEEDBYTES;
40596nacl.sign.signatureLength = crypto_sign_BYTES;
40597
40598nacl.hash = function(msg) {
40599 checkArrayTypes(msg);
40600 var h = new Uint8Array(crypto_hash_BYTES);
40601 crypto_hash(h, msg, msg.length);
40602 return h;
40603};
40604
40605nacl.hash.hashLength = crypto_hash_BYTES;
40606
40607nacl.verify = function(x, y) {
40608 checkArrayTypes(x, y);
40609 // Zero length arguments are considered not equal.
40610 if (x.length === 0 || y.length === 0) return false;
40611 if (x.length !== y.length) return false;
40612 return (vn(x, 0, y, 0, x.length) === 0) ? true : false;
40613};
40614
40615nacl.setPRNG = function(fn) {
40616 randombytes = fn;
40617};
40618
40619(function() {
40620 // Initialize PRNG if environment provides CSPRNG.
40621 // If not, methods calling randombytes will throw.
40622 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
40623 if (crypto && crypto.getRandomValues) {
40624 // Browsers.
40625 var QUOTA = 65536;
40626 nacl.setPRNG(function(x, n) {
40627 var i, v = new Uint8Array(n);
40628 for (i = 0; i < n; i += QUOTA) {
40629 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
40630 }
40631 for (i = 0; i < n; i++) x[i] = v[i];
40632 cleanup(v);
40633 });
40634 } else if (typeof require !== 'undefined') {
40635 // Node.js.
40636 crypto = require('crypto');
40637 if (crypto && crypto.randomBytes) {
40638 nacl.setPRNG(function(x, n) {
40639 var i, v = crypto.randomBytes(n);
40640 for (i = 0; i < n; i++) x[i] = v[i];
40641 cleanup(v);
40642 });
40643 }
40644 }
40645})();
40646
40647})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
40648
40649},{"crypto":20}],436:[function(require,module,exports){
40650(function (global){
40651
40652/**
40653 * Module exports.
40654 */
40655
40656module.exports = deprecate;
40657
40658/**
40659 * Mark that a method should not be used.
40660 * Returns a modified function which warns once by default.
40661 *
40662 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
40663 *
40664 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
40665 * will throw an Error when invoked.
40666 *
40667 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
40668 * will invoke `console.trace()` instead of `console.error()`.
40669 *
40670 * @param {Function} fn - the function to deprecate
40671 * @param {String} msg - the string to print to the console when `fn` is invoked
40672 * @returns {Function} a new "deprecated" version of `fn`
40673 * @api public
40674 */
40675
40676function deprecate (fn, msg) {
40677 if (config('noDeprecation')) {
40678 return fn;
40679 }
40680
40681 var warned = false;
40682 function deprecated() {
40683 if (!warned) {
40684 if (config('throwDeprecation')) {
40685 throw new Error(msg);
40686 } else if (config('traceDeprecation')) {
40687 console.trace(msg);
40688 } else {
40689 console.warn(msg);
40690 }
40691 warned = true;
40692 }
40693 return fn.apply(this, arguments);
40694 }
40695
40696 return deprecated;
40697}
40698
40699/**
40700 * Checks `localStorage` for boolean values for the given `name`.
40701 *
40702 * @param {String} name
40703 * @returns {Boolean}
40704 * @api private
40705 */
40706
40707function config (name) {
40708 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
40709 try {
40710 if (!global.localStorage) return false;
40711 } catch (_) {
40712 return false;
40713 }
40714 var val = global.localStorage[name];
40715 if (null == val) return false;
40716 return String(val).toLowerCase() === 'true';
40717}
40718
40719}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
40720},{}],437:[function(require,module,exports){
40721module.exports = function isBuffer(arg) {
40722 return arg && typeof arg === 'object'
40723 && typeof arg.copy === 'function'
40724 && typeof arg.fill === 'function'
40725 && typeof arg.readUInt8 === 'function';
40726}
40727},{}],438:[function(require,module,exports){
40728(function (process,global){
40729// Copyright Joyent, Inc. and other Node contributors.
40730//
40731// Permission is hereby granted, free of charge, to any person obtaining a
40732// copy of this software and associated documentation files (the
40733// "Software"), to deal in the Software without restriction, including
40734// without limitation the rights to use, copy, modify, merge, publish,
40735// distribute, sublicense, and/or sell copies of the Software, and to permit
40736// persons to whom the Software is furnished to do so, subject to the
40737// following conditions:
40738//
40739// The above copyright notice and this permission notice shall be included
40740// in all copies or substantial portions of the Software.
40741//
40742// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
40743// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
40744// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
40745// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
40746// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
40747// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
40748// USE OR OTHER DEALINGS IN THE SOFTWARE.
40749
40750var formatRegExp = /%[sdj%]/g;
40751exports.format = function(f) {
40752 if (!isString(f)) {
40753 var objects = [];
40754 for (var i = 0; i < arguments.length; i++) {
40755 objects.push(inspect(arguments[i]));
40756 }
40757 return objects.join(' ');
40758 }
40759
40760 var i = 1;
40761 var args = arguments;
40762 var len = args.length;
40763 var str = String(f).replace(formatRegExp, function(x) {
40764 if (x === '%%') return '%';
40765 if (i >= len) return x;
40766 switch (x) {
40767 case '%s': return String(args[i++]);
40768 case '%d': return Number(args[i++]);
40769 case '%j':
40770 try {
40771 return JSON.stringify(args[i++]);
40772 } catch (_) {
40773 return '[Circular]';
40774 }
40775 default:
40776 return x;
40777 }
40778 });
40779 for (var x = args[i]; i < len; x = args[++i]) {
40780 if (isNull(x) || !isObject(x)) {
40781 str += ' ' + x;
40782 } else {
40783 str += ' ' + inspect(x);
40784 }
40785 }
40786 return str;
40787};
40788
40789
40790// Mark that a method should not be used.
40791// Returns a modified function which warns once by default.
40792// If --no-deprecation is set, then it is a no-op.
40793exports.deprecate = function(fn, msg) {
40794 // Allow for deprecating things in the process of starting up.
40795 if (isUndefined(global.process)) {
40796 return function() {
40797 return exports.deprecate(fn, msg).apply(this, arguments);
40798 };
40799 }
40800
40801 if (process.noDeprecation === true) {
40802 return fn;
40803 }
40804
40805 var warned = false;
40806 function deprecated() {
40807 if (!warned) {
40808 if (process.throwDeprecation) {
40809 throw new Error(msg);
40810 } else if (process.traceDeprecation) {
40811 console.trace(msg);
40812 } else {
40813 console.error(msg);
40814 }
40815 warned = true;
40816 }
40817 return fn.apply(this, arguments);
40818 }
40819
40820 return deprecated;
40821};
40822
40823
40824var debugs = {};
40825var debugEnviron;
40826exports.debuglog = function(set) {
40827 if (isUndefined(debugEnviron))
40828 debugEnviron = process.env.NODE_DEBUG || '';
40829 set = set.toUpperCase();
40830 if (!debugs[set]) {
40831 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
40832 var pid = process.pid;
40833 debugs[set] = function() {
40834 var msg = exports.format.apply(exports, arguments);
40835 console.error('%s %d: %s', set, pid, msg);
40836 };
40837 } else {
40838 debugs[set] = function() {};
40839 }
40840 }
40841 return debugs[set];
40842};
40843
40844
40845/**
40846 * Echos the value of a value. Trys to print the value out
40847 * in the best way possible given the different types.
40848 *
40849 * @param {Object} obj The object to print out.
40850 * @param {Object} opts Optional options object that alters the output.
40851 */
40852/* legacy: obj, showHidden, depth, colors*/
40853function inspect(obj, opts) {
40854 // default options
40855 var ctx = {
40856 seen: [],
40857 stylize: stylizeNoColor
40858 };
40859 // legacy...
40860 if (arguments.length >= 3) ctx.depth = arguments[2];
40861 if (arguments.length >= 4) ctx.colors = arguments[3];
40862 if (isBoolean(opts)) {
40863 // legacy...
40864 ctx.showHidden = opts;
40865 } else if (opts) {
40866 // got an "options" object
40867 exports._extend(ctx, opts);
40868 }
40869 // set default options
40870 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
40871 if (isUndefined(ctx.depth)) ctx.depth = 2;
40872 if (isUndefined(ctx.colors)) ctx.colors = false;
40873 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
40874 if (ctx.colors) ctx.stylize = stylizeWithColor;
40875 return formatValue(ctx, obj, ctx.depth);
40876}
40877exports.inspect = inspect;
40878
40879
40880// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
40881inspect.colors = {
40882 'bold' : [1, 22],
40883 'italic' : [3, 23],
40884 'underline' : [4, 24],
40885 'inverse' : [7, 27],
40886 'white' : [37, 39],
40887 'grey' : [90, 39],
40888 'black' : [30, 39],
40889 'blue' : [34, 39],
40890 'cyan' : [36, 39],
40891 'green' : [32, 39],
40892 'magenta' : [35, 39],
40893 'red' : [31, 39],
40894 'yellow' : [33, 39]
40895};
40896
40897// Don't use 'blue' not visible on cmd.exe
40898inspect.styles = {
40899 'special': 'cyan',
40900 'number': 'yellow',
40901 'boolean': 'yellow',
40902 'undefined': 'grey',
40903 'null': 'bold',
40904 'string': 'green',
40905 'date': 'magenta',
40906 // "name": intentionally not styling
40907 'regexp': 'red'
40908};
40909
40910
40911function stylizeWithColor(str, styleType) {
40912 var style = inspect.styles[styleType];
40913
40914 if (style) {
40915 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
40916 '\u001b[' + inspect.colors[style][1] + 'm';
40917 } else {
40918 return str;
40919 }
40920}
40921
40922
40923function stylizeNoColor(str, styleType) {
40924 return str;
40925}
40926
40927
40928function arrayToHash(array) {
40929 var hash = {};
40930
40931 array.forEach(function(val, idx) {
40932 hash[val] = true;
40933 });
40934
40935 return hash;
40936}
40937
40938
40939function formatValue(ctx, value, recurseTimes) {
40940 // Provide a hook for user-specified inspect functions.
40941 // Check that value is an object with an inspect function on it
40942 if (ctx.customInspect &&
40943 value &&
40944 isFunction(value.inspect) &&
40945 // Filter out the util module, it's inspect function is special
40946 value.inspect !== exports.inspect &&
40947 // Also filter out any prototype objects using the circular check.
40948 !(value.constructor && value.constructor.prototype === value)) {
40949 var ret = value.inspect(recurseTimes, ctx);
40950 if (!isString(ret)) {
40951 ret = formatValue(ctx, ret, recurseTimes);
40952 }
40953 return ret;
40954 }
40955
40956 // Primitive types cannot have properties
40957 var primitive = formatPrimitive(ctx, value);
40958 if (primitive) {
40959 return primitive;
40960 }
40961
40962 // Look up the keys of the object.
40963 var keys = Object.keys(value);
40964 var visibleKeys = arrayToHash(keys);
40965
40966 if (ctx.showHidden) {
40967 keys = Object.getOwnPropertyNames(value);
40968 }
40969
40970 // IE doesn't make error fields non-enumerable
40971 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
40972 if (isError(value)
40973 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
40974 return formatError(value);
40975 }
40976
40977 // Some type of object without properties can be shortcutted.
40978 if (keys.length === 0) {
40979 if (isFunction(value)) {
40980 var name = value.name ? ': ' + value.name : '';
40981 return ctx.stylize('[Function' + name + ']', 'special');
40982 }
40983 if (isRegExp(value)) {
40984 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
40985 }
40986 if (isDate(value)) {
40987 return ctx.stylize(Date.prototype.toString.call(value), 'date');
40988 }
40989 if (isError(value)) {
40990 return formatError(value);
40991 }
40992 }
40993
40994 var base = '', array = false, braces = ['{', '}'];
40995
40996 // Make Array say that they are Array
40997 if (isArray(value)) {
40998 array = true;
40999 braces = ['[', ']'];
41000 }
41001
41002 // Make functions say that they are functions
41003 if (isFunction(value)) {
41004 var n = value.name ? ': ' + value.name : '';
41005 base = ' [Function' + n + ']';
41006 }
41007
41008 // Make RegExps say that they are RegExps
41009 if (isRegExp(value)) {
41010 base = ' ' + RegExp.prototype.toString.call(value);
41011 }
41012
41013 // Make dates with properties first say the date
41014 if (isDate(value)) {
41015 base = ' ' + Date.prototype.toUTCString.call(value);
41016 }
41017
41018 // Make error with message first say the error
41019 if (isError(value)) {
41020 base = ' ' + formatError(value);
41021 }
41022
41023 if (keys.length === 0 && (!array || value.length == 0)) {
41024 return braces[0] + base + braces[1];
41025 }
41026
41027 if (recurseTimes < 0) {
41028 if (isRegExp(value)) {
41029 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
41030 } else {
41031 return ctx.stylize('[Object]', 'special');
41032 }
41033 }
41034
41035 ctx.seen.push(value);
41036
41037 var output;
41038 if (array) {
41039 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
41040 } else {
41041 output = keys.map(function(key) {
41042 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
41043 });
41044 }
41045
41046 ctx.seen.pop();
41047
41048 return reduceToSingleString(output, base, braces);
41049}
41050
41051
41052function formatPrimitive(ctx, value) {
41053 if (isUndefined(value))
41054 return ctx.stylize('undefined', 'undefined');
41055 if (isString(value)) {
41056 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
41057 .replace(/'/g, "\\'")
41058 .replace(/\\"/g, '"') + '\'';
41059 return ctx.stylize(simple, 'string');
41060 }
41061 if (isNumber(value))
41062 return ctx.stylize('' + value, 'number');
41063 if (isBoolean(value))
41064 return ctx.stylize('' + value, 'boolean');
41065 // For some reason typeof null is "object", so special case here.
41066 if (isNull(value))
41067 return ctx.stylize('null', 'null');
41068}
41069
41070
41071function formatError(value) {
41072 return '[' + Error.prototype.toString.call(value) + ']';
41073}
41074
41075
41076function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
41077 var output = [];
41078 for (var i = 0, l = value.length; i < l; ++i) {
41079 if (hasOwnProperty(value, String(i))) {
41080 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
41081 String(i), true));
41082 } else {
41083 output.push('');
41084 }
41085 }
41086 keys.forEach(function(key) {
41087 if (!key.match(/^\d+$/)) {
41088 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
41089 key, true));
41090 }
41091 });
41092 return output;
41093}
41094
41095
41096function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
41097 var name, str, desc;
41098 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
41099 if (desc.get) {
41100 if (desc.set) {
41101 str = ctx.stylize('[Getter/Setter]', 'special');
41102 } else {
41103 str = ctx.stylize('[Getter]', 'special');
41104 }
41105 } else {
41106 if (desc.set) {
41107 str = ctx.stylize('[Setter]', 'special');
41108 }
41109 }
41110 if (!hasOwnProperty(visibleKeys, key)) {
41111 name = '[' + key + ']';
41112 }
41113 if (!str) {
41114 if (ctx.seen.indexOf(desc.value) < 0) {
41115 if (isNull(recurseTimes)) {
41116 str = formatValue(ctx, desc.value, null);
41117 } else {
41118 str = formatValue(ctx, desc.value, recurseTimes - 1);
41119 }
41120 if (str.indexOf('\n') > -1) {
41121 if (array) {
41122 str = str.split('\n').map(function(line) {
41123 return ' ' + line;
41124 }).join('\n').substr(2);
41125 } else {
41126 str = '\n' + str.split('\n').map(function(line) {
41127 return ' ' + line;
41128 }).join('\n');
41129 }
41130 }
41131 } else {
41132 str = ctx.stylize('[Circular]', 'special');
41133 }
41134 }
41135 if (isUndefined(name)) {
41136 if (array && key.match(/^\d+$/)) {
41137 return str;
41138 }
41139 name = JSON.stringify('' + key);
41140 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
41141 name = name.substr(1, name.length - 2);
41142 name = ctx.stylize(name, 'name');
41143 } else {
41144 name = name.replace(/'/g, "\\'")
41145 .replace(/\\"/g, '"')
41146 .replace(/(^"|"$)/g, "'");
41147 name = ctx.stylize(name, 'string');
41148 }
41149 }
41150
41151 return name + ': ' + str;
41152}
41153
41154
41155function reduceToSingleString(output, base, braces) {
41156 var numLinesEst = 0;
41157 var length = output.reduce(function(prev, cur) {
41158 numLinesEst++;
41159 if (cur.indexOf('\n') >= 0) numLinesEst++;
41160 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
41161 }, 0);
41162
41163 if (length > 60) {
41164 return braces[0] +
41165 (base === '' ? '' : base + '\n ') +
41166 ' ' +
41167 output.join(',\n ') +
41168 ' ' +
41169 braces[1];
41170 }
41171
41172 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
41173}
41174
41175
41176// NOTE: These type checking functions intentionally don't use `instanceof`
41177// because it is fragile and can be easily faked with `Object.create()`.
41178function isArray(ar) {
41179 return Array.isArray(ar);
41180}
41181exports.isArray = isArray;
41182
41183function isBoolean(arg) {
41184 return typeof arg === 'boolean';
41185}
41186exports.isBoolean = isBoolean;
41187
41188function isNull(arg) {
41189 return arg === null;
41190}
41191exports.isNull = isNull;
41192
41193function isNullOrUndefined(arg) {
41194 return arg == null;
41195}
41196exports.isNullOrUndefined = isNullOrUndefined;
41197
41198function isNumber(arg) {
41199 return typeof arg === 'number';
41200}
41201exports.isNumber = isNumber;
41202
41203function isString(arg) {
41204 return typeof arg === 'string';
41205}
41206exports.isString = isString;
41207
41208function isSymbol(arg) {
41209 return typeof arg === 'symbol';
41210}
41211exports.isSymbol = isSymbol;
41212
41213function isUndefined(arg) {
41214 return arg === void 0;
41215}
41216exports.isUndefined = isUndefined;
41217
41218function isRegExp(re) {
41219 return isObject(re) && objectToString(re) === '[object RegExp]';
41220}
41221exports.isRegExp = isRegExp;
41222
41223function isObject(arg) {
41224 return typeof arg === 'object' && arg !== null;
41225}
41226exports.isObject = isObject;
41227
41228function isDate(d) {
41229 return isObject(d) && objectToString(d) === '[object Date]';
41230}
41231exports.isDate = isDate;
41232
41233function isError(e) {
41234 return isObject(e) &&
41235 (objectToString(e) === '[object Error]' || e instanceof Error);
41236}
41237exports.isError = isError;
41238
41239function isFunction(arg) {
41240 return typeof arg === 'function';
41241}
41242exports.isFunction = isFunction;
41243
41244function isPrimitive(arg) {
41245 return arg === null ||
41246 typeof arg === 'boolean' ||
41247 typeof arg === 'number' ||
41248 typeof arg === 'string' ||
41249 typeof arg === 'symbol' || // ES6 symbol
41250 typeof arg === 'undefined';
41251}
41252exports.isPrimitive = isPrimitive;
41253
41254exports.isBuffer = require('./support/isBuffer');
41255
41256function objectToString(o) {
41257 return Object.prototype.toString.call(o);
41258}
41259
41260
41261function pad(n) {
41262 return n < 10 ? '0' + n.toString(10) : n.toString(10);
41263}
41264
41265
41266var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
41267 'Oct', 'Nov', 'Dec'];
41268
41269// 26 Feb 16:19:34
41270function timestamp() {
41271 var d = new Date();
41272 var time = [pad(d.getHours()),
41273 pad(d.getMinutes()),
41274 pad(d.getSeconds())].join(':');
41275 return [d.getDate(), months[d.getMonth()], time].join(' ');
41276}
41277
41278
41279// log is just a thin wrapper to console.log that prepends a timestamp
41280exports.log = function() {
41281 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
41282};
41283
41284
41285/**
41286 * Inherit the prototype methods from one constructor into another.
41287 *
41288 * The Function.prototype.inherits from lang.js rewritten as a standalone
41289 * function (not on Function.prototype). NOTE: If this file is to be loaded
41290 * during bootstrapping this function needs to be rewritten using some native
41291 * functions as prototype setup using normal JavaScript does not work as
41292 * expected during bootstrapping (see mirror.js in r114903).
41293 *
41294 * @param {function} ctor Constructor function which needs to inherit the
41295 * prototype.
41296 * @param {function} superCtor Constructor function to inherit prototype from.
41297 */
41298exports.inherits = require('inherits');
41299
41300exports._extend = function(origin, add) {
41301 // Don't do anything if add isn't an object
41302 if (!add || !isObject(add)) return origin;
41303
41304 var keys = Object.keys(add);
41305 var i = keys.length;
41306 while (i--) {
41307 origin[keys[i]] = add[keys[i]];
41308 }
41309 return origin;
41310};
41311
41312function hasOwnProperty(obj, prop) {
41313 return Object.prototype.hasOwnProperty.call(obj, prop);
41314}
41315
41316}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
41317},{"./support/isBuffer":437,"_process":369,"inherits":116}],439:[function(require,module,exports){
41318var indexOf = function (xs, item) {
41319 if (xs.indexOf) return xs.indexOf(item);
41320 else for (var i = 0; i < xs.length; i++) {
41321 if (xs[i] === item) return i;
41322 }
41323 return -1;
41324};
41325var Object_keys = function (obj) {
41326 if (Object.keys) return Object.keys(obj)
41327 else {
41328 var res = [];
41329 for (var key in obj) res.push(key)
41330 return res;
41331 }
41332};
41333
41334var forEach = function (xs, fn) {
41335 if (xs.forEach) return xs.forEach(fn)
41336 else for (var i = 0; i < xs.length; i++) {
41337 fn(xs[i], i, xs);
41338 }
41339};
41340
41341var defineProp = (function() {
41342 try {
41343 Object.defineProperty({}, '_', {});
41344 return function(obj, name, value) {
41345 Object.defineProperty(obj, name, {
41346 writable: true,
41347 enumerable: false,
41348 configurable: true,
41349 value: value
41350 })
41351 };
41352 } catch(e) {
41353 return function(obj, name, value) {
41354 obj[name] = value;
41355 };
41356 }
41357}());
41358
41359var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
41360'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
41361'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
41362'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
41363'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
41364
41365function Context() {}
41366Context.prototype = {};
41367
41368var Script = exports.Script = function NodeScript (code) {
41369 if (!(this instanceof Script)) return new Script(code);
41370 this.code = code;
41371};
41372
41373Script.prototype.runInContext = function (context) {
41374 if (!(context instanceof Context)) {
41375 throw new TypeError("needs a 'context' argument.");
41376 }
41377
41378 var iframe = document.createElement('iframe');
41379 if (!iframe.style) iframe.style = {};
41380 iframe.style.display = 'none';
41381
41382 document.body.appendChild(iframe);
41383
41384 var win = iframe.contentWindow;
41385 var wEval = win.eval, wExecScript = win.execScript;
41386
41387 if (!wEval && wExecScript) {
41388 // win.eval() magically appears when this is called in IE:
41389 wExecScript.call(win, 'null');
41390 wEval = win.eval;
41391 }
41392
41393 forEach(Object_keys(context), function (key) {
41394 win[key] = context[key];
41395 });
41396 forEach(globals, function (key) {
41397 if (context[key]) {
41398 win[key] = context[key];
41399 }
41400 });
41401
41402 var winKeys = Object_keys(win);
41403
41404 var res = wEval.call(win, this.code);
41405
41406 forEach(Object_keys(win), function (key) {
41407 // Avoid copying circular objects like `top` and `window` by only
41408 // updating existing context properties or new properties in the `win`
41409 // that was only introduced after the eval.
41410 if (key in context || indexOf(winKeys, key) === -1) {
41411 context[key] = win[key];
41412 }
41413 });
41414
41415 forEach(globals, function (key) {
41416 if (!(key in context)) {
41417 defineProp(context, key, win[key]);
41418 }
41419 });
41420
41421 document.body.removeChild(iframe);
41422
41423 return res;
41424};
41425
41426Script.prototype.runInThisContext = function () {
41427 return eval(this.code); // maybe...
41428};
41429
41430Script.prototype.runInNewContext = function (context) {
41431 var ctx = Script.createContext(context);
41432 var res = this.runInContext(ctx);
41433
41434 if (context) {
41435 forEach(Object_keys(ctx), function (key) {
41436 context[key] = ctx[key];
41437 });
41438 }
41439
41440 return res;
41441};
41442
41443forEach(Object_keys(Script.prototype), function (name) {
41444 exports[name] = Script[name] = function (code) {
41445 var s = Script(code);
41446 return s[name].apply(s, [].slice.call(arguments, 1));
41447 };
41448});
41449
41450exports.isContext = function (context) {
41451 return context instanceof Context;
41452};
41453
41454exports.createScript = function (code) {
41455 return exports.Script(code);
41456};
41457
41458exports.createContext = Script.createContext = function (context) {
41459 var copy = new Context();
41460 if(typeof context === 'object') {
41461 forEach(Object_keys(context), function (key) {
41462 copy[key] = context[key];
41463 });
41464 }
41465 return copy;
41466};
41467
41468},{}],440:[function(require,module,exports){
41469(function (Buffer){
41470const createHmac = require('create-hmac');
41471const StellarBase = require('stellar-base');
41472
41473window.stellarUtil = {
41474
41475 HARDENED_OFFSET: 0x80000000,
41476 ED25519_CURVE: 'ed25519 seed',
41477
41478 replaceDerive: (val) => val.replace("'", ''),
41479
41480 getMasterKeyFromSeed: function (seed) {
41481 const hmac = createHmac('sha512', this.ED25519_CURVE);
41482 const I = hmac.update(Buffer.from(seed, 'hex')).digest();
41483 const IL = I.slice(0, 32);
41484 const IR = I.slice(32);
41485 return {
41486 key: IL,
41487 chainCode: IR,
41488 };
41489 },
41490
41491 CKDPriv: ({key, chainCode}, index) => {
41492 const indexBuffer = Buffer.allocUnsafe(4);
41493 indexBuffer.writeUInt32BE(index, 0);
41494 const data = Buffer.concat([Buffer.alloc(1, 0), key, indexBuffer]);
41495 const I = createHmac('sha512', chainCode)
41496 .update(data)
41497 .digest();
41498 const IL = I.slice(0, 32);
41499 const IR = I.slice(32);
41500 return {
41501 key: IL,
41502 chainCode: IR,
41503 };
41504 },
41505
41506 derivePath: function (path, seed) {
41507
41508 const {key, chainCode} = this.getMasterKeyFromSeed(seed);
41509 const segments = path
41510 .split('/')
41511 .slice(1)
41512 .map(this.replaceDerive)
41513 .map(el => parseInt(el, 10));
41514 const result = segments.reduce((parentKeys, segment) => this.CKDPriv(parentKeys, segment + this.HARDENED_OFFSET), {key, chainCode});
41515 return StellarBase.Keypair.fromRawEd25519Seed(result.key);
41516 }
41517}
41518
41519}).call(this,require("buffer").Buffer)
41520},{"buffer":49,"create-hmac":69,"stellar-base":407}]},{},[440]);