UNPKG

797 kBJavaScriptView Raw
1var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
3function commonjsRequire () {
4 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
5}
6
7function unwrapExports (x) {
8 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9}
10
11function createCommonjsModule(fn, module) {
12 return module = { exports: {} }, fn(module, module.exports), module.exports;
13}
14
15function getCjsExportFromNamespace (n) {
16 return n && n['default'] || n;
17}
18
19var _nodeResolve_empty = {};
20
21var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
22 'default': _nodeResolve_empty
23});
24
25var require$$0 = getCjsExportFromNamespace(_nodeResolve_empty$1);
26
27var bn = createCommonjsModule(function (module) {
28(function (module, exports) {
29 'use strict';
30
31 // Utils
32 function assert (val, msg) {
33 if (!val) throw new Error(msg || 'Assertion failed');
34 }
35
36 // Could use `inherits` module, but don't want to move from single file
37 // architecture yet.
38 function inherits (ctor, superCtor) {
39 ctor.super_ = superCtor;
40 var TempCtor = function () {};
41 TempCtor.prototype = superCtor.prototype;
42 ctor.prototype = new TempCtor();
43 ctor.prototype.constructor = ctor;
44 }
45
46 // BN
47
48 function BN (number, base, endian) {
49 if (BN.isBN(number)) {
50 return number;
51 }
52
53 this.negative = 0;
54 this.words = null;
55 this.length = 0;
56
57 // Reduction context
58 this.red = null;
59
60 if (number !== null) {
61 if (base === 'le' || base === 'be') {
62 endian = base;
63 base = 10;
64 }
65
66 this._init(number || 0, base || 10, endian || 'be');
67 }
68 }
69 if (typeof module === 'object') {
70 module.exports = BN;
71 } else {
72 exports.BN = BN;
73 }
74
75 BN.BN = BN;
76 BN.wordSize = 26;
77
78 var Buffer;
79 try {
80 Buffer = require$$0.Buffer;
81 } catch (e) {
82 }
83
84 BN.isBN = function isBN (num) {
85 if (num instanceof BN) {
86 return true;
87 }
88
89 return num !== null && typeof num === 'object' &&
90 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
91 };
92
93 BN.max = function max (left, right) {
94 if (left.cmp(right) > 0) return left;
95 return right;
96 };
97
98 BN.min = function min (left, right) {
99 if (left.cmp(right) < 0) return left;
100 return right;
101 };
102
103 BN.prototype._init = function init (number, base, endian) {
104 if (typeof number === 'number') {
105 return this._initNumber(number, base, endian);
106 }
107
108 if (typeof number === 'object') {
109 return this._initArray(number, base, endian);
110 }
111
112 if (base === 'hex') {
113 base = 16;
114 }
115 assert(base === (base | 0) && base >= 2 && base <= 36);
116
117 number = number.toString().replace(/\s+/g, '');
118 var start = 0;
119 if (number[0] === '-') {
120 start++;
121 }
122
123 if (base === 16) {
124 this._parseHex(number, start);
125 } else {
126 this._parseBase(number, base, start);
127 }
128
129 if (number[0] === '-') {
130 this.negative = 1;
131 }
132
133 this.strip();
134
135 if (endian !== 'le') return;
136
137 this._initArray(this.toArray(), base, endian);
138 };
139
140 BN.prototype._initNumber = function _initNumber (number, base, endian) {
141 if (number < 0) {
142 this.negative = 1;
143 number = -number;
144 }
145 if (number < 0x4000000) {
146 this.words = [ number & 0x3ffffff ];
147 this.length = 1;
148 } else if (number < 0x10000000000000) {
149 this.words = [
150 number & 0x3ffffff,
151 (number / 0x4000000) & 0x3ffffff
152 ];
153 this.length = 2;
154 } else {
155 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
156 this.words = [
157 number & 0x3ffffff,
158 (number / 0x4000000) & 0x3ffffff,
159 1
160 ];
161 this.length = 3;
162 }
163
164 if (endian !== 'le') return;
165
166 // Reverse the bytes
167 this._initArray(this.toArray(), base, endian);
168 };
169
170 BN.prototype._initArray = function _initArray (number, base, endian) {
171 // Perhaps a Uint8Array
172 assert(typeof number.length === 'number');
173 if (number.length <= 0) {
174 this.words = [ 0 ];
175 this.length = 1;
176 return this;
177 }
178
179 this.length = Math.ceil(number.length / 3);
180 this.words = new Array(this.length);
181 for (var i = 0; i < this.length; i++) {
182 this.words[i] = 0;
183 }
184
185 var j, w;
186 var off = 0;
187 if (endian === 'be') {
188 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
189 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
190 this.words[j] |= (w << off) & 0x3ffffff;
191 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
192 off += 24;
193 if (off >= 26) {
194 off -= 26;
195 j++;
196 }
197 }
198 } else if (endian === 'le') {
199 for (i = 0, j = 0; i < number.length; i += 3) {
200 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
201 this.words[j] |= (w << off) & 0x3ffffff;
202 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
203 off += 24;
204 if (off >= 26) {
205 off -= 26;
206 j++;
207 }
208 }
209 }
210 return this.strip();
211 };
212
213 function parseHex (str, start, end) {
214 var r = 0;
215 var len = Math.min(str.length, end);
216 for (var i = start; i < len; i++) {
217 var c = str.charCodeAt(i) - 48;
218
219 r <<= 4;
220
221 // 'a' - 'f'
222 if (c >= 49 && c <= 54) {
223 r |= c - 49 + 0xa;
224
225 // 'A' - 'F'
226 } else if (c >= 17 && c <= 22) {
227 r |= c - 17 + 0xa;
228
229 // '0' - '9'
230 } else {
231 r |= c & 0xf;
232 }
233 }
234 return r;
235 }
236
237 BN.prototype._parseHex = function _parseHex (number, start) {
238 // Create possibly bigger array to ensure that it fits the number
239 this.length = Math.ceil((number.length - start) / 6);
240 this.words = new Array(this.length);
241 for (var i = 0; i < this.length; i++) {
242 this.words[i] = 0;
243 }
244
245 var j, w;
246 // Scan 24-bit chunks and add them to the number
247 var off = 0;
248 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
249 w = parseHex(number, i, i + 6);
250 this.words[j] |= (w << off) & 0x3ffffff;
251 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
252 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
253 off += 24;
254 if (off >= 26) {
255 off -= 26;
256 j++;
257 }
258 }
259 if (i + 6 !== start) {
260 w = parseHex(number, start, i + 6);
261 this.words[j] |= (w << off) & 0x3ffffff;
262 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
263 }
264 this.strip();
265 };
266
267 function parseBase (str, start, end, mul) {
268 var r = 0;
269 var len = Math.min(str.length, end);
270 for (var i = start; i < len; i++) {
271 var c = str.charCodeAt(i) - 48;
272
273 r *= mul;
274
275 // 'a'
276 if (c >= 49) {
277 r += c - 49 + 0xa;
278
279 // 'A'
280 } else if (c >= 17) {
281 r += c - 17 + 0xa;
282
283 // '0' - '9'
284 } else {
285 r += c;
286 }
287 }
288 return r;
289 }
290
291 BN.prototype._parseBase = function _parseBase (number, base, start) {
292 // Initialize as zero
293 this.words = [ 0 ];
294 this.length = 1;
295
296 // Find length of limb in base
297 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
298 limbLen++;
299 }
300 limbLen--;
301 limbPow = (limbPow / base) | 0;
302
303 var total = number.length - start;
304 var mod = total % limbLen;
305 var end = Math.min(total, total - mod) + start;
306
307 var word = 0;
308 for (var i = start; i < end; i += limbLen) {
309 word = parseBase(number, i, i + limbLen, base);
310
311 this.imuln(limbPow);
312 if (this.words[0] + word < 0x4000000) {
313 this.words[0] += word;
314 } else {
315 this._iaddn(word);
316 }
317 }
318
319 if (mod !== 0) {
320 var pow = 1;
321 word = parseBase(number, i, number.length, base);
322
323 for (i = 0; i < mod; i++) {
324 pow *= base;
325 }
326
327 this.imuln(pow);
328 if (this.words[0] + word < 0x4000000) {
329 this.words[0] += word;
330 } else {
331 this._iaddn(word);
332 }
333 }
334 };
335
336 BN.prototype.copy = function copy (dest) {
337 dest.words = new Array(this.length);
338 for (var i = 0; i < this.length; i++) {
339 dest.words[i] = this.words[i];
340 }
341 dest.length = this.length;
342 dest.negative = this.negative;
343 dest.red = this.red;
344 };
345
346 BN.prototype.clone = function clone () {
347 var r = new BN(null);
348 this.copy(r);
349 return r;
350 };
351
352 BN.prototype._expand = function _expand (size) {
353 while (this.length < size) {
354 this.words[this.length++] = 0;
355 }
356 return this;
357 };
358
359 // Remove leading `0` from `this`
360 BN.prototype.strip = function strip () {
361 while (this.length > 1 && this.words[this.length - 1] === 0) {
362 this.length--;
363 }
364 return this._normSign();
365 };
366
367 BN.prototype._normSign = function _normSign () {
368 // -0 = 0
369 if (this.length === 1 && this.words[0] === 0) {
370 this.negative = 0;
371 }
372 return this;
373 };
374
375 BN.prototype.inspect = function inspect () {
376 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
377 };
378
379 /*
380
381 var zeros = [];
382 var groupSizes = [];
383 var groupBases = [];
384
385 var s = '';
386 var i = -1;
387 while (++i < BN.wordSize) {
388 zeros[i] = s;
389 s += '0';
390 }
391 groupSizes[0] = 0;
392 groupSizes[1] = 0;
393 groupBases[0] = 0;
394 groupBases[1] = 0;
395 var base = 2 - 1;
396 while (++base < 36 + 1) {
397 var groupSize = 0;
398 var groupBase = 1;
399 while (groupBase < (1 << BN.wordSize) / base) {
400 groupBase *= base;
401 groupSize += 1;
402 }
403 groupSizes[base] = groupSize;
404 groupBases[base] = groupBase;
405 }
406
407 */
408
409 var zeros = [
410 '',
411 '0',
412 '00',
413 '000',
414 '0000',
415 '00000',
416 '000000',
417 '0000000',
418 '00000000',
419 '000000000',
420 '0000000000',
421 '00000000000',
422 '000000000000',
423 '0000000000000',
424 '00000000000000',
425 '000000000000000',
426 '0000000000000000',
427 '00000000000000000',
428 '000000000000000000',
429 '0000000000000000000',
430 '00000000000000000000',
431 '000000000000000000000',
432 '0000000000000000000000',
433 '00000000000000000000000',
434 '000000000000000000000000',
435 '0000000000000000000000000'
436 ];
437
438 var groupSizes = [
439 0, 0,
440 25, 16, 12, 11, 10, 9, 8,
441 8, 7, 7, 7, 7, 6, 6,
442 6, 6, 6, 6, 6, 5, 5,
443 5, 5, 5, 5, 5, 5, 5,
444 5, 5, 5, 5, 5, 5, 5
445 ];
446
447 var groupBases = [
448 0, 0,
449 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
450 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
451 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
452 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
453 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
454 ];
455
456 BN.prototype.toString = function toString (base, padding) {
457 base = base || 10;
458 padding = padding | 0 || 1;
459
460 var out;
461 if (base === 16 || base === 'hex') {
462 out = '';
463 var off = 0;
464 var carry = 0;
465 for (var i = 0; i < this.length; i++) {
466 var w = this.words[i];
467 var word = (((w << off) | carry) & 0xffffff).toString(16);
468 carry = (w >>> (24 - off)) & 0xffffff;
469 if (carry !== 0 || i !== this.length - 1) {
470 out = zeros[6 - word.length] + word + out;
471 } else {
472 out = word + out;
473 }
474 off += 2;
475 if (off >= 26) {
476 off -= 26;
477 i--;
478 }
479 }
480 if (carry !== 0) {
481 out = carry.toString(16) + out;
482 }
483 while (out.length % padding !== 0) {
484 out = '0' + out;
485 }
486 if (this.negative !== 0) {
487 out = '-' + out;
488 }
489 return out;
490 }
491
492 if (base === (base | 0) && base >= 2 && base <= 36) {
493 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
494 var groupSize = groupSizes[base];
495 // var groupBase = Math.pow(base, groupSize);
496 var groupBase = groupBases[base];
497 out = '';
498 var c = this.clone();
499 c.negative = 0;
500 while (!c.isZero()) {
501 var r = c.modn(groupBase).toString(base);
502 c = c.idivn(groupBase);
503
504 if (!c.isZero()) {
505 out = zeros[groupSize - r.length] + r + out;
506 } else {
507 out = r + out;
508 }
509 }
510 if (this.isZero()) {
511 out = '0' + out;
512 }
513 while (out.length % padding !== 0) {
514 out = '0' + out;
515 }
516 if (this.negative !== 0) {
517 out = '-' + out;
518 }
519 return out;
520 }
521
522 assert(false, 'Base should be between 2 and 36');
523 };
524
525 BN.prototype.toNumber = function toNumber () {
526 var ret = this.words[0];
527 if (this.length === 2) {
528 ret += this.words[1] * 0x4000000;
529 } else if (this.length === 3 && this.words[2] === 0x01) {
530 // NOTE: at this stage it is known that the top bit is set
531 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
532 } else if (this.length > 2) {
533 assert(false, 'Number can only safely store up to 53 bits');
534 }
535 return (this.negative !== 0) ? -ret : ret;
536 };
537
538 BN.prototype.toJSON = function toJSON () {
539 return this.toString(16);
540 };
541
542 BN.prototype.toBuffer = function toBuffer (endian, length) {
543 assert(typeof Buffer !== 'undefined');
544 return this.toArrayLike(Buffer, endian, length);
545 };
546
547 BN.prototype.toArray = function toArray (endian, length) {
548 return this.toArrayLike(Array, endian, length);
549 };
550
551 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
552 var byteLength = this.byteLength();
553 var reqLength = length || Math.max(1, byteLength);
554 assert(byteLength <= reqLength, 'byte array longer than desired length');
555 assert(reqLength > 0, 'Requested array length <= 0');
556
557 this.strip();
558 var littleEndian = endian === 'le';
559 var res = new ArrayType(reqLength);
560
561 var b, i;
562 var q = this.clone();
563 if (!littleEndian) {
564 // Assume big-endian
565 for (i = 0; i < reqLength - byteLength; i++) {
566 res[i] = 0;
567 }
568
569 for (i = 0; !q.isZero(); i++) {
570 b = q.andln(0xff);
571 q.iushrn(8);
572
573 res[reqLength - i - 1] = b;
574 }
575 } else {
576 for (i = 0; !q.isZero(); i++) {
577 b = q.andln(0xff);
578 q.iushrn(8);
579
580 res[i] = b;
581 }
582
583 for (; i < reqLength; i++) {
584 res[i] = 0;
585 }
586 }
587
588 return res;
589 };
590
591 if (Math.clz32) {
592 BN.prototype._countBits = function _countBits (w) {
593 return 32 - Math.clz32(w);
594 };
595 } else {
596 BN.prototype._countBits = function _countBits (w) {
597 var t = w;
598 var r = 0;
599 if (t >= 0x1000) {
600 r += 13;
601 t >>>= 13;
602 }
603 if (t >= 0x40) {
604 r += 7;
605 t >>>= 7;
606 }
607 if (t >= 0x8) {
608 r += 4;
609 t >>>= 4;
610 }
611 if (t >= 0x02) {
612 r += 2;
613 t >>>= 2;
614 }
615 return r + t;
616 };
617 }
618
619 BN.prototype._zeroBits = function _zeroBits (w) {
620 // Short-cut
621 if (w === 0) return 26;
622
623 var t = w;
624 var r = 0;
625 if ((t & 0x1fff) === 0) {
626 r += 13;
627 t >>>= 13;
628 }
629 if ((t & 0x7f) === 0) {
630 r += 7;
631 t >>>= 7;
632 }
633 if ((t & 0xf) === 0) {
634 r += 4;
635 t >>>= 4;
636 }
637 if ((t & 0x3) === 0) {
638 r += 2;
639 t >>>= 2;
640 }
641 if ((t & 0x1) === 0) {
642 r++;
643 }
644 return r;
645 };
646
647 // Return number of used bits in a BN
648 BN.prototype.bitLength = function bitLength () {
649 var w = this.words[this.length - 1];
650 var hi = this._countBits(w);
651 return (this.length - 1) * 26 + hi;
652 };
653
654 function toBitArray (num) {
655 var w = new Array(num.bitLength());
656
657 for (var bit = 0; bit < w.length; bit++) {
658 var off = (bit / 26) | 0;
659 var wbit = bit % 26;
660
661 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
662 }
663
664 return w;
665 }
666
667 // Number of trailing zero bits
668 BN.prototype.zeroBits = function zeroBits () {
669 if (this.isZero()) return 0;
670
671 var r = 0;
672 for (var i = 0; i < this.length; i++) {
673 var b = this._zeroBits(this.words[i]);
674 r += b;
675 if (b !== 26) break;
676 }
677 return r;
678 };
679
680 BN.prototype.byteLength = function byteLength () {
681 return Math.ceil(this.bitLength() / 8);
682 };
683
684 BN.prototype.toTwos = function toTwos (width) {
685 if (this.negative !== 0) {
686 return this.abs().inotn(width).iaddn(1);
687 }
688 return this.clone();
689 };
690
691 BN.prototype.fromTwos = function fromTwos (width) {
692 if (this.testn(width - 1)) {
693 return this.notn(width).iaddn(1).ineg();
694 }
695 return this.clone();
696 };
697
698 BN.prototype.isNeg = function isNeg () {
699 return this.negative !== 0;
700 };
701
702 // Return negative clone of `this`
703 BN.prototype.neg = function neg () {
704 return this.clone().ineg();
705 };
706
707 BN.prototype.ineg = function ineg () {
708 if (!this.isZero()) {
709 this.negative ^= 1;
710 }
711
712 return this;
713 };
714
715 // Or `num` with `this` in-place
716 BN.prototype.iuor = function iuor (num) {
717 while (this.length < num.length) {
718 this.words[this.length++] = 0;
719 }
720
721 for (var i = 0; i < num.length; i++) {
722 this.words[i] = this.words[i] | num.words[i];
723 }
724
725 return this.strip();
726 };
727
728 BN.prototype.ior = function ior (num) {
729 assert((this.negative | num.negative) === 0);
730 return this.iuor(num);
731 };
732
733 // Or `num` with `this`
734 BN.prototype.or = function or (num) {
735 if (this.length > num.length) return this.clone().ior(num);
736 return num.clone().ior(this);
737 };
738
739 BN.prototype.uor = function uor (num) {
740 if (this.length > num.length) return this.clone().iuor(num);
741 return num.clone().iuor(this);
742 };
743
744 // And `num` with `this` in-place
745 BN.prototype.iuand = function iuand (num) {
746 // b = min-length(num, this)
747 var b;
748 if (this.length > num.length) {
749 b = num;
750 } else {
751 b = this;
752 }
753
754 for (var i = 0; i < b.length; i++) {
755 this.words[i] = this.words[i] & num.words[i];
756 }
757
758 this.length = b.length;
759
760 return this.strip();
761 };
762
763 BN.prototype.iand = function iand (num) {
764 assert((this.negative | num.negative) === 0);
765 return this.iuand(num);
766 };
767
768 // And `num` with `this`
769 BN.prototype.and = function and (num) {
770 if (this.length > num.length) return this.clone().iand(num);
771 return num.clone().iand(this);
772 };
773
774 BN.prototype.uand = function uand (num) {
775 if (this.length > num.length) return this.clone().iuand(num);
776 return num.clone().iuand(this);
777 };
778
779 // Xor `num` with `this` in-place
780 BN.prototype.iuxor = function iuxor (num) {
781 // a.length > b.length
782 var a;
783 var b;
784 if (this.length > num.length) {
785 a = this;
786 b = num;
787 } else {
788 a = num;
789 b = this;
790 }
791
792 for (var i = 0; i < b.length; i++) {
793 this.words[i] = a.words[i] ^ b.words[i];
794 }
795
796 if (this !== a) {
797 for (; i < a.length; i++) {
798 this.words[i] = a.words[i];
799 }
800 }
801
802 this.length = a.length;
803
804 return this.strip();
805 };
806
807 BN.prototype.ixor = function ixor (num) {
808 assert((this.negative | num.negative) === 0);
809 return this.iuxor(num);
810 };
811
812 // Xor `num` with `this`
813 BN.prototype.xor = function xor (num) {
814 if (this.length > num.length) return this.clone().ixor(num);
815 return num.clone().ixor(this);
816 };
817
818 BN.prototype.uxor = function uxor (num) {
819 if (this.length > num.length) return this.clone().iuxor(num);
820 return num.clone().iuxor(this);
821 };
822
823 // Not ``this`` with ``width`` bitwidth
824 BN.prototype.inotn = function inotn (width) {
825 assert(typeof width === 'number' && width >= 0);
826
827 var bytesNeeded = Math.ceil(width / 26) | 0;
828 var bitsLeft = width % 26;
829
830 // Extend the buffer with leading zeroes
831 this._expand(bytesNeeded);
832
833 if (bitsLeft > 0) {
834 bytesNeeded--;
835 }
836
837 // Handle complete words
838 for (var i = 0; i < bytesNeeded; i++) {
839 this.words[i] = ~this.words[i] & 0x3ffffff;
840 }
841
842 // Handle the residue
843 if (bitsLeft > 0) {
844 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
845 }
846
847 // And remove leading zeroes
848 return this.strip();
849 };
850
851 BN.prototype.notn = function notn (width) {
852 return this.clone().inotn(width);
853 };
854
855 // Set `bit` of `this`
856 BN.prototype.setn = function setn (bit, val) {
857 assert(typeof bit === 'number' && bit >= 0);
858
859 var off = (bit / 26) | 0;
860 var wbit = bit % 26;
861
862 this._expand(off + 1);
863
864 if (val) {
865 this.words[off] = this.words[off] | (1 << wbit);
866 } else {
867 this.words[off] = this.words[off] & ~(1 << wbit);
868 }
869
870 return this.strip();
871 };
872
873 // Add `num` to `this` in-place
874 BN.prototype.iadd = function iadd (num) {
875 var r;
876
877 // negative + positive
878 if (this.negative !== 0 && num.negative === 0) {
879 this.negative = 0;
880 r = this.isub(num);
881 this.negative ^= 1;
882 return this._normSign();
883
884 // positive + negative
885 } else if (this.negative === 0 && num.negative !== 0) {
886 num.negative = 0;
887 r = this.isub(num);
888 num.negative = 1;
889 return r._normSign();
890 }
891
892 // a.length > b.length
893 var a, b;
894 if (this.length > num.length) {
895 a = this;
896 b = num;
897 } else {
898 a = num;
899 b = this;
900 }
901
902 var carry = 0;
903 for (var i = 0; i < b.length; i++) {
904 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
905 this.words[i] = r & 0x3ffffff;
906 carry = r >>> 26;
907 }
908 for (; carry !== 0 && i < a.length; i++) {
909 r = (a.words[i] | 0) + carry;
910 this.words[i] = r & 0x3ffffff;
911 carry = r >>> 26;
912 }
913
914 this.length = a.length;
915 if (carry !== 0) {
916 this.words[this.length] = carry;
917 this.length++;
918 // Copy the rest of the words
919 } else if (a !== this) {
920 for (; i < a.length; i++) {
921 this.words[i] = a.words[i];
922 }
923 }
924
925 return this;
926 };
927
928 // Add `num` to `this`
929 BN.prototype.add = function add (num) {
930 var res;
931 if (num.negative !== 0 && this.negative === 0) {
932 num.negative = 0;
933 res = this.sub(num);
934 num.negative ^= 1;
935 return res;
936 } else if (num.negative === 0 && this.negative !== 0) {
937 this.negative = 0;
938 res = num.sub(this);
939 this.negative = 1;
940 return res;
941 }
942
943 if (this.length > num.length) return this.clone().iadd(num);
944
945 return num.clone().iadd(this);
946 };
947
948 // Subtract `num` from `this` in-place
949 BN.prototype.isub = function isub (num) {
950 // this - (-num) = this + num
951 if (num.negative !== 0) {
952 num.negative = 0;
953 var r = this.iadd(num);
954 num.negative = 1;
955 return r._normSign();
956
957 // -this - num = -(this + num)
958 } else if (this.negative !== 0) {
959 this.negative = 0;
960 this.iadd(num);
961 this.negative = 1;
962 return this._normSign();
963 }
964
965 // At this point both numbers are positive
966 var cmp = this.cmp(num);
967
968 // Optimization - zeroify
969 if (cmp === 0) {
970 this.negative = 0;
971 this.length = 1;
972 this.words[0] = 0;
973 return this;
974 }
975
976 // a > b
977 var a, b;
978 if (cmp > 0) {
979 a = this;
980 b = num;
981 } else {
982 a = num;
983 b = this;
984 }
985
986 var carry = 0;
987 for (var i = 0; i < b.length; i++) {
988 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
989 carry = r >> 26;
990 this.words[i] = r & 0x3ffffff;
991 }
992 for (; carry !== 0 && i < a.length; i++) {
993 r = (a.words[i] | 0) + carry;
994 carry = r >> 26;
995 this.words[i] = r & 0x3ffffff;
996 }
997
998 // Copy rest of the words
999 if (carry === 0 && i < a.length && a !== this) {
1000 for (; i < a.length; i++) {
1001 this.words[i] = a.words[i];
1002 }
1003 }
1004
1005 this.length = Math.max(this.length, i);
1006
1007 if (a !== this) {
1008 this.negative = 1;
1009 }
1010
1011 return this.strip();
1012 };
1013
1014 // Subtract `num` from `this`
1015 BN.prototype.sub = function sub (num) {
1016 return this.clone().isub(num);
1017 };
1018
1019 function smallMulTo (self, num, out) {
1020 out.negative = num.negative ^ self.negative;
1021 var len = (self.length + num.length) | 0;
1022 out.length = len;
1023 len = (len - 1) | 0;
1024
1025 // Peel one iteration (compiler can't do it, because of code complexity)
1026 var a = self.words[0] | 0;
1027 var b = num.words[0] | 0;
1028 var r = a * b;
1029
1030 var lo = r & 0x3ffffff;
1031 var carry = (r / 0x4000000) | 0;
1032 out.words[0] = lo;
1033
1034 for (var k = 1; k < len; k++) {
1035 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
1036 // note that ncarry could be >= 0x3ffffff
1037 var ncarry = carry >>> 26;
1038 var rword = carry & 0x3ffffff;
1039 var maxJ = Math.min(k, num.length - 1);
1040 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
1041 var i = (k - j) | 0;
1042 a = self.words[i] | 0;
1043 b = num.words[j] | 0;
1044 r = a * b + rword;
1045 ncarry += (r / 0x4000000) | 0;
1046 rword = r & 0x3ffffff;
1047 }
1048 out.words[k] = rword | 0;
1049 carry = ncarry | 0;
1050 }
1051 if (carry !== 0) {
1052 out.words[k] = carry | 0;
1053 } else {
1054 out.length--;
1055 }
1056
1057 return out.strip();
1058 }
1059
1060 // TODO(indutny): it may be reasonable to omit it for users who don't need
1061 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
1062 // multiplication (like elliptic secp256k1).
1063 var comb10MulTo = function comb10MulTo (self, num, out) {
1064 var a = self.words;
1065 var b = num.words;
1066 var o = out.words;
1067 var c = 0;
1068 var lo;
1069 var mid;
1070 var hi;
1071 var a0 = a[0] | 0;
1072 var al0 = a0 & 0x1fff;
1073 var ah0 = a0 >>> 13;
1074 var a1 = a[1] | 0;
1075 var al1 = a1 & 0x1fff;
1076 var ah1 = a1 >>> 13;
1077 var a2 = a[2] | 0;
1078 var al2 = a2 & 0x1fff;
1079 var ah2 = a2 >>> 13;
1080 var a3 = a[3] | 0;
1081 var al3 = a3 & 0x1fff;
1082 var ah3 = a3 >>> 13;
1083 var a4 = a[4] | 0;
1084 var al4 = a4 & 0x1fff;
1085 var ah4 = a4 >>> 13;
1086 var a5 = a[5] | 0;
1087 var al5 = a5 & 0x1fff;
1088 var ah5 = a5 >>> 13;
1089 var a6 = a[6] | 0;
1090 var al6 = a6 & 0x1fff;
1091 var ah6 = a6 >>> 13;
1092 var a7 = a[7] | 0;
1093 var al7 = a7 & 0x1fff;
1094 var ah7 = a7 >>> 13;
1095 var a8 = a[8] | 0;
1096 var al8 = a8 & 0x1fff;
1097 var ah8 = a8 >>> 13;
1098 var a9 = a[9] | 0;
1099 var al9 = a9 & 0x1fff;
1100 var ah9 = a9 >>> 13;
1101 var b0 = b[0] | 0;
1102 var bl0 = b0 & 0x1fff;
1103 var bh0 = b0 >>> 13;
1104 var b1 = b[1] | 0;
1105 var bl1 = b1 & 0x1fff;
1106 var bh1 = b1 >>> 13;
1107 var b2 = b[2] | 0;
1108 var bl2 = b2 & 0x1fff;
1109 var bh2 = b2 >>> 13;
1110 var b3 = b[3] | 0;
1111 var bl3 = b3 & 0x1fff;
1112 var bh3 = b3 >>> 13;
1113 var b4 = b[4] | 0;
1114 var bl4 = b4 & 0x1fff;
1115 var bh4 = b4 >>> 13;
1116 var b5 = b[5] | 0;
1117 var bl5 = b5 & 0x1fff;
1118 var bh5 = b5 >>> 13;
1119 var b6 = b[6] | 0;
1120 var bl6 = b6 & 0x1fff;
1121 var bh6 = b6 >>> 13;
1122 var b7 = b[7] | 0;
1123 var bl7 = b7 & 0x1fff;
1124 var bh7 = b7 >>> 13;
1125 var b8 = b[8] | 0;
1126 var bl8 = b8 & 0x1fff;
1127 var bh8 = b8 >>> 13;
1128 var b9 = b[9] | 0;
1129 var bl9 = b9 & 0x1fff;
1130 var bh9 = b9 >>> 13;
1131
1132 out.negative = self.negative ^ num.negative;
1133 out.length = 19;
1134 /* k = 0 */
1135 lo = Math.imul(al0, bl0);
1136 mid = Math.imul(al0, bh0);
1137 mid = (mid + Math.imul(ah0, bl0)) | 0;
1138 hi = Math.imul(ah0, bh0);
1139 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1140 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
1141 w0 &= 0x3ffffff;
1142 /* k = 1 */
1143 lo = Math.imul(al1, bl0);
1144 mid = Math.imul(al1, bh0);
1145 mid = (mid + Math.imul(ah1, bl0)) | 0;
1146 hi = Math.imul(ah1, bh0);
1147 lo = (lo + Math.imul(al0, bl1)) | 0;
1148 mid = (mid + Math.imul(al0, bh1)) | 0;
1149 mid = (mid + Math.imul(ah0, bl1)) | 0;
1150 hi = (hi + Math.imul(ah0, bh1)) | 0;
1151 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1152 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
1153 w1 &= 0x3ffffff;
1154 /* k = 2 */
1155 lo = Math.imul(al2, bl0);
1156 mid = Math.imul(al2, bh0);
1157 mid = (mid + Math.imul(ah2, bl0)) | 0;
1158 hi = Math.imul(ah2, bh0);
1159 lo = (lo + Math.imul(al1, bl1)) | 0;
1160 mid = (mid + Math.imul(al1, bh1)) | 0;
1161 mid = (mid + Math.imul(ah1, bl1)) | 0;
1162 hi = (hi + Math.imul(ah1, bh1)) | 0;
1163 lo = (lo + Math.imul(al0, bl2)) | 0;
1164 mid = (mid + Math.imul(al0, bh2)) | 0;
1165 mid = (mid + Math.imul(ah0, bl2)) | 0;
1166 hi = (hi + Math.imul(ah0, bh2)) | 0;
1167 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1168 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
1169 w2 &= 0x3ffffff;
1170 /* k = 3 */
1171 lo = Math.imul(al3, bl0);
1172 mid = Math.imul(al3, bh0);
1173 mid = (mid + Math.imul(ah3, bl0)) | 0;
1174 hi = Math.imul(ah3, bh0);
1175 lo = (lo + Math.imul(al2, bl1)) | 0;
1176 mid = (mid + Math.imul(al2, bh1)) | 0;
1177 mid = (mid + Math.imul(ah2, bl1)) | 0;
1178 hi = (hi + Math.imul(ah2, bh1)) | 0;
1179 lo = (lo + Math.imul(al1, bl2)) | 0;
1180 mid = (mid + Math.imul(al1, bh2)) | 0;
1181 mid = (mid + Math.imul(ah1, bl2)) | 0;
1182 hi = (hi + Math.imul(ah1, bh2)) | 0;
1183 lo = (lo + Math.imul(al0, bl3)) | 0;
1184 mid = (mid + Math.imul(al0, bh3)) | 0;
1185 mid = (mid + Math.imul(ah0, bl3)) | 0;
1186 hi = (hi + Math.imul(ah0, bh3)) | 0;
1187 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1188 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
1189 w3 &= 0x3ffffff;
1190 /* k = 4 */
1191 lo = Math.imul(al4, bl0);
1192 mid = Math.imul(al4, bh0);
1193 mid = (mid + Math.imul(ah4, bl0)) | 0;
1194 hi = Math.imul(ah4, bh0);
1195 lo = (lo + Math.imul(al3, bl1)) | 0;
1196 mid = (mid + Math.imul(al3, bh1)) | 0;
1197 mid = (mid + Math.imul(ah3, bl1)) | 0;
1198 hi = (hi + Math.imul(ah3, bh1)) | 0;
1199 lo = (lo + Math.imul(al2, bl2)) | 0;
1200 mid = (mid + Math.imul(al2, bh2)) | 0;
1201 mid = (mid + Math.imul(ah2, bl2)) | 0;
1202 hi = (hi + Math.imul(ah2, bh2)) | 0;
1203 lo = (lo + Math.imul(al1, bl3)) | 0;
1204 mid = (mid + Math.imul(al1, bh3)) | 0;
1205 mid = (mid + Math.imul(ah1, bl3)) | 0;
1206 hi = (hi + Math.imul(ah1, bh3)) | 0;
1207 lo = (lo + Math.imul(al0, bl4)) | 0;
1208 mid = (mid + Math.imul(al0, bh4)) | 0;
1209 mid = (mid + Math.imul(ah0, bl4)) | 0;
1210 hi = (hi + Math.imul(ah0, bh4)) | 0;
1211 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1212 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
1213 w4 &= 0x3ffffff;
1214 /* k = 5 */
1215 lo = Math.imul(al5, bl0);
1216 mid = Math.imul(al5, bh0);
1217 mid = (mid + Math.imul(ah5, bl0)) | 0;
1218 hi = Math.imul(ah5, bh0);
1219 lo = (lo + Math.imul(al4, bl1)) | 0;
1220 mid = (mid + Math.imul(al4, bh1)) | 0;
1221 mid = (mid + Math.imul(ah4, bl1)) | 0;
1222 hi = (hi + Math.imul(ah4, bh1)) | 0;
1223 lo = (lo + Math.imul(al3, bl2)) | 0;
1224 mid = (mid + Math.imul(al3, bh2)) | 0;
1225 mid = (mid + Math.imul(ah3, bl2)) | 0;
1226 hi = (hi + Math.imul(ah3, bh2)) | 0;
1227 lo = (lo + Math.imul(al2, bl3)) | 0;
1228 mid = (mid + Math.imul(al2, bh3)) | 0;
1229 mid = (mid + Math.imul(ah2, bl3)) | 0;
1230 hi = (hi + Math.imul(ah2, bh3)) | 0;
1231 lo = (lo + Math.imul(al1, bl4)) | 0;
1232 mid = (mid + Math.imul(al1, bh4)) | 0;
1233 mid = (mid + Math.imul(ah1, bl4)) | 0;
1234 hi = (hi + Math.imul(ah1, bh4)) | 0;
1235 lo = (lo + Math.imul(al0, bl5)) | 0;
1236 mid = (mid + Math.imul(al0, bh5)) | 0;
1237 mid = (mid + Math.imul(ah0, bl5)) | 0;
1238 hi = (hi + Math.imul(ah0, bh5)) | 0;
1239 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1240 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
1241 w5 &= 0x3ffffff;
1242 /* k = 6 */
1243 lo = Math.imul(al6, bl0);
1244 mid = Math.imul(al6, bh0);
1245 mid = (mid + Math.imul(ah6, bl0)) | 0;
1246 hi = Math.imul(ah6, bh0);
1247 lo = (lo + Math.imul(al5, bl1)) | 0;
1248 mid = (mid + Math.imul(al5, bh1)) | 0;
1249 mid = (mid + Math.imul(ah5, bl1)) | 0;
1250 hi = (hi + Math.imul(ah5, bh1)) | 0;
1251 lo = (lo + Math.imul(al4, bl2)) | 0;
1252 mid = (mid + Math.imul(al4, bh2)) | 0;
1253 mid = (mid + Math.imul(ah4, bl2)) | 0;
1254 hi = (hi + Math.imul(ah4, bh2)) | 0;
1255 lo = (lo + Math.imul(al3, bl3)) | 0;
1256 mid = (mid + Math.imul(al3, bh3)) | 0;
1257 mid = (mid + Math.imul(ah3, bl3)) | 0;
1258 hi = (hi + Math.imul(ah3, bh3)) | 0;
1259 lo = (lo + Math.imul(al2, bl4)) | 0;
1260 mid = (mid + Math.imul(al2, bh4)) | 0;
1261 mid = (mid + Math.imul(ah2, bl4)) | 0;
1262 hi = (hi + Math.imul(ah2, bh4)) | 0;
1263 lo = (lo + Math.imul(al1, bl5)) | 0;
1264 mid = (mid + Math.imul(al1, bh5)) | 0;
1265 mid = (mid + Math.imul(ah1, bl5)) | 0;
1266 hi = (hi + Math.imul(ah1, bh5)) | 0;
1267 lo = (lo + Math.imul(al0, bl6)) | 0;
1268 mid = (mid + Math.imul(al0, bh6)) | 0;
1269 mid = (mid + Math.imul(ah0, bl6)) | 0;
1270 hi = (hi + Math.imul(ah0, bh6)) | 0;
1271 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1272 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
1273 w6 &= 0x3ffffff;
1274 /* k = 7 */
1275 lo = Math.imul(al7, bl0);
1276 mid = Math.imul(al7, bh0);
1277 mid = (mid + Math.imul(ah7, bl0)) | 0;
1278 hi = Math.imul(ah7, bh0);
1279 lo = (lo + Math.imul(al6, bl1)) | 0;
1280 mid = (mid + Math.imul(al6, bh1)) | 0;
1281 mid = (mid + Math.imul(ah6, bl1)) | 0;
1282 hi = (hi + Math.imul(ah6, bh1)) | 0;
1283 lo = (lo + Math.imul(al5, bl2)) | 0;
1284 mid = (mid + Math.imul(al5, bh2)) | 0;
1285 mid = (mid + Math.imul(ah5, bl2)) | 0;
1286 hi = (hi + Math.imul(ah5, bh2)) | 0;
1287 lo = (lo + Math.imul(al4, bl3)) | 0;
1288 mid = (mid + Math.imul(al4, bh3)) | 0;
1289 mid = (mid + Math.imul(ah4, bl3)) | 0;
1290 hi = (hi + Math.imul(ah4, bh3)) | 0;
1291 lo = (lo + Math.imul(al3, bl4)) | 0;
1292 mid = (mid + Math.imul(al3, bh4)) | 0;
1293 mid = (mid + Math.imul(ah3, bl4)) | 0;
1294 hi = (hi + Math.imul(ah3, bh4)) | 0;
1295 lo = (lo + Math.imul(al2, bl5)) | 0;
1296 mid = (mid + Math.imul(al2, bh5)) | 0;
1297 mid = (mid + Math.imul(ah2, bl5)) | 0;
1298 hi = (hi + Math.imul(ah2, bh5)) | 0;
1299 lo = (lo + Math.imul(al1, bl6)) | 0;
1300 mid = (mid + Math.imul(al1, bh6)) | 0;
1301 mid = (mid + Math.imul(ah1, bl6)) | 0;
1302 hi = (hi + Math.imul(ah1, bh6)) | 0;
1303 lo = (lo + Math.imul(al0, bl7)) | 0;
1304 mid = (mid + Math.imul(al0, bh7)) | 0;
1305 mid = (mid + Math.imul(ah0, bl7)) | 0;
1306 hi = (hi + Math.imul(ah0, bh7)) | 0;
1307 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1308 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
1309 w7 &= 0x3ffffff;
1310 /* k = 8 */
1311 lo = Math.imul(al8, bl0);
1312 mid = Math.imul(al8, bh0);
1313 mid = (mid + Math.imul(ah8, bl0)) | 0;
1314 hi = Math.imul(ah8, bh0);
1315 lo = (lo + Math.imul(al7, bl1)) | 0;
1316 mid = (mid + Math.imul(al7, bh1)) | 0;
1317 mid = (mid + Math.imul(ah7, bl1)) | 0;
1318 hi = (hi + Math.imul(ah7, bh1)) | 0;
1319 lo = (lo + Math.imul(al6, bl2)) | 0;
1320 mid = (mid + Math.imul(al6, bh2)) | 0;
1321 mid = (mid + Math.imul(ah6, bl2)) | 0;
1322 hi = (hi + Math.imul(ah6, bh2)) | 0;
1323 lo = (lo + Math.imul(al5, bl3)) | 0;
1324 mid = (mid + Math.imul(al5, bh3)) | 0;
1325 mid = (mid + Math.imul(ah5, bl3)) | 0;
1326 hi = (hi + Math.imul(ah5, bh3)) | 0;
1327 lo = (lo + Math.imul(al4, bl4)) | 0;
1328 mid = (mid + Math.imul(al4, bh4)) | 0;
1329 mid = (mid + Math.imul(ah4, bl4)) | 0;
1330 hi = (hi + Math.imul(ah4, bh4)) | 0;
1331 lo = (lo + Math.imul(al3, bl5)) | 0;
1332 mid = (mid + Math.imul(al3, bh5)) | 0;
1333 mid = (mid + Math.imul(ah3, bl5)) | 0;
1334 hi = (hi + Math.imul(ah3, bh5)) | 0;
1335 lo = (lo + Math.imul(al2, bl6)) | 0;
1336 mid = (mid + Math.imul(al2, bh6)) | 0;
1337 mid = (mid + Math.imul(ah2, bl6)) | 0;
1338 hi = (hi + Math.imul(ah2, bh6)) | 0;
1339 lo = (lo + Math.imul(al1, bl7)) | 0;
1340 mid = (mid + Math.imul(al1, bh7)) | 0;
1341 mid = (mid + Math.imul(ah1, bl7)) | 0;
1342 hi = (hi + Math.imul(ah1, bh7)) | 0;
1343 lo = (lo + Math.imul(al0, bl8)) | 0;
1344 mid = (mid + Math.imul(al0, bh8)) | 0;
1345 mid = (mid + Math.imul(ah0, bl8)) | 0;
1346 hi = (hi + Math.imul(ah0, bh8)) | 0;
1347 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1348 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
1349 w8 &= 0x3ffffff;
1350 /* k = 9 */
1351 lo = Math.imul(al9, bl0);
1352 mid = Math.imul(al9, bh0);
1353 mid = (mid + Math.imul(ah9, bl0)) | 0;
1354 hi = Math.imul(ah9, bh0);
1355 lo = (lo + Math.imul(al8, bl1)) | 0;
1356 mid = (mid + Math.imul(al8, bh1)) | 0;
1357 mid = (mid + Math.imul(ah8, bl1)) | 0;
1358 hi = (hi + Math.imul(ah8, bh1)) | 0;
1359 lo = (lo + Math.imul(al7, bl2)) | 0;
1360 mid = (mid + Math.imul(al7, bh2)) | 0;
1361 mid = (mid + Math.imul(ah7, bl2)) | 0;
1362 hi = (hi + Math.imul(ah7, bh2)) | 0;
1363 lo = (lo + Math.imul(al6, bl3)) | 0;
1364 mid = (mid + Math.imul(al6, bh3)) | 0;
1365 mid = (mid + Math.imul(ah6, bl3)) | 0;
1366 hi = (hi + Math.imul(ah6, bh3)) | 0;
1367 lo = (lo + Math.imul(al5, bl4)) | 0;
1368 mid = (mid + Math.imul(al5, bh4)) | 0;
1369 mid = (mid + Math.imul(ah5, bl4)) | 0;
1370 hi = (hi + Math.imul(ah5, bh4)) | 0;
1371 lo = (lo + Math.imul(al4, bl5)) | 0;
1372 mid = (mid + Math.imul(al4, bh5)) | 0;
1373 mid = (mid + Math.imul(ah4, bl5)) | 0;
1374 hi = (hi + Math.imul(ah4, bh5)) | 0;
1375 lo = (lo + Math.imul(al3, bl6)) | 0;
1376 mid = (mid + Math.imul(al3, bh6)) | 0;
1377 mid = (mid + Math.imul(ah3, bl6)) | 0;
1378 hi = (hi + Math.imul(ah3, bh6)) | 0;
1379 lo = (lo + Math.imul(al2, bl7)) | 0;
1380 mid = (mid + Math.imul(al2, bh7)) | 0;
1381 mid = (mid + Math.imul(ah2, bl7)) | 0;
1382 hi = (hi + Math.imul(ah2, bh7)) | 0;
1383 lo = (lo + Math.imul(al1, bl8)) | 0;
1384 mid = (mid + Math.imul(al1, bh8)) | 0;
1385 mid = (mid + Math.imul(ah1, bl8)) | 0;
1386 hi = (hi + Math.imul(ah1, bh8)) | 0;
1387 lo = (lo + Math.imul(al0, bl9)) | 0;
1388 mid = (mid + Math.imul(al0, bh9)) | 0;
1389 mid = (mid + Math.imul(ah0, bl9)) | 0;
1390 hi = (hi + Math.imul(ah0, bh9)) | 0;
1391 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1392 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
1393 w9 &= 0x3ffffff;
1394 /* k = 10 */
1395 lo = Math.imul(al9, bl1);
1396 mid = Math.imul(al9, bh1);
1397 mid = (mid + Math.imul(ah9, bl1)) | 0;
1398 hi = Math.imul(ah9, bh1);
1399 lo = (lo + Math.imul(al8, bl2)) | 0;
1400 mid = (mid + Math.imul(al8, bh2)) | 0;
1401 mid = (mid + Math.imul(ah8, bl2)) | 0;
1402 hi = (hi + Math.imul(ah8, bh2)) | 0;
1403 lo = (lo + Math.imul(al7, bl3)) | 0;
1404 mid = (mid + Math.imul(al7, bh3)) | 0;
1405 mid = (mid + Math.imul(ah7, bl3)) | 0;
1406 hi = (hi + Math.imul(ah7, bh3)) | 0;
1407 lo = (lo + Math.imul(al6, bl4)) | 0;
1408 mid = (mid + Math.imul(al6, bh4)) | 0;
1409 mid = (mid + Math.imul(ah6, bl4)) | 0;
1410 hi = (hi + Math.imul(ah6, bh4)) | 0;
1411 lo = (lo + Math.imul(al5, bl5)) | 0;
1412 mid = (mid + Math.imul(al5, bh5)) | 0;
1413 mid = (mid + Math.imul(ah5, bl5)) | 0;
1414 hi = (hi + Math.imul(ah5, bh5)) | 0;
1415 lo = (lo + Math.imul(al4, bl6)) | 0;
1416 mid = (mid + Math.imul(al4, bh6)) | 0;
1417 mid = (mid + Math.imul(ah4, bl6)) | 0;
1418 hi = (hi + Math.imul(ah4, bh6)) | 0;
1419 lo = (lo + Math.imul(al3, bl7)) | 0;
1420 mid = (mid + Math.imul(al3, bh7)) | 0;
1421 mid = (mid + Math.imul(ah3, bl7)) | 0;
1422 hi = (hi + Math.imul(ah3, bh7)) | 0;
1423 lo = (lo + Math.imul(al2, bl8)) | 0;
1424 mid = (mid + Math.imul(al2, bh8)) | 0;
1425 mid = (mid + Math.imul(ah2, bl8)) | 0;
1426 hi = (hi + Math.imul(ah2, bh8)) | 0;
1427 lo = (lo + Math.imul(al1, bl9)) | 0;
1428 mid = (mid + Math.imul(al1, bh9)) | 0;
1429 mid = (mid + Math.imul(ah1, bl9)) | 0;
1430 hi = (hi + Math.imul(ah1, bh9)) | 0;
1431 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1432 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
1433 w10 &= 0x3ffffff;
1434 /* k = 11 */
1435 lo = Math.imul(al9, bl2);
1436 mid = Math.imul(al9, bh2);
1437 mid = (mid + Math.imul(ah9, bl2)) | 0;
1438 hi = Math.imul(ah9, bh2);
1439 lo = (lo + Math.imul(al8, bl3)) | 0;
1440 mid = (mid + Math.imul(al8, bh3)) | 0;
1441 mid = (mid + Math.imul(ah8, bl3)) | 0;
1442 hi = (hi + Math.imul(ah8, bh3)) | 0;
1443 lo = (lo + Math.imul(al7, bl4)) | 0;
1444 mid = (mid + Math.imul(al7, bh4)) | 0;
1445 mid = (mid + Math.imul(ah7, bl4)) | 0;
1446 hi = (hi + Math.imul(ah7, bh4)) | 0;
1447 lo = (lo + Math.imul(al6, bl5)) | 0;
1448 mid = (mid + Math.imul(al6, bh5)) | 0;
1449 mid = (mid + Math.imul(ah6, bl5)) | 0;
1450 hi = (hi + Math.imul(ah6, bh5)) | 0;
1451 lo = (lo + Math.imul(al5, bl6)) | 0;
1452 mid = (mid + Math.imul(al5, bh6)) | 0;
1453 mid = (mid + Math.imul(ah5, bl6)) | 0;
1454 hi = (hi + Math.imul(ah5, bh6)) | 0;
1455 lo = (lo + Math.imul(al4, bl7)) | 0;
1456 mid = (mid + Math.imul(al4, bh7)) | 0;
1457 mid = (mid + Math.imul(ah4, bl7)) | 0;
1458 hi = (hi + Math.imul(ah4, bh7)) | 0;
1459 lo = (lo + Math.imul(al3, bl8)) | 0;
1460 mid = (mid + Math.imul(al3, bh8)) | 0;
1461 mid = (mid + Math.imul(ah3, bl8)) | 0;
1462 hi = (hi + Math.imul(ah3, bh8)) | 0;
1463 lo = (lo + Math.imul(al2, bl9)) | 0;
1464 mid = (mid + Math.imul(al2, bh9)) | 0;
1465 mid = (mid + Math.imul(ah2, bl9)) | 0;
1466 hi = (hi + Math.imul(ah2, bh9)) | 0;
1467 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1468 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
1469 w11 &= 0x3ffffff;
1470 /* k = 12 */
1471 lo = Math.imul(al9, bl3);
1472 mid = Math.imul(al9, bh3);
1473 mid = (mid + Math.imul(ah9, bl3)) | 0;
1474 hi = Math.imul(ah9, bh3);
1475 lo = (lo + Math.imul(al8, bl4)) | 0;
1476 mid = (mid + Math.imul(al8, bh4)) | 0;
1477 mid = (mid + Math.imul(ah8, bl4)) | 0;
1478 hi = (hi + Math.imul(ah8, bh4)) | 0;
1479 lo = (lo + Math.imul(al7, bl5)) | 0;
1480 mid = (mid + Math.imul(al7, bh5)) | 0;
1481 mid = (mid + Math.imul(ah7, bl5)) | 0;
1482 hi = (hi + Math.imul(ah7, bh5)) | 0;
1483 lo = (lo + Math.imul(al6, bl6)) | 0;
1484 mid = (mid + Math.imul(al6, bh6)) | 0;
1485 mid = (mid + Math.imul(ah6, bl6)) | 0;
1486 hi = (hi + Math.imul(ah6, bh6)) | 0;
1487 lo = (lo + Math.imul(al5, bl7)) | 0;
1488 mid = (mid + Math.imul(al5, bh7)) | 0;
1489 mid = (mid + Math.imul(ah5, bl7)) | 0;
1490 hi = (hi + Math.imul(ah5, bh7)) | 0;
1491 lo = (lo + Math.imul(al4, bl8)) | 0;
1492 mid = (mid + Math.imul(al4, bh8)) | 0;
1493 mid = (mid + Math.imul(ah4, bl8)) | 0;
1494 hi = (hi + Math.imul(ah4, bh8)) | 0;
1495 lo = (lo + Math.imul(al3, bl9)) | 0;
1496 mid = (mid + Math.imul(al3, bh9)) | 0;
1497 mid = (mid + Math.imul(ah3, bl9)) | 0;
1498 hi = (hi + Math.imul(ah3, bh9)) | 0;
1499 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1500 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
1501 w12 &= 0x3ffffff;
1502 /* k = 13 */
1503 lo = Math.imul(al9, bl4);
1504 mid = Math.imul(al9, bh4);
1505 mid = (mid + Math.imul(ah9, bl4)) | 0;
1506 hi = Math.imul(ah9, bh4);
1507 lo = (lo + Math.imul(al8, bl5)) | 0;
1508 mid = (mid + Math.imul(al8, bh5)) | 0;
1509 mid = (mid + Math.imul(ah8, bl5)) | 0;
1510 hi = (hi + Math.imul(ah8, bh5)) | 0;
1511 lo = (lo + Math.imul(al7, bl6)) | 0;
1512 mid = (mid + Math.imul(al7, bh6)) | 0;
1513 mid = (mid + Math.imul(ah7, bl6)) | 0;
1514 hi = (hi + Math.imul(ah7, bh6)) | 0;
1515 lo = (lo + Math.imul(al6, bl7)) | 0;
1516 mid = (mid + Math.imul(al6, bh7)) | 0;
1517 mid = (mid + Math.imul(ah6, bl7)) | 0;
1518 hi = (hi + Math.imul(ah6, bh7)) | 0;
1519 lo = (lo + Math.imul(al5, bl8)) | 0;
1520 mid = (mid + Math.imul(al5, bh8)) | 0;
1521 mid = (mid + Math.imul(ah5, bl8)) | 0;
1522 hi = (hi + Math.imul(ah5, bh8)) | 0;
1523 lo = (lo + Math.imul(al4, bl9)) | 0;
1524 mid = (mid + Math.imul(al4, bh9)) | 0;
1525 mid = (mid + Math.imul(ah4, bl9)) | 0;
1526 hi = (hi + Math.imul(ah4, bh9)) | 0;
1527 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1528 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
1529 w13 &= 0x3ffffff;
1530 /* k = 14 */
1531 lo = Math.imul(al9, bl5);
1532 mid = Math.imul(al9, bh5);
1533 mid = (mid + Math.imul(ah9, bl5)) | 0;
1534 hi = Math.imul(ah9, bh5);
1535 lo = (lo + Math.imul(al8, bl6)) | 0;
1536 mid = (mid + Math.imul(al8, bh6)) | 0;
1537 mid = (mid + Math.imul(ah8, bl6)) | 0;
1538 hi = (hi + Math.imul(ah8, bh6)) | 0;
1539 lo = (lo + Math.imul(al7, bl7)) | 0;
1540 mid = (mid + Math.imul(al7, bh7)) | 0;
1541 mid = (mid + Math.imul(ah7, bl7)) | 0;
1542 hi = (hi + Math.imul(ah7, bh7)) | 0;
1543 lo = (lo + Math.imul(al6, bl8)) | 0;
1544 mid = (mid + Math.imul(al6, bh8)) | 0;
1545 mid = (mid + Math.imul(ah6, bl8)) | 0;
1546 hi = (hi + Math.imul(ah6, bh8)) | 0;
1547 lo = (lo + Math.imul(al5, bl9)) | 0;
1548 mid = (mid + Math.imul(al5, bh9)) | 0;
1549 mid = (mid + Math.imul(ah5, bl9)) | 0;
1550 hi = (hi + Math.imul(ah5, bh9)) | 0;
1551 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1552 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
1553 w14 &= 0x3ffffff;
1554 /* k = 15 */
1555 lo = Math.imul(al9, bl6);
1556 mid = Math.imul(al9, bh6);
1557 mid = (mid + Math.imul(ah9, bl6)) | 0;
1558 hi = Math.imul(ah9, bh6);
1559 lo = (lo + Math.imul(al8, bl7)) | 0;
1560 mid = (mid + Math.imul(al8, bh7)) | 0;
1561 mid = (mid + Math.imul(ah8, bl7)) | 0;
1562 hi = (hi + Math.imul(ah8, bh7)) | 0;
1563 lo = (lo + Math.imul(al7, bl8)) | 0;
1564 mid = (mid + Math.imul(al7, bh8)) | 0;
1565 mid = (mid + Math.imul(ah7, bl8)) | 0;
1566 hi = (hi + Math.imul(ah7, bh8)) | 0;
1567 lo = (lo + Math.imul(al6, bl9)) | 0;
1568 mid = (mid + Math.imul(al6, bh9)) | 0;
1569 mid = (mid + Math.imul(ah6, bl9)) | 0;
1570 hi = (hi + Math.imul(ah6, bh9)) | 0;
1571 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1572 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
1573 w15 &= 0x3ffffff;
1574 /* k = 16 */
1575 lo = Math.imul(al9, bl7);
1576 mid = Math.imul(al9, bh7);
1577 mid = (mid + Math.imul(ah9, bl7)) | 0;
1578 hi = Math.imul(ah9, bh7);
1579 lo = (lo + Math.imul(al8, bl8)) | 0;
1580 mid = (mid + Math.imul(al8, bh8)) | 0;
1581 mid = (mid + Math.imul(ah8, bl8)) | 0;
1582 hi = (hi + Math.imul(ah8, bh8)) | 0;
1583 lo = (lo + Math.imul(al7, bl9)) | 0;
1584 mid = (mid + Math.imul(al7, bh9)) | 0;
1585 mid = (mid + Math.imul(ah7, bl9)) | 0;
1586 hi = (hi + Math.imul(ah7, bh9)) | 0;
1587 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1588 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
1589 w16 &= 0x3ffffff;
1590 /* k = 17 */
1591 lo = Math.imul(al9, bl8);
1592 mid = Math.imul(al9, bh8);
1593 mid = (mid + Math.imul(ah9, bl8)) | 0;
1594 hi = Math.imul(ah9, bh8);
1595 lo = (lo + Math.imul(al8, bl9)) | 0;
1596 mid = (mid + Math.imul(al8, bh9)) | 0;
1597 mid = (mid + Math.imul(ah8, bl9)) | 0;
1598 hi = (hi + Math.imul(ah8, bh9)) | 0;
1599 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1600 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
1601 w17 &= 0x3ffffff;
1602 /* k = 18 */
1603 lo = Math.imul(al9, bl9);
1604 mid = Math.imul(al9, bh9);
1605 mid = (mid + Math.imul(ah9, bl9)) | 0;
1606 hi = Math.imul(ah9, bh9);
1607 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
1608 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
1609 w18 &= 0x3ffffff;
1610 o[0] = w0;
1611 o[1] = w1;
1612 o[2] = w2;
1613 o[3] = w3;
1614 o[4] = w4;
1615 o[5] = w5;
1616 o[6] = w6;
1617 o[7] = w7;
1618 o[8] = w8;
1619 o[9] = w9;
1620 o[10] = w10;
1621 o[11] = w11;
1622 o[12] = w12;
1623 o[13] = w13;
1624 o[14] = w14;
1625 o[15] = w15;
1626 o[16] = w16;
1627 o[17] = w17;
1628 o[18] = w18;
1629 if (c !== 0) {
1630 o[19] = c;
1631 out.length++;
1632 }
1633 return out;
1634 };
1635
1636 // Polyfill comb
1637 if (!Math.imul) {
1638 comb10MulTo = smallMulTo;
1639 }
1640
1641 function bigMulTo (self, num, out) {
1642 out.negative = num.negative ^ self.negative;
1643 out.length = self.length + num.length;
1644
1645 var carry = 0;
1646 var hncarry = 0;
1647 for (var k = 0; k < out.length - 1; k++) {
1648 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
1649 // note that ncarry could be >= 0x3ffffff
1650 var ncarry = hncarry;
1651 hncarry = 0;
1652 var rword = carry & 0x3ffffff;
1653 var maxJ = Math.min(k, num.length - 1);
1654 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
1655 var i = k - j;
1656 var a = self.words[i] | 0;
1657 var b = num.words[j] | 0;
1658 var r = a * b;
1659
1660 var lo = r & 0x3ffffff;
1661 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
1662 lo = (lo + rword) | 0;
1663 rword = lo & 0x3ffffff;
1664 ncarry = (ncarry + (lo >>> 26)) | 0;
1665
1666 hncarry += ncarry >>> 26;
1667 ncarry &= 0x3ffffff;
1668 }
1669 out.words[k] = rword;
1670 carry = ncarry;
1671 ncarry = hncarry;
1672 }
1673 if (carry !== 0) {
1674 out.words[k] = carry;
1675 } else {
1676 out.length--;
1677 }
1678
1679 return out.strip();
1680 }
1681
1682 function jumboMulTo (self, num, out) {
1683 var fftm = new FFTM();
1684 return fftm.mulp(self, num, out);
1685 }
1686
1687 BN.prototype.mulTo = function mulTo (num, out) {
1688 var res;
1689 var len = this.length + num.length;
1690 if (this.length === 10 && num.length === 10) {
1691 res = comb10MulTo(this, num, out);
1692 } else if (len < 63) {
1693 res = smallMulTo(this, num, out);
1694 } else if (len < 1024) {
1695 res = bigMulTo(this, num, out);
1696 } else {
1697 res = jumboMulTo(this, num, out);
1698 }
1699
1700 return res;
1701 };
1702
1703 // Cooley-Tukey algorithm for FFT
1704 // slightly revisited to rely on looping instead of recursion
1705
1706 function FFTM (x, y) {
1707 this.x = x;
1708 this.y = y;
1709 }
1710
1711 FFTM.prototype.makeRBT = function makeRBT (N) {
1712 var t = new Array(N);
1713 var l = BN.prototype._countBits(N) - 1;
1714 for (var i = 0; i < N; i++) {
1715 t[i] = this.revBin(i, l, N);
1716 }
1717
1718 return t;
1719 };
1720
1721 // Returns binary-reversed representation of `x`
1722 FFTM.prototype.revBin = function revBin (x, l, N) {
1723 if (x === 0 || x === N - 1) return x;
1724
1725 var rb = 0;
1726 for (var i = 0; i < l; i++) {
1727 rb |= (x & 1) << (l - i - 1);
1728 x >>= 1;
1729 }
1730
1731 return rb;
1732 };
1733
1734 // Performs "tweedling" phase, therefore 'emulating'
1735 // behaviour of the recursive algorithm
1736 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
1737 for (var i = 0; i < N; i++) {
1738 rtws[i] = rws[rbt[i]];
1739 itws[i] = iws[rbt[i]];
1740 }
1741 };
1742
1743 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
1744 this.permute(rbt, rws, iws, rtws, itws, N);
1745
1746 for (var s = 1; s < N; s <<= 1) {
1747 var l = s << 1;
1748
1749 var rtwdf = Math.cos(2 * Math.PI / l);
1750 var itwdf = Math.sin(2 * Math.PI / l);
1751
1752 for (var p = 0; p < N; p += l) {
1753 var rtwdf_ = rtwdf;
1754 var itwdf_ = itwdf;
1755
1756 for (var j = 0; j < s; j++) {
1757 var re = rtws[p + j];
1758 var ie = itws[p + j];
1759
1760 var ro = rtws[p + j + s];
1761 var io = itws[p + j + s];
1762
1763 var rx = rtwdf_ * ro - itwdf_ * io;
1764
1765 io = rtwdf_ * io + itwdf_ * ro;
1766 ro = rx;
1767
1768 rtws[p + j] = re + ro;
1769 itws[p + j] = ie + io;
1770
1771 rtws[p + j + s] = re - ro;
1772 itws[p + j + s] = ie - io;
1773
1774 /* jshint maxdepth : false */
1775 if (j !== l) {
1776 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
1777
1778 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
1779 rtwdf_ = rx;
1780 }
1781 }
1782 }
1783 }
1784 };
1785
1786 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
1787 var N = Math.max(m, n) | 1;
1788 var odd = N & 1;
1789 var i = 0;
1790 for (N = N / 2 | 0; N; N = N >>> 1) {
1791 i++;
1792 }
1793
1794 return 1 << i + 1 + odd;
1795 };
1796
1797 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
1798 if (N <= 1) return;
1799
1800 for (var i = 0; i < N / 2; i++) {
1801 var t = rws[i];
1802
1803 rws[i] = rws[N - i - 1];
1804 rws[N - i - 1] = t;
1805
1806 t = iws[i];
1807
1808 iws[i] = -iws[N - i - 1];
1809 iws[N - i - 1] = -t;
1810 }
1811 };
1812
1813 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
1814 var carry = 0;
1815 for (var i = 0; i < N / 2; i++) {
1816 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
1817 Math.round(ws[2 * i] / N) +
1818 carry;
1819
1820 ws[i] = w & 0x3ffffff;
1821
1822 if (w < 0x4000000) {
1823 carry = 0;
1824 } else {
1825 carry = w / 0x4000000 | 0;
1826 }
1827 }
1828
1829 return ws;
1830 };
1831
1832 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
1833 var carry = 0;
1834 for (var i = 0; i < len; i++) {
1835 carry = carry + (ws[i] | 0);
1836
1837 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
1838 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
1839 }
1840
1841 // Pad with zeroes
1842 for (i = 2 * len; i < N; ++i) {
1843 rws[i] = 0;
1844 }
1845
1846 assert(carry === 0);
1847 assert((carry & ~0x1fff) === 0);
1848 };
1849
1850 FFTM.prototype.stub = function stub (N) {
1851 var ph = new Array(N);
1852 for (var i = 0; i < N; i++) {
1853 ph[i] = 0;
1854 }
1855
1856 return ph;
1857 };
1858
1859 FFTM.prototype.mulp = function mulp (x, y, out) {
1860 var N = 2 * this.guessLen13b(x.length, y.length);
1861
1862 var rbt = this.makeRBT(N);
1863
1864 var _ = this.stub(N);
1865
1866 var rws = new Array(N);
1867 var rwst = new Array(N);
1868 var iwst = new Array(N);
1869
1870 var nrws = new Array(N);
1871 var nrwst = new Array(N);
1872 var niwst = new Array(N);
1873
1874 var rmws = out.words;
1875 rmws.length = N;
1876
1877 this.convert13b(x.words, x.length, rws, N);
1878 this.convert13b(y.words, y.length, nrws, N);
1879
1880 this.transform(rws, _, rwst, iwst, N, rbt);
1881 this.transform(nrws, _, nrwst, niwst, N, rbt);
1882
1883 for (var i = 0; i < N; i++) {
1884 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
1885 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
1886 rwst[i] = rx;
1887 }
1888
1889 this.conjugate(rwst, iwst, N);
1890 this.transform(rwst, iwst, rmws, _, N, rbt);
1891 this.conjugate(rmws, _, N);
1892 this.normalize13b(rmws, N);
1893
1894 out.negative = x.negative ^ y.negative;
1895 out.length = x.length + y.length;
1896 return out.strip();
1897 };
1898
1899 // Multiply `this` by `num`
1900 BN.prototype.mul = function mul (num) {
1901 var out = new BN(null);
1902 out.words = new Array(this.length + num.length);
1903 return this.mulTo(num, out);
1904 };
1905
1906 // Multiply employing FFT
1907 BN.prototype.mulf = function mulf (num) {
1908 var out = new BN(null);
1909 out.words = new Array(this.length + num.length);
1910 return jumboMulTo(this, num, out);
1911 };
1912
1913 // In-place Multiplication
1914 BN.prototype.imul = function imul (num) {
1915 return this.clone().mulTo(num, this);
1916 };
1917
1918 BN.prototype.imuln = function imuln (num) {
1919 assert(typeof num === 'number');
1920 assert(num < 0x4000000);
1921
1922 // Carry
1923 var carry = 0;
1924 for (var i = 0; i < this.length; i++) {
1925 var w = (this.words[i] | 0) * num;
1926 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
1927 carry >>= 26;
1928 carry += (w / 0x4000000) | 0;
1929 // NOTE: lo is 27bit maximum
1930 carry += lo >>> 26;
1931 this.words[i] = lo & 0x3ffffff;
1932 }
1933
1934 if (carry !== 0) {
1935 this.words[i] = carry;
1936 this.length++;
1937 }
1938
1939 return this;
1940 };
1941
1942 BN.prototype.muln = function muln (num) {
1943 return this.clone().imuln(num);
1944 };
1945
1946 // `this` * `this`
1947 BN.prototype.sqr = function sqr () {
1948 return this.mul(this);
1949 };
1950
1951 // `this` * `this` in-place
1952 BN.prototype.isqr = function isqr () {
1953 return this.imul(this.clone());
1954 };
1955
1956 // Math.pow(`this`, `num`)
1957 BN.prototype.pow = function pow (num) {
1958 var w = toBitArray(num);
1959 if (w.length === 0) return new BN(1);
1960
1961 // Skip leading zeroes
1962 var res = this;
1963 for (var i = 0; i < w.length; i++, res = res.sqr()) {
1964 if (w[i] !== 0) break;
1965 }
1966
1967 if (++i < w.length) {
1968 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
1969 if (w[i] === 0) continue;
1970
1971 res = res.mul(q);
1972 }
1973 }
1974
1975 return res;
1976 };
1977
1978 // Shift-left in-place
1979 BN.prototype.iushln = function iushln (bits) {
1980 assert(typeof bits === 'number' && bits >= 0);
1981 var r = bits % 26;
1982 var s = (bits - r) / 26;
1983 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
1984 var i;
1985
1986 if (r !== 0) {
1987 var carry = 0;
1988
1989 for (i = 0; i < this.length; i++) {
1990 var newCarry = this.words[i] & carryMask;
1991 var c = ((this.words[i] | 0) - newCarry) << r;
1992 this.words[i] = c | carry;
1993 carry = newCarry >>> (26 - r);
1994 }
1995
1996 if (carry) {
1997 this.words[i] = carry;
1998 this.length++;
1999 }
2000 }
2001
2002 if (s !== 0) {
2003 for (i = this.length - 1; i >= 0; i--) {
2004 this.words[i + s] = this.words[i];
2005 }
2006
2007 for (i = 0; i < s; i++) {
2008 this.words[i] = 0;
2009 }
2010
2011 this.length += s;
2012 }
2013
2014 return this.strip();
2015 };
2016
2017 BN.prototype.ishln = function ishln (bits) {
2018 // TODO(indutny): implement me
2019 assert(this.negative === 0);
2020 return this.iushln(bits);
2021 };
2022
2023 // Shift-right in-place
2024 // NOTE: `hint` is a lowest bit before trailing zeroes
2025 // NOTE: if `extended` is present - it will be filled with destroyed bits
2026 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
2027 assert(typeof bits === 'number' && bits >= 0);
2028 var h;
2029 if (hint) {
2030 h = (hint - (hint % 26)) / 26;
2031 } else {
2032 h = 0;
2033 }
2034
2035 var r = bits % 26;
2036 var s = Math.min((bits - r) / 26, this.length);
2037 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
2038 var maskedWords = extended;
2039
2040 h -= s;
2041 h = Math.max(0, h);
2042
2043 // Extended mode, copy masked part
2044 if (maskedWords) {
2045 for (var i = 0; i < s; i++) {
2046 maskedWords.words[i] = this.words[i];
2047 }
2048 maskedWords.length = s;
2049 }
2050
2051 if (s === 0) {
2052 // No-op, we should not move anything at all
2053 } else if (this.length > s) {
2054 this.length -= s;
2055 for (i = 0; i < this.length; i++) {
2056 this.words[i] = this.words[i + s];
2057 }
2058 } else {
2059 this.words[0] = 0;
2060 this.length = 1;
2061 }
2062
2063 var carry = 0;
2064 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
2065 var word = this.words[i] | 0;
2066 this.words[i] = (carry << (26 - r)) | (word >>> r);
2067 carry = word & mask;
2068 }
2069
2070 // Push carried bits as a mask
2071 if (maskedWords && carry !== 0) {
2072 maskedWords.words[maskedWords.length++] = carry;
2073 }
2074
2075 if (this.length === 0) {
2076 this.words[0] = 0;
2077 this.length = 1;
2078 }
2079
2080 return this.strip();
2081 };
2082
2083 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
2084 // TODO(indutny): implement me
2085 assert(this.negative === 0);
2086 return this.iushrn(bits, hint, extended);
2087 };
2088
2089 // Shift-left
2090 BN.prototype.shln = function shln (bits) {
2091 return this.clone().ishln(bits);
2092 };
2093
2094 BN.prototype.ushln = function ushln (bits) {
2095 return this.clone().iushln(bits);
2096 };
2097
2098 // Shift-right
2099 BN.prototype.shrn = function shrn (bits) {
2100 return this.clone().ishrn(bits);
2101 };
2102
2103 BN.prototype.ushrn = function ushrn (bits) {
2104 return this.clone().iushrn(bits);
2105 };
2106
2107 // Test if n bit is set
2108 BN.prototype.testn = function testn (bit) {
2109 assert(typeof bit === 'number' && bit >= 0);
2110 var r = bit % 26;
2111 var s = (bit - r) / 26;
2112 var q = 1 << r;
2113
2114 // Fast case: bit is much higher than all existing words
2115 if (this.length <= s) return false;
2116
2117 // Check bit and return
2118 var w = this.words[s];
2119
2120 return !!(w & q);
2121 };
2122
2123 // Return only lowers bits of number (in-place)
2124 BN.prototype.imaskn = function imaskn (bits) {
2125 assert(typeof bits === 'number' && bits >= 0);
2126 var r = bits % 26;
2127 var s = (bits - r) / 26;
2128
2129 assert(this.negative === 0, 'imaskn works only with positive numbers');
2130
2131 if (this.length <= s) {
2132 return this;
2133 }
2134
2135 if (r !== 0) {
2136 s++;
2137 }
2138 this.length = Math.min(s, this.length);
2139
2140 if (r !== 0) {
2141 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
2142 this.words[this.length - 1] &= mask;
2143 }
2144
2145 return this.strip();
2146 };
2147
2148 // Return only lowers bits of number
2149 BN.prototype.maskn = function maskn (bits) {
2150 return this.clone().imaskn(bits);
2151 };
2152
2153 // Add plain number `num` to `this`
2154 BN.prototype.iaddn = function iaddn (num) {
2155 assert(typeof num === 'number');
2156 assert(num < 0x4000000);
2157 if (num < 0) return this.isubn(-num);
2158
2159 // Possible sign change
2160 if (this.negative !== 0) {
2161 if (this.length === 1 && (this.words[0] | 0) < num) {
2162 this.words[0] = num - (this.words[0] | 0);
2163 this.negative = 0;
2164 return this;
2165 }
2166
2167 this.negative = 0;
2168 this.isubn(num);
2169 this.negative = 1;
2170 return this;
2171 }
2172
2173 // Add without checks
2174 return this._iaddn(num);
2175 };
2176
2177 BN.prototype._iaddn = function _iaddn (num) {
2178 this.words[0] += num;
2179
2180 // Carry
2181 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
2182 this.words[i] -= 0x4000000;
2183 if (i === this.length - 1) {
2184 this.words[i + 1] = 1;
2185 } else {
2186 this.words[i + 1]++;
2187 }
2188 }
2189 this.length = Math.max(this.length, i + 1);
2190
2191 return this;
2192 };
2193
2194 // Subtract plain number `num` from `this`
2195 BN.prototype.isubn = function isubn (num) {
2196 assert(typeof num === 'number');
2197 assert(num < 0x4000000);
2198 if (num < 0) return this.iaddn(-num);
2199
2200 if (this.negative !== 0) {
2201 this.negative = 0;
2202 this.iaddn(num);
2203 this.negative = 1;
2204 return this;
2205 }
2206
2207 this.words[0] -= num;
2208
2209 if (this.length === 1 && this.words[0] < 0) {
2210 this.words[0] = -this.words[0];
2211 this.negative = 1;
2212 } else {
2213 // Carry
2214 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
2215 this.words[i] += 0x4000000;
2216 this.words[i + 1] -= 1;
2217 }
2218 }
2219
2220 return this.strip();
2221 };
2222
2223 BN.prototype.addn = function addn (num) {
2224 return this.clone().iaddn(num);
2225 };
2226
2227 BN.prototype.subn = function subn (num) {
2228 return this.clone().isubn(num);
2229 };
2230
2231 BN.prototype.iabs = function iabs () {
2232 this.negative = 0;
2233
2234 return this;
2235 };
2236
2237 BN.prototype.abs = function abs () {
2238 return this.clone().iabs();
2239 };
2240
2241 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
2242 var len = num.length + shift;
2243 var i;
2244
2245 this._expand(len);
2246
2247 var w;
2248 var carry = 0;
2249 for (i = 0; i < num.length; i++) {
2250 w = (this.words[i + shift] | 0) + carry;
2251 var right = (num.words[i] | 0) * mul;
2252 w -= right & 0x3ffffff;
2253 carry = (w >> 26) - ((right / 0x4000000) | 0);
2254 this.words[i + shift] = w & 0x3ffffff;
2255 }
2256 for (; i < this.length - shift; i++) {
2257 w = (this.words[i + shift] | 0) + carry;
2258 carry = w >> 26;
2259 this.words[i + shift] = w & 0x3ffffff;
2260 }
2261
2262 if (carry === 0) return this.strip();
2263
2264 // Subtraction overflow
2265 assert(carry === -1);
2266 carry = 0;
2267 for (i = 0; i < this.length; i++) {
2268 w = -(this.words[i] | 0) + carry;
2269 carry = w >> 26;
2270 this.words[i] = w & 0x3ffffff;
2271 }
2272 this.negative = 1;
2273
2274 return this.strip();
2275 };
2276
2277 BN.prototype._wordDiv = function _wordDiv (num, mode) {
2278 var shift = this.length - num.length;
2279
2280 var a = this.clone();
2281 var b = num;
2282
2283 // Normalize
2284 var bhi = b.words[b.length - 1] | 0;
2285 var bhiBits = this._countBits(bhi);
2286 shift = 26 - bhiBits;
2287 if (shift !== 0) {
2288 b = b.ushln(shift);
2289 a.iushln(shift);
2290 bhi = b.words[b.length - 1] | 0;
2291 }
2292
2293 // Initialize quotient
2294 var m = a.length - b.length;
2295 var q;
2296
2297 if (mode !== 'mod') {
2298 q = new BN(null);
2299 q.length = m + 1;
2300 q.words = new Array(q.length);
2301 for (var i = 0; i < q.length; i++) {
2302 q.words[i] = 0;
2303 }
2304 }
2305
2306 var diff = a.clone()._ishlnsubmul(b, 1, m);
2307 if (diff.negative === 0) {
2308 a = diff;
2309 if (q) {
2310 q.words[m] = 1;
2311 }
2312 }
2313
2314 for (var j = m - 1; j >= 0; j--) {
2315 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
2316 (a.words[b.length + j - 1] | 0);
2317
2318 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
2319 // (0x7ffffff)
2320 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
2321
2322 a._ishlnsubmul(b, qj, j);
2323 while (a.negative !== 0) {
2324 qj--;
2325 a.negative = 0;
2326 a._ishlnsubmul(b, 1, j);
2327 if (!a.isZero()) {
2328 a.negative ^= 1;
2329 }
2330 }
2331 if (q) {
2332 q.words[j] = qj;
2333 }
2334 }
2335 if (q) {
2336 q.strip();
2337 }
2338 a.strip();
2339
2340 // Denormalize
2341 if (mode !== 'div' && shift !== 0) {
2342 a.iushrn(shift);
2343 }
2344
2345 return {
2346 div: q || null,
2347 mod: a
2348 };
2349 };
2350
2351 // NOTE: 1) `mode` can be set to `mod` to request mod only,
2352 // to `div` to request div only, or be absent to
2353 // request both div & mod
2354 // 2) `positive` is true if unsigned mod is requested
2355 BN.prototype.divmod = function divmod (num, mode, positive) {
2356 assert(!num.isZero());
2357
2358 if (this.isZero()) {
2359 return {
2360 div: new BN(0),
2361 mod: new BN(0)
2362 };
2363 }
2364
2365 var div, mod, res;
2366 if (this.negative !== 0 && num.negative === 0) {
2367 res = this.neg().divmod(num, mode);
2368
2369 if (mode !== 'mod') {
2370 div = res.div.neg();
2371 }
2372
2373 if (mode !== 'div') {
2374 mod = res.mod.neg();
2375 if (positive && mod.negative !== 0) {
2376 mod.iadd(num);
2377 }
2378 }
2379
2380 return {
2381 div: div,
2382 mod: mod
2383 };
2384 }
2385
2386 if (this.negative === 0 && num.negative !== 0) {
2387 res = this.divmod(num.neg(), mode);
2388
2389 if (mode !== 'mod') {
2390 div = res.div.neg();
2391 }
2392
2393 return {
2394 div: div,
2395 mod: res.mod
2396 };
2397 }
2398
2399 if ((this.negative & num.negative) !== 0) {
2400 res = this.neg().divmod(num.neg(), mode);
2401
2402 if (mode !== 'div') {
2403 mod = res.mod.neg();
2404 if (positive && mod.negative !== 0) {
2405 mod.isub(num);
2406 }
2407 }
2408
2409 return {
2410 div: res.div,
2411 mod: mod
2412 };
2413 }
2414
2415 // Both numbers are positive at this point
2416
2417 // Strip both numbers to approximate shift value
2418 if (num.length > this.length || this.cmp(num) < 0) {
2419 return {
2420 div: new BN(0),
2421 mod: this
2422 };
2423 }
2424
2425 // Very short reduction
2426 if (num.length === 1) {
2427 if (mode === 'div') {
2428 return {
2429 div: this.divn(num.words[0]),
2430 mod: null
2431 };
2432 }
2433
2434 if (mode === 'mod') {
2435 return {
2436 div: null,
2437 mod: new BN(this.modn(num.words[0]))
2438 };
2439 }
2440
2441 return {
2442 div: this.divn(num.words[0]),
2443 mod: new BN(this.modn(num.words[0]))
2444 };
2445 }
2446
2447 return this._wordDiv(num, mode);
2448 };
2449
2450 // Find `this` / `num`
2451 BN.prototype.div = function div (num) {
2452 return this.divmod(num, 'div', false).div;
2453 };
2454
2455 // Find `this` % `num`
2456 BN.prototype.mod = function mod (num) {
2457 return this.divmod(num, 'mod', false).mod;
2458 };
2459
2460 BN.prototype.umod = function umod (num) {
2461 return this.divmod(num, 'mod', true).mod;
2462 };
2463
2464 // Find Round(`this` / `num`)
2465 BN.prototype.divRound = function divRound (num) {
2466 var dm = this.divmod(num);
2467
2468 // Fast case - exact division
2469 if (dm.mod.isZero()) return dm.div;
2470
2471 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
2472
2473 var half = num.ushrn(1);
2474 var r2 = num.andln(1);
2475 var cmp = mod.cmp(half);
2476
2477 // Round down
2478 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
2479
2480 // Round up
2481 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
2482 };
2483
2484 BN.prototype.modn = function modn (num) {
2485 assert(num <= 0x3ffffff);
2486 var p = (1 << 26) % num;
2487
2488 var acc = 0;
2489 for (var i = this.length - 1; i >= 0; i--) {
2490 acc = (p * acc + (this.words[i] | 0)) % num;
2491 }
2492
2493 return acc;
2494 };
2495
2496 // In-place division by number
2497 BN.prototype.idivn = function idivn (num) {
2498 assert(num <= 0x3ffffff);
2499
2500 var carry = 0;
2501 for (var i = this.length - 1; i >= 0; i--) {
2502 var w = (this.words[i] | 0) + carry * 0x4000000;
2503 this.words[i] = (w / num) | 0;
2504 carry = w % num;
2505 }
2506
2507 return this.strip();
2508 };
2509
2510 BN.prototype.divn = function divn (num) {
2511 return this.clone().idivn(num);
2512 };
2513
2514 BN.prototype.egcd = function egcd (p) {
2515 assert(p.negative === 0);
2516 assert(!p.isZero());
2517
2518 var x = this;
2519 var y = p.clone();
2520
2521 if (x.negative !== 0) {
2522 x = x.umod(p);
2523 } else {
2524 x = x.clone();
2525 }
2526
2527 // A * x + B * y = x
2528 var A = new BN(1);
2529 var B = new BN(0);
2530
2531 // C * x + D * y = y
2532 var C = new BN(0);
2533 var D = new BN(1);
2534
2535 var g = 0;
2536
2537 while (x.isEven() && y.isEven()) {
2538 x.iushrn(1);
2539 y.iushrn(1);
2540 ++g;
2541 }
2542
2543 var yp = y.clone();
2544 var xp = x.clone();
2545
2546 while (!x.isZero()) {
2547 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
2548 if (i > 0) {
2549 x.iushrn(i);
2550 while (i-- > 0) {
2551 if (A.isOdd() || B.isOdd()) {
2552 A.iadd(yp);
2553 B.isub(xp);
2554 }
2555
2556 A.iushrn(1);
2557 B.iushrn(1);
2558 }
2559 }
2560
2561 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
2562 if (j > 0) {
2563 y.iushrn(j);
2564 while (j-- > 0) {
2565 if (C.isOdd() || D.isOdd()) {
2566 C.iadd(yp);
2567 D.isub(xp);
2568 }
2569
2570 C.iushrn(1);
2571 D.iushrn(1);
2572 }
2573 }
2574
2575 if (x.cmp(y) >= 0) {
2576 x.isub(y);
2577 A.isub(C);
2578 B.isub(D);
2579 } else {
2580 y.isub(x);
2581 C.isub(A);
2582 D.isub(B);
2583 }
2584 }
2585
2586 return {
2587 a: C,
2588 b: D,
2589 gcd: y.iushln(g)
2590 };
2591 };
2592
2593 // This is reduced incarnation of the binary EEA
2594 // above, designated to invert members of the
2595 // _prime_ fields F(p) at a maximal speed
2596 BN.prototype._invmp = function _invmp (p) {
2597 assert(p.negative === 0);
2598 assert(!p.isZero());
2599
2600 var a = this;
2601 var b = p.clone();
2602
2603 if (a.negative !== 0) {
2604 a = a.umod(p);
2605 } else {
2606 a = a.clone();
2607 }
2608
2609 var x1 = new BN(1);
2610 var x2 = new BN(0);
2611
2612 var delta = b.clone();
2613
2614 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
2615 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
2616 if (i > 0) {
2617 a.iushrn(i);
2618 while (i-- > 0) {
2619 if (x1.isOdd()) {
2620 x1.iadd(delta);
2621 }
2622
2623 x1.iushrn(1);
2624 }
2625 }
2626
2627 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
2628 if (j > 0) {
2629 b.iushrn(j);
2630 while (j-- > 0) {
2631 if (x2.isOdd()) {
2632 x2.iadd(delta);
2633 }
2634
2635 x2.iushrn(1);
2636 }
2637 }
2638
2639 if (a.cmp(b) >= 0) {
2640 a.isub(b);
2641 x1.isub(x2);
2642 } else {
2643 b.isub(a);
2644 x2.isub(x1);
2645 }
2646 }
2647
2648 var res;
2649 if (a.cmpn(1) === 0) {
2650 res = x1;
2651 } else {
2652 res = x2;
2653 }
2654
2655 if (res.cmpn(0) < 0) {
2656 res.iadd(p);
2657 }
2658
2659 return res;
2660 };
2661
2662 BN.prototype.gcd = function gcd (num) {
2663 if (this.isZero()) return num.abs();
2664 if (num.isZero()) return this.abs();
2665
2666 var a = this.clone();
2667 var b = num.clone();
2668 a.negative = 0;
2669 b.negative = 0;
2670
2671 // Remove common factor of two
2672 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
2673 a.iushrn(1);
2674 b.iushrn(1);
2675 }
2676
2677 do {
2678 while (a.isEven()) {
2679 a.iushrn(1);
2680 }
2681 while (b.isEven()) {
2682 b.iushrn(1);
2683 }
2684
2685 var r = a.cmp(b);
2686 if (r < 0) {
2687 // Swap `a` and `b` to make `a` always bigger than `b`
2688 var t = a;
2689 a = b;
2690 b = t;
2691 } else if (r === 0 || b.cmpn(1) === 0) {
2692 break;
2693 }
2694
2695 a.isub(b);
2696 } while (true);
2697
2698 return b.iushln(shift);
2699 };
2700
2701 // Invert number in the field F(num)
2702 BN.prototype.invm = function invm (num) {
2703 return this.egcd(num).a.umod(num);
2704 };
2705
2706 BN.prototype.isEven = function isEven () {
2707 return (this.words[0] & 1) === 0;
2708 };
2709
2710 BN.prototype.isOdd = function isOdd () {
2711 return (this.words[0] & 1) === 1;
2712 };
2713
2714 // And first word and num
2715 BN.prototype.andln = function andln (num) {
2716 return this.words[0] & num;
2717 };
2718
2719 // Increment at the bit position in-line
2720 BN.prototype.bincn = function bincn (bit) {
2721 assert(typeof bit === 'number');
2722 var r = bit % 26;
2723 var s = (bit - r) / 26;
2724 var q = 1 << r;
2725
2726 // Fast case: bit is much higher than all existing words
2727 if (this.length <= s) {
2728 this._expand(s + 1);
2729 this.words[s] |= q;
2730 return this;
2731 }
2732
2733 // Add bit and propagate, if needed
2734 var carry = q;
2735 for (var i = s; carry !== 0 && i < this.length; i++) {
2736 var w = this.words[i] | 0;
2737 w += carry;
2738 carry = w >>> 26;
2739 w &= 0x3ffffff;
2740 this.words[i] = w;
2741 }
2742 if (carry !== 0) {
2743 this.words[i] = carry;
2744 this.length++;
2745 }
2746 return this;
2747 };
2748
2749 BN.prototype.isZero = function isZero () {
2750 return this.length === 1 && this.words[0] === 0;
2751 };
2752
2753 BN.prototype.cmpn = function cmpn (num) {
2754 var negative = num < 0;
2755
2756 if (this.negative !== 0 && !negative) return -1;
2757 if (this.negative === 0 && negative) return 1;
2758
2759 this.strip();
2760
2761 var res;
2762 if (this.length > 1) {
2763 res = 1;
2764 } else {
2765 if (negative) {
2766 num = -num;
2767 }
2768
2769 assert(num <= 0x3ffffff, 'Number is too big');
2770
2771 var w = this.words[0] | 0;
2772 res = w === num ? 0 : w < num ? -1 : 1;
2773 }
2774 if (this.negative !== 0) return -res | 0;
2775 return res;
2776 };
2777
2778 // Compare two numbers and return:
2779 // 1 - if `this` > `num`
2780 // 0 - if `this` == `num`
2781 // -1 - if `this` < `num`
2782 BN.prototype.cmp = function cmp (num) {
2783 if (this.negative !== 0 && num.negative === 0) return -1;
2784 if (this.negative === 0 && num.negative !== 0) return 1;
2785
2786 var res = this.ucmp(num);
2787 if (this.negative !== 0) return -res | 0;
2788 return res;
2789 };
2790
2791 // Unsigned comparison
2792 BN.prototype.ucmp = function ucmp (num) {
2793 // At this point both numbers have the same sign
2794 if (this.length > num.length) return 1;
2795 if (this.length < num.length) return -1;
2796
2797 var res = 0;
2798 for (var i = this.length - 1; i >= 0; i--) {
2799 var a = this.words[i] | 0;
2800 var b = num.words[i] | 0;
2801
2802 if (a === b) continue;
2803 if (a < b) {
2804 res = -1;
2805 } else if (a > b) {
2806 res = 1;
2807 }
2808 break;
2809 }
2810 return res;
2811 };
2812
2813 BN.prototype.gtn = function gtn (num) {
2814 return this.cmpn(num) === 1;
2815 };
2816
2817 BN.prototype.gt = function gt (num) {
2818 return this.cmp(num) === 1;
2819 };
2820
2821 BN.prototype.gten = function gten (num) {
2822 return this.cmpn(num) >= 0;
2823 };
2824
2825 BN.prototype.gte = function gte (num) {
2826 return this.cmp(num) >= 0;
2827 };
2828
2829 BN.prototype.ltn = function ltn (num) {
2830 return this.cmpn(num) === -1;
2831 };
2832
2833 BN.prototype.lt = function lt (num) {
2834 return this.cmp(num) === -1;
2835 };
2836
2837 BN.prototype.lten = function lten (num) {
2838 return this.cmpn(num) <= 0;
2839 };
2840
2841 BN.prototype.lte = function lte (num) {
2842 return this.cmp(num) <= 0;
2843 };
2844
2845 BN.prototype.eqn = function eqn (num) {
2846 return this.cmpn(num) === 0;
2847 };
2848
2849 BN.prototype.eq = function eq (num) {
2850 return this.cmp(num) === 0;
2851 };
2852
2853 //
2854 // A reduce context, could be using montgomery or something better, depending
2855 // on the `m` itself.
2856 //
2857 BN.red = function red (num) {
2858 return new Red(num);
2859 };
2860
2861 BN.prototype.toRed = function toRed (ctx) {
2862 assert(!this.red, 'Already a number in reduction context');
2863 assert(this.negative === 0, 'red works only with positives');
2864 return ctx.convertTo(this)._forceRed(ctx);
2865 };
2866
2867 BN.prototype.fromRed = function fromRed () {
2868 assert(this.red, 'fromRed works only with numbers in reduction context');
2869 return this.red.convertFrom(this);
2870 };
2871
2872 BN.prototype._forceRed = function _forceRed (ctx) {
2873 this.red = ctx;
2874 return this;
2875 };
2876
2877 BN.prototype.forceRed = function forceRed (ctx) {
2878 assert(!this.red, 'Already a number in reduction context');
2879 return this._forceRed(ctx);
2880 };
2881
2882 BN.prototype.redAdd = function redAdd (num) {
2883 assert(this.red, 'redAdd works only with red numbers');
2884 return this.red.add(this, num);
2885 };
2886
2887 BN.prototype.redIAdd = function redIAdd (num) {
2888 assert(this.red, 'redIAdd works only with red numbers');
2889 return this.red.iadd(this, num);
2890 };
2891
2892 BN.prototype.redSub = function redSub (num) {
2893 assert(this.red, 'redSub works only with red numbers');
2894 return this.red.sub(this, num);
2895 };
2896
2897 BN.prototype.redISub = function redISub (num) {
2898 assert(this.red, 'redISub works only with red numbers');
2899 return this.red.isub(this, num);
2900 };
2901
2902 BN.prototype.redShl = function redShl (num) {
2903 assert(this.red, 'redShl works only with red numbers');
2904 return this.red.shl(this, num);
2905 };
2906
2907 BN.prototype.redMul = function redMul (num) {
2908 assert(this.red, 'redMul works only with red numbers');
2909 this.red._verify2(this, num);
2910 return this.red.mul(this, num);
2911 };
2912
2913 BN.prototype.redIMul = function redIMul (num) {
2914 assert(this.red, 'redMul works only with red numbers');
2915 this.red._verify2(this, num);
2916 return this.red.imul(this, num);
2917 };
2918
2919 BN.prototype.redSqr = function redSqr () {
2920 assert(this.red, 'redSqr works only with red numbers');
2921 this.red._verify1(this);
2922 return this.red.sqr(this);
2923 };
2924
2925 BN.prototype.redISqr = function redISqr () {
2926 assert(this.red, 'redISqr works only with red numbers');
2927 this.red._verify1(this);
2928 return this.red.isqr(this);
2929 };
2930
2931 // Square root over p
2932 BN.prototype.redSqrt = function redSqrt () {
2933 assert(this.red, 'redSqrt works only with red numbers');
2934 this.red._verify1(this);
2935 return this.red.sqrt(this);
2936 };
2937
2938 BN.prototype.redInvm = function redInvm () {
2939 assert(this.red, 'redInvm works only with red numbers');
2940 this.red._verify1(this);
2941 return this.red.invm(this);
2942 };
2943
2944 // Return negative clone of `this` % `red modulo`
2945 BN.prototype.redNeg = function redNeg () {
2946 assert(this.red, 'redNeg works only with red numbers');
2947 this.red._verify1(this);
2948 return this.red.neg(this);
2949 };
2950
2951 BN.prototype.redPow = function redPow (num) {
2952 assert(this.red && !num.red, 'redPow(normalNum)');
2953 this.red._verify1(this);
2954 return this.red.pow(this, num);
2955 };
2956
2957 // Prime numbers with efficient reduction
2958 var primes = {
2959 k256: null,
2960 p224: null,
2961 p192: null,
2962 p25519: null
2963 };
2964
2965 // Pseudo-Mersenne prime
2966 function MPrime (name, p) {
2967 // P = 2 ^ N - K
2968 this.name = name;
2969 this.p = new BN(p, 16);
2970 this.n = this.p.bitLength();
2971 this.k = new BN(1).iushln(this.n).isub(this.p);
2972
2973 this.tmp = this._tmp();
2974 }
2975
2976 MPrime.prototype._tmp = function _tmp () {
2977 var tmp = new BN(null);
2978 tmp.words = new Array(Math.ceil(this.n / 13));
2979 return tmp;
2980 };
2981
2982 MPrime.prototype.ireduce = function ireduce (num) {
2983 // Assumes that `num` is less than `P^2`
2984 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
2985 var r = num;
2986 var rlen;
2987
2988 do {
2989 this.split(r, this.tmp);
2990 r = this.imulK(r);
2991 r = r.iadd(this.tmp);
2992 rlen = r.bitLength();
2993 } while (rlen > this.n);
2994
2995 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
2996 if (cmp === 0) {
2997 r.words[0] = 0;
2998 r.length = 1;
2999 } else if (cmp > 0) {
3000 r.isub(this.p);
3001 } else {
3002 if (r.strip !== undefined) {
3003 // r is BN v4 instance
3004 r.strip();
3005 } else {
3006 // r is BN v5 instance
3007 r._strip();
3008 }
3009 }
3010
3011 return r;
3012 };
3013
3014 MPrime.prototype.split = function split (input, out) {
3015 input.iushrn(this.n, 0, out);
3016 };
3017
3018 MPrime.prototype.imulK = function imulK (num) {
3019 return num.imul(this.k);
3020 };
3021
3022 function K256 () {
3023 MPrime.call(
3024 this,
3025 'k256',
3026 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
3027 }
3028 inherits(K256, MPrime);
3029
3030 K256.prototype.split = function split (input, output) {
3031 // 256 = 9 * 26 + 22
3032 var mask = 0x3fffff;
3033
3034 var outLen = Math.min(input.length, 9);
3035 for (var i = 0; i < outLen; i++) {
3036 output.words[i] = input.words[i];
3037 }
3038 output.length = outLen;
3039
3040 if (input.length <= 9) {
3041 input.words[0] = 0;
3042 input.length = 1;
3043 return;
3044 }
3045
3046 // Shift by 9 limbs
3047 var prev = input.words[9];
3048 output.words[output.length++] = prev & mask;
3049
3050 for (i = 10; i < input.length; i++) {
3051 var next = input.words[i] | 0;
3052 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
3053 prev = next;
3054 }
3055 prev >>>= 22;
3056 input.words[i - 10] = prev;
3057 if (prev === 0 && input.length > 10) {
3058 input.length -= 10;
3059 } else {
3060 input.length -= 9;
3061 }
3062 };
3063
3064 K256.prototype.imulK = function imulK (num) {
3065 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
3066 num.words[num.length] = 0;
3067 num.words[num.length + 1] = 0;
3068 num.length += 2;
3069
3070 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
3071 var lo = 0;
3072 for (var i = 0; i < num.length; i++) {
3073 var w = num.words[i] | 0;
3074 lo += w * 0x3d1;
3075 num.words[i] = lo & 0x3ffffff;
3076 lo = w * 0x40 + ((lo / 0x4000000) | 0);
3077 }
3078
3079 // Fast length reduction
3080 if (num.words[num.length - 1] === 0) {
3081 num.length--;
3082 if (num.words[num.length - 1] === 0) {
3083 num.length--;
3084 }
3085 }
3086 return num;
3087 };
3088
3089 function P224 () {
3090 MPrime.call(
3091 this,
3092 'p224',
3093 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
3094 }
3095 inherits(P224, MPrime);
3096
3097 function P192 () {
3098 MPrime.call(
3099 this,
3100 'p192',
3101 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
3102 }
3103 inherits(P192, MPrime);
3104
3105 function P25519 () {
3106 // 2 ^ 255 - 19
3107 MPrime.call(
3108 this,
3109 '25519',
3110 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
3111 }
3112 inherits(P25519, MPrime);
3113
3114 P25519.prototype.imulK = function imulK (num) {
3115 // K = 0x13
3116 var carry = 0;
3117 for (var i = 0; i < num.length; i++) {
3118 var hi = (num.words[i] | 0) * 0x13 + carry;
3119 var lo = hi & 0x3ffffff;
3120 hi >>>= 26;
3121
3122 num.words[i] = lo;
3123 carry = hi;
3124 }
3125 if (carry !== 0) {
3126 num.words[num.length++] = carry;
3127 }
3128 return num;
3129 };
3130
3131 // Exported mostly for testing purposes, use plain name instead
3132 BN._prime = function prime (name) {
3133 // Cached version of prime
3134 if (primes[name]) return primes[name];
3135
3136 var prime;
3137 if (name === 'k256') {
3138 prime = new K256();
3139 } else if (name === 'p224') {
3140 prime = new P224();
3141 } else if (name === 'p192') {
3142 prime = new P192();
3143 } else if (name === 'p25519') {
3144 prime = new P25519();
3145 } else {
3146 throw new Error('Unknown prime ' + name);
3147 }
3148 primes[name] = prime;
3149
3150 return prime;
3151 };
3152
3153 //
3154 // Base reduction engine
3155 //
3156 function Red (m) {
3157 if (typeof m === 'string') {
3158 var prime = BN._prime(m);
3159 this.m = prime.p;
3160 this.prime = prime;
3161 } else {
3162 assert(m.gtn(1), 'modulus must be greater than 1');
3163 this.m = m;
3164 this.prime = null;
3165 }
3166 }
3167
3168 Red.prototype._verify1 = function _verify1 (a) {
3169 assert(a.negative === 0, 'red works only with positives');
3170 assert(a.red, 'red works only with red numbers');
3171 };
3172
3173 Red.prototype._verify2 = function _verify2 (a, b) {
3174 assert((a.negative | b.negative) === 0, 'red works only with positives');
3175 assert(a.red && a.red === b.red,
3176 'red works only with red numbers');
3177 };
3178
3179 Red.prototype.imod = function imod (a) {
3180 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
3181 return a.umod(this.m)._forceRed(this);
3182 };
3183
3184 Red.prototype.neg = function neg (a) {
3185 if (a.isZero()) {
3186 return a.clone();
3187 }
3188
3189 return this.m.sub(a)._forceRed(this);
3190 };
3191
3192 Red.prototype.add = function add (a, b) {
3193 this._verify2(a, b);
3194
3195 var res = a.add(b);
3196 if (res.cmp(this.m) >= 0) {
3197 res.isub(this.m);
3198 }
3199 return res._forceRed(this);
3200 };
3201
3202 Red.prototype.iadd = function iadd (a, b) {
3203 this._verify2(a, b);
3204
3205 var res = a.iadd(b);
3206 if (res.cmp(this.m) >= 0) {
3207 res.isub(this.m);
3208 }
3209 return res;
3210 };
3211
3212 Red.prototype.sub = function sub (a, b) {
3213 this._verify2(a, b);
3214
3215 var res = a.sub(b);
3216 if (res.cmpn(0) < 0) {
3217 res.iadd(this.m);
3218 }
3219 return res._forceRed(this);
3220 };
3221
3222 Red.prototype.isub = function isub (a, b) {
3223 this._verify2(a, b);
3224
3225 var res = a.isub(b);
3226 if (res.cmpn(0) < 0) {
3227 res.iadd(this.m);
3228 }
3229 return res;
3230 };
3231
3232 Red.prototype.shl = function shl (a, num) {
3233 this._verify1(a);
3234 return this.imod(a.ushln(num));
3235 };
3236
3237 Red.prototype.imul = function imul (a, b) {
3238 this._verify2(a, b);
3239 return this.imod(a.imul(b));
3240 };
3241
3242 Red.prototype.mul = function mul (a, b) {
3243 this._verify2(a, b);
3244 return this.imod(a.mul(b));
3245 };
3246
3247 Red.prototype.isqr = function isqr (a) {
3248 return this.imul(a, a.clone());
3249 };
3250
3251 Red.prototype.sqr = function sqr (a) {
3252 return this.mul(a, a);
3253 };
3254
3255 Red.prototype.sqrt = function sqrt (a) {
3256 if (a.isZero()) return a.clone();
3257
3258 var mod3 = this.m.andln(3);
3259 assert(mod3 % 2 === 1);
3260
3261 // Fast case
3262 if (mod3 === 3) {
3263 var pow = this.m.add(new BN(1)).iushrn(2);
3264 return this.pow(a, pow);
3265 }
3266
3267 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
3268 //
3269 // Find Q and S, that Q * 2 ^ S = (P - 1)
3270 var q = this.m.subn(1);
3271 var s = 0;
3272 while (!q.isZero() && q.andln(1) === 0) {
3273 s++;
3274 q.iushrn(1);
3275 }
3276 assert(!q.isZero());
3277
3278 var one = new BN(1).toRed(this);
3279 var nOne = one.redNeg();
3280
3281 // Find quadratic non-residue
3282 // NOTE: Max is such because of generalized Riemann hypothesis.
3283 var lpow = this.m.subn(1).iushrn(1);
3284 var z = this.m.bitLength();
3285 z = new BN(2 * z * z).toRed(this);
3286
3287 while (this.pow(z, lpow).cmp(nOne) !== 0) {
3288 z.redIAdd(nOne);
3289 }
3290
3291 var c = this.pow(z, q);
3292 var r = this.pow(a, q.addn(1).iushrn(1));
3293 var t = this.pow(a, q);
3294 var m = s;
3295 while (t.cmp(one) !== 0) {
3296 var tmp = t;
3297 for (var i = 0; tmp.cmp(one) !== 0; i++) {
3298 tmp = tmp.redSqr();
3299 }
3300 assert(i < m);
3301 var b = this.pow(c, new BN(1).iushln(m - i - 1));
3302
3303 r = r.redMul(b);
3304 c = b.redSqr();
3305 t = t.redMul(c);
3306 m = i;
3307 }
3308
3309 return r;
3310 };
3311
3312 Red.prototype.invm = function invm (a) {
3313 var inv = a._invmp(this.m);
3314 if (inv.negative !== 0) {
3315 inv.negative = 0;
3316 return this.imod(inv).redNeg();
3317 } else {
3318 return this.imod(inv);
3319 }
3320 };
3321
3322 Red.prototype.pow = function pow (a, num) {
3323 if (num.isZero()) return new BN(1).toRed(this);
3324 if (num.cmpn(1) === 0) return a.clone();
3325
3326 var windowSize = 4;
3327 var wnd = new Array(1 << windowSize);
3328 wnd[0] = new BN(1).toRed(this);
3329 wnd[1] = a;
3330 for (var i = 2; i < wnd.length; i++) {
3331 wnd[i] = this.mul(wnd[i - 1], a);
3332 }
3333
3334 var res = wnd[0];
3335 var current = 0;
3336 var currentLen = 0;
3337 var start = num.bitLength() % 26;
3338 if (start === 0) {
3339 start = 26;
3340 }
3341
3342 for (i = num.length - 1; i >= 0; i--) {
3343 var word = num.words[i];
3344 for (var j = start - 1; j >= 0; j--) {
3345 var bit = (word >> j) & 1;
3346 if (res !== wnd[0]) {
3347 res = this.sqr(res);
3348 }
3349
3350 if (bit === 0 && current === 0) {
3351 currentLen = 0;
3352 continue;
3353 }
3354
3355 current <<= 1;
3356 current |= bit;
3357 currentLen++;
3358 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
3359
3360 res = this.mul(res, wnd[current]);
3361 currentLen = 0;
3362 current = 0;
3363 }
3364 start = 26;
3365 }
3366
3367 return res;
3368 };
3369
3370 Red.prototype.convertTo = function convertTo (num) {
3371 var r = num.umod(this.m);
3372
3373 return r === num ? r.clone() : r;
3374 };
3375
3376 Red.prototype.convertFrom = function convertFrom (num) {
3377 var res = num.clone();
3378 res.red = null;
3379 return res;
3380 };
3381
3382 //
3383 // Montgomery method engine
3384 //
3385
3386 BN.mont = function mont (num) {
3387 return new Mont(num);
3388 };
3389
3390 function Mont (m) {
3391 Red.call(this, m);
3392
3393 this.shift = this.m.bitLength();
3394 if (this.shift % 26 !== 0) {
3395 this.shift += 26 - (this.shift % 26);
3396 }
3397
3398 this.r = new BN(1).iushln(this.shift);
3399 this.r2 = this.imod(this.r.sqr());
3400 this.rinv = this.r._invmp(this.m);
3401
3402 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
3403 this.minv = this.minv.umod(this.r);
3404 this.minv = this.r.sub(this.minv);
3405 }
3406 inherits(Mont, Red);
3407
3408 Mont.prototype.convertTo = function convertTo (num) {
3409 return this.imod(num.ushln(this.shift));
3410 };
3411
3412 Mont.prototype.convertFrom = function convertFrom (num) {
3413 var r = this.imod(num.mul(this.rinv));
3414 r.red = null;
3415 return r;
3416 };
3417
3418 Mont.prototype.imul = function imul (a, b) {
3419 if (a.isZero() || b.isZero()) {
3420 a.words[0] = 0;
3421 a.length = 1;
3422 return a;
3423 }
3424
3425 var t = a.imul(b);
3426 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
3427 var u = t.isub(c).iushrn(this.shift);
3428 var res = u;
3429
3430 if (u.cmp(this.m) >= 0) {
3431 res = u.isub(this.m);
3432 } else if (u.cmpn(0) < 0) {
3433 res = u.iadd(this.m);
3434 }
3435
3436 return res._forceRed(this);
3437 };
3438
3439 Mont.prototype.mul = function mul (a, b) {
3440 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
3441
3442 var t = a.mul(b);
3443 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
3444 var u = t.isub(c).iushrn(this.shift);
3445 var res = u;
3446 if (u.cmp(this.m) >= 0) {
3447 res = u.isub(this.m);
3448 } else if (u.cmpn(0) < 0) {
3449 res = u.iadd(this.m);
3450 }
3451
3452 return res._forceRed(this);
3453 };
3454
3455 Mont.prototype.invm = function invm (a) {
3456 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
3457 var res = this.imod(a._invmp(this.m).mul(this.r2));
3458 return res._forceRed(this);
3459 };
3460})('object' === 'undefined' || module, commonjsGlobal);
3461});
3462var bn_1 = bn.BN;
3463
3464const version = "logger/5.0.4";
3465
3466"use strict";
3467let _permanentCensorErrors = false;
3468let _censorErrors = false;
3469const LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 };
3470let _logLevel = LogLevels["default"];
3471let _globalLogger = null;
3472function _checkNormalize() {
3473 try {
3474 const missing = [];
3475 // Make sure all forms of normalization are supported
3476 ["NFD", "NFC", "NFKD", "NFKC"].forEach((form) => {
3477 try {
3478 if ("test".normalize(form) !== "test") {
3479 throw new Error("bad normalize");
3480 }
3481 ;
3482 }
3483 catch (error) {
3484 missing.push(form);
3485 }
3486 });
3487 if (missing.length) {
3488 throw new Error("missing " + missing.join(", "));
3489 }
3490 if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) {
3491 throw new Error("broken implementation");
3492 }
3493 }
3494 catch (error) {
3495 return error.message;
3496 }
3497 return null;
3498}
3499const _normalizeError = _checkNormalize();
3500var LogLevel;
3501(function (LogLevel) {
3502 LogLevel["DEBUG"] = "DEBUG";
3503 LogLevel["INFO"] = "INFO";
3504 LogLevel["WARNING"] = "WARNING";
3505 LogLevel["ERROR"] = "ERROR";
3506 LogLevel["OFF"] = "OFF";
3507})(LogLevel || (LogLevel = {}));
3508var ErrorCode;
3509(function (ErrorCode) {
3510 ///////////////////
3511 // Generic Errors
3512 // Unknown Error
3513 ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
3514 // Not Implemented
3515 ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
3516 // Unsupported Operation
3517 // - operation
3518 ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION";
3519 // Network Error (i.e. Ethereum Network, such as an invalid chain ID)
3520 // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown)
3521 ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
3522 // Some sort of bad response from the server
3523 ErrorCode["SERVER_ERROR"] = "SERVER_ERROR";
3524 // Timeout
3525 ErrorCode["TIMEOUT"] = "TIMEOUT";
3526 ///////////////////
3527 // Operational Errors
3528 // Buffer Overrun
3529 ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN";
3530 // Numeric Fault
3531 // - operation: the operation being executed
3532 // - fault: the reason this faulted
3533 ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT";
3534 ///////////////////
3535 // Argument Errors
3536 // Missing new operator to an object
3537 // - name: The name of the class
3538 ErrorCode["MISSING_NEW"] = "MISSING_NEW";
3539 // Invalid argument (e.g. value is incompatible with type) to a function:
3540 // - argument: The argument name that was invalid
3541 // - value: The value of the argument
3542 ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
3543 // Missing argument to a function:
3544 // - count: The number of arguments received
3545 // - expectedCount: The number of arguments expected
3546 ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT";
3547 // Too many arguments
3548 // - count: The number of arguments received
3549 // - expectedCount: The number of arguments expected
3550 ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT";
3551 ///////////////////
3552 // Blockchain Errors
3553 // Call exception
3554 // - transaction: the transaction
3555 // - address?: the contract address
3556 // - args?: The arguments passed into the function
3557 // - method?: The Solidity method signature
3558 // - errorSignature?: The EIP848 error signature
3559 // - errorArgs?: The EIP848 error parameters
3560 // - reason: The reason (only for EIP848 "Error(string)")
3561 ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION";
3562 // Insufficien funds (< value + gasLimit * gasPrice)
3563 // - transaction: the transaction attempted
3564 ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
3565 // Nonce has already been used
3566 // - transaction: the transaction attempted
3567 ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED";
3568 // The replacement fee for the transaction is too low
3569 // - transaction: the transaction attempted
3570 ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED";
3571 // The gas limit could not be estimated
3572 // - transaction: the transaction passed to estimateGas
3573 ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
3574})(ErrorCode || (ErrorCode = {}));
3575;
3576class Logger {
3577 constructor(version) {
3578 Object.defineProperty(this, "version", {
3579 enumerable: true,
3580 value: version,
3581 writable: false
3582 });
3583 }
3584 _log(logLevel, args) {
3585 const level = logLevel.toLowerCase();
3586 if (LogLevels[level] == null) {
3587 this.throwArgumentError("invalid log level name", "logLevel", logLevel);
3588 }
3589 if (_logLevel > LogLevels[level]) {
3590 return;
3591 }
3592 console.log.apply(console, args);
3593 }
3594 debug(...args) {
3595 this._log(Logger.levels.DEBUG, args);
3596 }
3597 info(...args) {
3598 this._log(Logger.levels.INFO, args);
3599 }
3600 warn(...args) {
3601 this._log(Logger.levels.WARNING, args);
3602 }
3603 makeError(message, code, params) {
3604 // Errors are being censored
3605 if (_censorErrors) {
3606 return this.makeError("censored error", code, {});
3607 }
3608 if (!code) {
3609 code = Logger.errors.UNKNOWN_ERROR;
3610 }
3611 if (!params) {
3612 params = {};
3613 }
3614 const messageDetails = [];
3615 Object.keys(params).forEach((key) => {
3616 try {
3617 messageDetails.push(key + "=" + JSON.stringify(params[key]));
3618 }
3619 catch (error) {
3620 messageDetails.push(key + "=" + JSON.stringify(params[key].toString()));
3621 }
3622 });
3623 messageDetails.push(`code=${code}`);
3624 messageDetails.push(`version=${this.version}`);
3625 const reason = message;
3626 if (messageDetails.length) {
3627 message += " (" + messageDetails.join(", ") + ")";
3628 }
3629 // @TODO: Any??
3630 const error = new Error(message);
3631 error.reason = reason;
3632 error.code = code;
3633 Object.keys(params).forEach(function (key) {
3634 error[key] = params[key];
3635 });
3636 return error;
3637 }
3638 throwError(message, code, params) {
3639 throw this.makeError(message, code, params);
3640 }
3641 throwArgumentError(message, name, value) {
3642 return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {
3643 argument: name,
3644 value: value
3645 });
3646 }
3647 assert(condition, message, code, params) {
3648 if (!!condition) {
3649 return;
3650 }
3651 this.throwError(message, code, params);
3652 }
3653 assertArgument(condition, message, name, value) {
3654 if (!!condition) {
3655 return;
3656 }
3657 this.throwArgumentError(message, name, value);
3658 }
3659 checkNormalize(message) {
3660 if (message == null) {
3661 message = "platform missing String.prototype.normalize";
3662 }
3663 if (_normalizeError) {
3664 this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, {
3665 operation: "String.prototype.normalize", form: _normalizeError
3666 });
3667 }
3668 }
3669 checkSafeUint53(value, message) {
3670 if (typeof (value) !== "number") {
3671 return;
3672 }
3673 if (message == null) {
3674 message = "value not safe";
3675 }
3676 if (value < 0 || value >= 0x1fffffffffffff) {
3677 this.throwError(message, Logger.errors.NUMERIC_FAULT, {
3678 operation: "checkSafeInteger",
3679 fault: "out-of-safe-range",
3680 value: value
3681 });
3682 }
3683 if (value % 1) {
3684 this.throwError(message, Logger.errors.NUMERIC_FAULT, {
3685 operation: "checkSafeInteger",
3686 fault: "non-integer",
3687 value: value
3688 });
3689 }
3690 }
3691 checkArgumentCount(count, expectedCount, message) {
3692 if (message) {
3693 message = ": " + message;
3694 }
3695 else {
3696 message = "";
3697 }
3698 if (count < expectedCount) {
3699 this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, {
3700 count: count,
3701 expectedCount: expectedCount
3702 });
3703 }
3704 if (count > expectedCount) {
3705 this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, {
3706 count: count,
3707 expectedCount: expectedCount
3708 });
3709 }
3710 }
3711 checkNew(target, kind) {
3712 if (target === Object || target == null) {
3713 this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
3714 }
3715 }
3716 checkAbstract(target, kind) {
3717 if (target === kind) {
3718 this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" });
3719 }
3720 else if (target === Object || target == null) {
3721 this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
3722 }
3723 }
3724 static globalLogger() {
3725 if (!_globalLogger) {
3726 _globalLogger = new Logger(version);
3727 }
3728 return _globalLogger;
3729 }
3730 static setCensorship(censorship, permanent) {
3731 if (!censorship && permanent) {
3732 this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, {
3733 operation: "setCensorship"
3734 });
3735 }
3736 if (_permanentCensorErrors) {
3737 if (!censorship) {
3738 return;
3739 }
3740 this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, {
3741 operation: "setCensorship"
3742 });
3743 }
3744 _censorErrors = !!censorship;
3745 _permanentCensorErrors = !!permanent;
3746 }
3747 static setLogLevel(logLevel) {
3748 const level = LogLevels[logLevel.toLowerCase()];
3749 if (level == null) {
3750 Logger.globalLogger().warn("invalid log level - " + logLevel);
3751 return;
3752 }
3753 _logLevel = level;
3754 }
3755}
3756Logger.errors = ErrorCode;
3757Logger.levels = LogLevel;
3758
3759var lib_esm = /*#__PURE__*/Object.freeze({
3760 get LogLevel () { return LogLevel; },
3761 get ErrorCode () { return ErrorCode; },
3762 Logger: Logger
3763});
3764
3765const version$1 = "bytes/5.0.3";
3766
3767"use strict";
3768const logger = new Logger(version$1);
3769///////////////////////////////
3770function isHexable(value) {
3771 return !!(value.toHexString);
3772}
3773function addSlice(array) {
3774 if (array.slice) {
3775 return array;
3776 }
3777 array.slice = function () {
3778 const args = Array.prototype.slice.call(arguments);
3779 return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));
3780 };
3781 return array;
3782}
3783function isBytesLike(value) {
3784 return ((isHexString(value) && !(value.length % 2)) || isBytes(value));
3785}
3786function isBytes(value) {
3787 if (value == null) {
3788 return false;
3789 }
3790 if (value.constructor === Uint8Array) {
3791 return true;
3792 }
3793 if (typeof (value) === "string") {
3794 return false;
3795 }
3796 if (value.length == null) {
3797 return false;
3798 }
3799 for (let i = 0; i < value.length; i++) {
3800 const v = value[i];
3801 if (v < 0 || v >= 256 || (v % 1)) {
3802 return false;
3803 }
3804 }
3805 return true;
3806}
3807function arrayify(value, options) {
3808 if (!options) {
3809 options = {};
3810 }
3811 if (typeof (value) === "number") {
3812 logger.checkSafeUint53(value, "invalid arrayify value");
3813 const result = [];
3814 while (value) {
3815 result.unshift(value & 0xff);
3816 value = parseInt(String(value / 256));
3817 }
3818 if (result.length === 0) {
3819 result.push(0);
3820 }
3821 return addSlice(new Uint8Array(result));
3822 }
3823 if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
3824 value = "0x" + value;
3825 }
3826 if (isHexable(value)) {
3827 value = value.toHexString();
3828 }
3829 if (isHexString(value)) {
3830 let hex = value.substring(2);
3831 if (hex.length % 2) {
3832 if (options.hexPad === "left") {
3833 hex = "0x0" + hex.substring(2);
3834 }
3835 else if (options.hexPad === "right") {
3836 hex += "0";
3837 }
3838 else {
3839 logger.throwArgumentError("hex data is odd-length", "value", value);
3840 }
3841 }
3842 const result = [];
3843 for (let i = 0; i < hex.length; i += 2) {
3844 result.push(parseInt(hex.substring(i, i + 2), 16));
3845 }
3846 return addSlice(new Uint8Array(result));
3847 }
3848 if (isBytes(value)) {
3849 return addSlice(new Uint8Array(value));
3850 }
3851 return logger.throwArgumentError("invalid arrayify value", "value", value);
3852}
3853function concat(items) {
3854 const objects = items.map(item => arrayify(item));
3855 const length = objects.reduce((accum, item) => (accum + item.length), 0);
3856 const result = new Uint8Array(length);
3857 objects.reduce((offset, object) => {
3858 result.set(object, offset);
3859 return offset + object.length;
3860 }, 0);
3861 return addSlice(result);
3862}
3863function stripZeros(value) {
3864 let result = arrayify(value);
3865 if (result.length === 0) {
3866 return result;
3867 }
3868 // Find the first non-zero entry
3869 let start = 0;
3870 while (start < result.length && result[start] === 0) {
3871 start++;
3872 }
3873 // If we started with zeros, strip them
3874 if (start) {
3875 result = result.slice(start);
3876 }
3877 return result;
3878}
3879function zeroPad(value, length) {
3880 value = arrayify(value);
3881 if (value.length > length) {
3882 logger.throwArgumentError("value out of range", "value", arguments[0]);
3883 }
3884 const result = new Uint8Array(length);
3885 result.set(value, length - value.length);
3886 return addSlice(result);
3887}
3888function isHexString(value, length) {
3889 if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
3890 return false;
3891 }
3892 if (length && value.length !== 2 + 2 * length) {
3893 return false;
3894 }
3895 return true;
3896}
3897const HexCharacters = "0123456789abcdef";
3898function hexlify(value, options) {
3899 if (!options) {
3900 options = {};
3901 }
3902 if (typeof (value) === "number") {
3903 logger.checkSafeUint53(value, "invalid hexlify value");
3904 let hex = "";
3905 while (value) {
3906 hex = HexCharacters[value & 0x0f] + hex;
3907 value = Math.floor(value / 16);
3908 }
3909 if (hex.length) {
3910 if (hex.length % 2) {
3911 hex = "0" + hex;
3912 }
3913 return "0x" + hex;
3914 }
3915 return "0x00";
3916 }
3917 if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
3918 value = "0x" + value;
3919 }
3920 if (isHexable(value)) {
3921 return value.toHexString();
3922 }
3923 if (isHexString(value)) {
3924 if (value.length % 2) {
3925 if (options.hexPad === "left") {
3926 value = "0x0" + value.substring(2);
3927 }
3928 else if (options.hexPad === "right") {
3929 value += "0";
3930 }
3931 else {
3932 logger.throwArgumentError("hex data is odd-length", "value", value);
3933 }
3934 }
3935 return value.toLowerCase();
3936 }
3937 if (isBytes(value)) {
3938 let result = "0x";
3939 for (let i = 0; i < value.length; i++) {
3940 let v = value[i];
3941 result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
3942 }
3943 return result;
3944 }
3945 return logger.throwArgumentError("invalid hexlify value", "value", value);
3946}
3947/*
3948function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {
3949 if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") {
3950 return "0x0" + value.substring(2);
3951 }
3952 return value;
3953}
3954*/
3955function hexDataLength(data) {
3956 if (typeof (data) !== "string") {
3957 data = hexlify(data);
3958 }
3959 else if (!isHexString(data) || (data.length % 2)) {
3960 return null;
3961 }
3962 return (data.length - 2) / 2;
3963}
3964function hexDataSlice(data, offset, endOffset) {
3965 if (typeof (data) !== "string") {
3966 data = hexlify(data);
3967 }
3968 else if (!isHexString(data) || (data.length % 2)) {
3969 logger.throwArgumentError("invalid hexData", "value", data);
3970 }
3971 offset = 2 + 2 * offset;
3972 if (endOffset != null) {
3973 return "0x" + data.substring(offset, 2 + 2 * endOffset);
3974 }
3975 return "0x" + data.substring(offset);
3976}
3977function hexConcat(items) {
3978 let result = "0x";
3979 items.forEach((item) => {
3980 result += hexlify(item).substring(2);
3981 });
3982 return result;
3983}
3984function hexValue(value) {
3985 const trimmed = hexStripZeros(hexlify(value, { hexPad: "left" }));
3986 if (trimmed === "0x") {
3987 return "0x0";
3988 }
3989 return trimmed;
3990}
3991function hexStripZeros(value) {
3992 if (typeof (value) !== "string") {
3993 value = hexlify(value);
3994 }
3995 if (!isHexString(value)) {
3996 logger.throwArgumentError("invalid hex string", "value", value);
3997 }
3998 value = value.substring(2);
3999 let offset = 0;
4000 while (offset < value.length && value[offset] === "0") {
4001 offset++;
4002 }
4003 return "0x" + value.substring(offset);
4004}
4005function hexZeroPad(value, length) {
4006 if (typeof (value) !== "string") {
4007 value = hexlify(value);
4008 }
4009 else if (!isHexString(value)) {
4010 logger.throwArgumentError("invalid hex string", "value", value);
4011 }
4012 if (value.length > 2 * length + 2) {
4013 logger.throwArgumentError("value out of range", "value", arguments[1]);
4014 }
4015 while (value.length < 2 * length + 2) {
4016 value = "0x0" + value.substring(2);
4017 }
4018 return value;
4019}
4020function splitSignature(signature) {
4021 const result = {
4022 r: "0x",
4023 s: "0x",
4024 _vs: "0x",
4025 recoveryParam: 0,
4026 v: 0
4027 };
4028 if (isBytesLike(signature)) {
4029 const bytes = arrayify(signature);
4030 if (bytes.length !== 65) {
4031 logger.throwArgumentError("invalid signature string; must be 65 bytes", "signature", signature);
4032 }
4033 // Get the r, s and v
4034 result.r = hexlify(bytes.slice(0, 32));
4035 result.s = hexlify(bytes.slice(32, 64));
4036 result.v = bytes[64];
4037 // Allow a recid to be used as the v
4038 if (result.v < 27) {
4039 if (result.v === 0 || result.v === 1) {
4040 result.v += 27;
4041 }
4042 else {
4043 logger.throwArgumentError("signature invalid v byte", "signature", signature);
4044 }
4045 }
4046 // Compute recoveryParam from v
4047 result.recoveryParam = 1 - (result.v % 2);
4048 // Compute _vs from recoveryParam and s
4049 if (result.recoveryParam) {
4050 bytes[32] |= 0x80;
4051 }
4052 result._vs = hexlify(bytes.slice(32, 64));
4053 }
4054 else {
4055 result.r = signature.r;
4056 result.s = signature.s;
4057 result.v = signature.v;
4058 result.recoveryParam = signature.recoveryParam;
4059 result._vs = signature._vs;
4060 // If the _vs is available, use it to populate missing s, v and recoveryParam
4061 // and verify non-missing s, v and recoveryParam
4062 if (result._vs != null) {
4063 const vs = zeroPad(arrayify(result._vs), 32);
4064 result._vs = hexlify(vs);
4065 // Set or check the recid
4066 const recoveryParam = ((vs[0] >= 128) ? 1 : 0);
4067 if (result.recoveryParam == null) {
4068 result.recoveryParam = recoveryParam;
4069 }
4070 else if (result.recoveryParam !== recoveryParam) {
4071 logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature);
4072 }
4073 // Set or check the s
4074 vs[0] &= 0x7f;
4075 const s = hexlify(vs);
4076 if (result.s == null) {
4077 result.s = s;
4078 }
4079 else if (result.s !== s) {
4080 logger.throwArgumentError("signature v mismatch _vs", "signature", signature);
4081 }
4082 }
4083 // Use recid and v to populate each other
4084 if (result.recoveryParam == null) {
4085 if (result.v == null) {
4086 logger.throwArgumentError("signature missing v and recoveryParam", "signature", signature);
4087 }
4088 else {
4089 result.recoveryParam = 1 - (result.v % 2);
4090 }
4091 }
4092 else {
4093 if (result.v == null) {
4094 result.v = 27 + result.recoveryParam;
4095 }
4096 else if (result.recoveryParam !== (1 - (result.v % 2))) {
4097 logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature);
4098 }
4099 }
4100 if (result.r == null || !isHexString(result.r)) {
4101 logger.throwArgumentError("signature missing or invalid r", "signature", signature);
4102 }
4103 else {
4104 result.r = hexZeroPad(result.r, 32);
4105 }
4106 if (result.s == null || !isHexString(result.s)) {
4107 logger.throwArgumentError("signature missing or invalid s", "signature", signature);
4108 }
4109 else {
4110 result.s = hexZeroPad(result.s, 32);
4111 }
4112 const vs = arrayify(result.s);
4113 if (vs[0] >= 128) {
4114 logger.throwArgumentError("signature s out of range", "signature", signature);
4115 }
4116 if (result.recoveryParam) {
4117 vs[0] |= 0x80;
4118 }
4119 const _vs = hexlify(vs);
4120 if (result._vs) {
4121 if (!isHexString(result._vs)) {
4122 logger.throwArgumentError("signature invalid _vs", "signature", signature);
4123 }
4124 result._vs = hexZeroPad(result._vs, 32);
4125 }
4126 // Set or check the _vs
4127 if (result._vs == null) {
4128 result._vs = _vs;
4129 }
4130 else if (result._vs !== _vs) {
4131 logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature);
4132 }
4133 }
4134 return result;
4135}
4136function joinSignature(signature) {
4137 signature = splitSignature(signature);
4138 return hexlify(concat([
4139 signature.r,
4140 signature.s,
4141 (signature.recoveryParam ? "0x1c" : "0x1b")
4142 ]));
4143}
4144
4145var lib_esm$1 = /*#__PURE__*/Object.freeze({
4146 isBytesLike: isBytesLike,
4147 isBytes: isBytes,
4148 arrayify: arrayify,
4149 concat: concat,
4150 stripZeros: stripZeros,
4151 zeroPad: zeroPad,
4152 isHexString: isHexString,
4153 hexlify: hexlify,
4154 hexDataLength: hexDataLength,
4155 hexDataSlice: hexDataSlice,
4156 hexConcat: hexConcat,
4157 hexValue: hexValue,
4158 hexStripZeros: hexStripZeros,
4159 hexZeroPad: hexZeroPad,
4160 splitSignature: splitSignature,
4161 joinSignature: joinSignature
4162});
4163
4164const version$2 = "bignumber/5.0.5";
4165
4166"use strict";
4167const logger$1 = new Logger(version$2);
4168const _constructorGuard = {};
4169const MAX_SAFE = 0x1fffffffffffff;
4170function isBigNumberish(value) {
4171 return (value != null) && (BigNumber.isBigNumber(value) ||
4172 (typeof (value) === "number" && (value % 1) === 0) ||
4173 (typeof (value) === "string" && !!value.match(/^-?[0-9]+$/)) ||
4174 isHexString(value) ||
4175 (typeof (value) === "bigint") ||
4176 isBytes(value));
4177}
4178class BigNumber {
4179 constructor(constructorGuard, hex) {
4180 logger$1.checkNew(new.target, BigNumber);
4181 if (constructorGuard !== _constructorGuard) {
4182 logger$1.throwError("cannot call constructor directly; use BigNumber.from", Logger.errors.UNSUPPORTED_OPERATION, {
4183 operation: "new (BigNumber)"
4184 });
4185 }
4186 this._hex = hex;
4187 this._isBigNumber = true;
4188 Object.freeze(this);
4189 }
4190 fromTwos(value) {
4191 return toBigNumber(toBN(this).fromTwos(value));
4192 }
4193 toTwos(value) {
4194 return toBigNumber(toBN(this).toTwos(value));
4195 }
4196 abs() {
4197 if (this._hex[0] === "-") {
4198 return BigNumber.from(this._hex.substring(1));
4199 }
4200 return this;
4201 }
4202 add(other) {
4203 return toBigNumber(toBN(this).add(toBN(other)));
4204 }
4205 sub(other) {
4206 return toBigNumber(toBN(this).sub(toBN(other)));
4207 }
4208 div(other) {
4209 const o = BigNumber.from(other);
4210 if (o.isZero()) {
4211 throwFault("division by zero", "div");
4212 }
4213 return toBigNumber(toBN(this).div(toBN(other)));
4214 }
4215 mul(other) {
4216 return toBigNumber(toBN(this).mul(toBN(other)));
4217 }
4218 mod(other) {
4219 const value = toBN(other);
4220 if (value.isNeg()) {
4221 throwFault("cannot modulo negative values", "mod");
4222 }
4223 return toBigNumber(toBN(this).umod(value));
4224 }
4225 pow(other) {
4226 const value = toBN(other);
4227 if (value.isNeg()) {
4228 throwFault("cannot raise to negative values", "pow");
4229 }
4230 return toBigNumber(toBN(this).pow(value));
4231 }
4232 and(other) {
4233 const value = toBN(other);
4234 if (this.isNegative() || value.isNeg()) {
4235 throwFault("cannot 'and' negative values", "and");
4236 }
4237 return toBigNumber(toBN(this).and(value));
4238 }
4239 or(other) {
4240 const value = toBN(other);
4241 if (this.isNegative() || value.isNeg()) {
4242 throwFault("cannot 'or' negative values", "or");
4243 }
4244 return toBigNumber(toBN(this).or(value));
4245 }
4246 xor(other) {
4247 const value = toBN(other);
4248 if (this.isNegative() || value.isNeg()) {
4249 throwFault("cannot 'xor' negative values", "xor");
4250 }
4251 return toBigNumber(toBN(this).xor(value));
4252 }
4253 mask(value) {
4254 if (this.isNegative() || value < 0) {
4255 throwFault("cannot mask negative values", "mask");
4256 }
4257 return toBigNumber(toBN(this).maskn(value));
4258 }
4259 shl(value) {
4260 if (this.isNegative() || value < 0) {
4261 throwFault("cannot shift negative values", "shl");
4262 }
4263 return toBigNumber(toBN(this).shln(value));
4264 }
4265 shr(value) {
4266 if (this.isNegative() || value < 0) {
4267 throwFault("cannot shift negative values", "shr");
4268 }
4269 return toBigNumber(toBN(this).shrn(value));
4270 }
4271 eq(other) {
4272 return toBN(this).eq(toBN(other));
4273 }
4274 lt(other) {
4275 return toBN(this).lt(toBN(other));
4276 }
4277 lte(other) {
4278 return toBN(this).lte(toBN(other));
4279 }
4280 gt(other) {
4281 return toBN(this).gt(toBN(other));
4282 }
4283 gte(other) {
4284 return toBN(this).gte(toBN(other));
4285 }
4286 isNegative() {
4287 return (this._hex[0] === "-");
4288 }
4289 isZero() {
4290 return toBN(this).isZero();
4291 }
4292 toNumber() {
4293 try {
4294 return toBN(this).toNumber();
4295 }
4296 catch (error) {
4297 throwFault("overflow", "toNumber", this.toString());
4298 }
4299 return null;
4300 }
4301 toString() {
4302 // Lots of people expect this, which we do not support, so check
4303 if (arguments.length !== 0) {
4304 logger$1.throwError("bigNumber.toString does not accept parameters", Logger.errors.UNEXPECTED_ARGUMENT, {});
4305 }
4306 return toBN(this).toString(10);
4307 }
4308 toHexString() {
4309 return this._hex;
4310 }
4311 static from(value) {
4312 if (value instanceof BigNumber) {
4313 return value;
4314 }
4315 if (typeof (value) === "string") {
4316 if (value.match(/^-?0x[0-9a-f]+$/i)) {
4317 return new BigNumber(_constructorGuard, toHex(value));
4318 }
4319 if (value.match(/^-?[0-9]+$/)) {
4320 return new BigNumber(_constructorGuard, toHex(new bn_1(value)));
4321 }
4322 return logger$1.throwArgumentError("invalid BigNumber string", "value", value);
4323 }
4324 if (typeof (value) === "number") {
4325 if (value % 1) {
4326 throwFault("underflow", "BigNumber.from", value);
4327 }
4328 if (value >= MAX_SAFE || value <= -MAX_SAFE) {
4329 throwFault("overflow", "BigNumber.from", value);
4330 }
4331 return BigNumber.from(String(value));
4332 }
4333 if (typeof (value) === "bigint") {
4334 return BigNumber.from(value.toString());
4335 }
4336 if (isBytes(value)) {
4337 return BigNumber.from(hexlify(value));
4338 }
4339 if (value._hex && isHexString(value._hex)) {
4340 return BigNumber.from(value._hex);
4341 }
4342 if (value.toHexString) {
4343 value = value.toHexString();
4344 if (typeof (value) === "string") {
4345 return BigNumber.from(value);
4346 }
4347 }
4348 return logger$1.throwArgumentError("invalid BigNumber value", "value", value);
4349 }
4350 static isBigNumber(value) {
4351 return !!(value && value._isBigNumber);
4352 }
4353}
4354// Normalize the hex string
4355function toHex(value) {
4356 // For BN, call on the hex string
4357 if (typeof (value) !== "string") {
4358 return toHex(value.toString(16));
4359 }
4360 // If negative, prepend the negative sign to the normalized positive value
4361 if (value[0] === "-") {
4362 // Strip off the negative sign
4363 value = value.substring(1);
4364 // Cannot have mulitple negative signs (e.g. "--0x04")
4365 if (value[0] === "-") {
4366 logger$1.throwArgumentError("invalid hex", "value", value);
4367 }
4368 // Call toHex on the positive component
4369 value = toHex(value);
4370 // Do not allow "-0x00"
4371 if (value === "0x00") {
4372 return value;
4373 }
4374 // Negate the value
4375 return "-" + value;
4376 }
4377 // Add a "0x" prefix if missing
4378 if (value.substring(0, 2) !== "0x") {
4379 value = "0x" + value;
4380 }
4381 // Normalize zero
4382 if (value === "0x") {
4383 return "0x00";
4384 }
4385 // Make the string even length
4386 if (value.length % 2) {
4387 value = "0x0" + value.substring(2);
4388 }
4389 // Trim to smallest even-length string
4390 while (value.length > 4 && value.substring(0, 4) === "0x00") {
4391 value = "0x" + value.substring(4);
4392 }
4393 return value;
4394}
4395function toBigNumber(value) {
4396 return BigNumber.from(toHex(value));
4397}
4398function toBN(value) {
4399 const hex = BigNumber.from(value).toHexString();
4400 if (hex[0] === "-") {
4401 return (new bn_1("-" + hex.substring(3), 16));
4402 }
4403 return new bn_1(hex.substring(2), 16);
4404}
4405function throwFault(fault, operation, value) {
4406 const params = { fault: fault, operation: operation };
4407 if (value != null) {
4408 params.value = value;
4409 }
4410 return logger$1.throwError(fault, Logger.errors.NUMERIC_FAULT, params);
4411}
4412
4413"use strict";
4414const logger$2 = new Logger(version$2);
4415const _constructorGuard$1 = {};
4416const Zero = BigNumber.from(0);
4417const NegativeOne = BigNumber.from(-1);
4418function throwFault$1(message, fault, operation, value) {
4419 const params = { fault: fault, operation: operation };
4420 if (value !== undefined) {
4421 params.value = value;
4422 }
4423 return logger$2.throwError(message, Logger.errors.NUMERIC_FAULT, params);
4424}
4425// Constant to pull zeros from for multipliers
4426let zeros = "0";
4427while (zeros.length < 256) {
4428 zeros += zeros;
4429}
4430// Returns a string "1" followed by decimal "0"s
4431function getMultiplier(decimals) {
4432 if (typeof (decimals) !== "number") {
4433 try {
4434 decimals = BigNumber.from(decimals).toNumber();
4435 }
4436 catch (e) { }
4437 }
4438 if (typeof (decimals) === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) {
4439 return ("1" + zeros.substring(0, decimals));
4440 }
4441 return logger$2.throwArgumentError("invalid decimal size", "decimals", decimals);
4442}
4443function formatFixed(value, decimals) {
4444 if (decimals == null) {
4445 decimals = 0;
4446 }
4447 const multiplier = getMultiplier(decimals);
4448 // Make sure wei is a big number (convert as necessary)
4449 value = BigNumber.from(value);
4450 const negative = value.lt(Zero);
4451 if (negative) {
4452 value = value.mul(NegativeOne);
4453 }
4454 let fraction = value.mod(multiplier).toString();
4455 while (fraction.length < multiplier.length - 1) {
4456 fraction = "0" + fraction;
4457 }
4458 // Strip training 0
4459 fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
4460 const whole = value.div(multiplier).toString();
4461 value = whole + "." + fraction;
4462 if (negative) {
4463 value = "-" + value;
4464 }
4465 return value;
4466}
4467function parseFixed(value, decimals) {
4468 if (decimals == null) {
4469 decimals = 0;
4470 }
4471 const multiplier = getMultiplier(decimals);
4472 if (typeof (value) !== "string" || !value.match(/^-?[0-9.,]+$/)) {
4473 logger$2.throwArgumentError("invalid decimal value", "value", value);
4474 }
4475 if (multiplier.length - 1 === 0) {
4476 return BigNumber.from(value);
4477 }
4478 // Is it negative?
4479 const negative = (value.substring(0, 1) === "-");
4480 if (negative) {
4481 value = value.substring(1);
4482 }
4483 if (value === ".") {
4484 logger$2.throwArgumentError("missing value", "value", value);
4485 }
4486 // Split it into a whole and fractional part
4487 const comps = value.split(".");
4488 if (comps.length > 2) {
4489 logger$2.throwArgumentError("too many decimal points", "value", value);
4490 }
4491 let whole = comps[0], fraction = comps[1];
4492 if (!whole) {
4493 whole = "0";
4494 }
4495 if (!fraction) {
4496 fraction = "0";
4497 }
4498 // Prevent underflow
4499 if (fraction.length > multiplier.length - 1) {
4500 throwFault$1("fractional component exceeds decimals", "underflow", "parseFixed");
4501 }
4502 // Fully pad the string with zeros to get to wei
4503 while (fraction.length < multiplier.length - 1) {
4504 fraction += "0";
4505 }
4506 const wholeValue = BigNumber.from(whole);
4507 const fractionValue = BigNumber.from(fraction);
4508 let wei = (wholeValue.mul(multiplier)).add(fractionValue);
4509 if (negative) {
4510 wei = wei.mul(NegativeOne);
4511 }
4512 return wei;
4513}
4514class FixedFormat {
4515 constructor(constructorGuard, signed, width, decimals) {
4516 if (constructorGuard !== _constructorGuard$1) {
4517 logger$2.throwError("cannot use FixedFormat constructor; use FixedFormat.from", Logger.errors.UNSUPPORTED_OPERATION, {
4518 operation: "new FixedFormat"
4519 });
4520 }
4521 this.signed = signed;
4522 this.width = width;
4523 this.decimals = decimals;
4524 this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
4525 this._multiplier = getMultiplier(decimals);
4526 Object.freeze(this);
4527 }
4528 static from(value) {
4529 if (value instanceof FixedFormat) {
4530 return value;
4531 }
4532 let signed = true;
4533 let width = 128;
4534 let decimals = 18;
4535 if (typeof (value) === "string") {
4536 if (value === "fixed") {
4537 // defaults...
4538 }
4539 else if (value === "ufixed") {
4540 signed = false;
4541 }
4542 else if (value != null) {
4543 const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
4544 if (!match) {
4545 logger$2.throwArgumentError("invalid fixed format", "format", value);
4546 }
4547 signed = (match[1] !== "u");
4548 width = parseInt(match[2]);
4549 decimals = parseInt(match[3]);
4550 }
4551 }
4552 else if (value) {
4553 const check = (key, type, defaultValue) => {
4554 if (value[key] == null) {
4555 return defaultValue;
4556 }
4557 if (typeof (value[key]) !== type) {
4558 logger$2.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]);
4559 }
4560 return value[key];
4561 };
4562 signed = check("signed", "boolean", signed);
4563 width = check("width", "number", width);
4564 decimals = check("decimals", "number", decimals);
4565 }
4566 if (width % 8) {
4567 logger$2.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width);
4568 }
4569 if (decimals > 80) {
4570 logger$2.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals);
4571 }
4572 return new FixedFormat(_constructorGuard$1, signed, width, decimals);
4573 }
4574}
4575class FixedNumber {
4576 constructor(constructorGuard, hex, value, format) {
4577 logger$2.checkNew(new.target, FixedNumber);
4578 if (constructorGuard !== _constructorGuard$1) {
4579 logger$2.throwError("cannot use FixedNumber constructor; use FixedNumber.from", Logger.errors.UNSUPPORTED_OPERATION, {
4580 operation: "new FixedFormat"
4581 });
4582 }
4583 this.format = format;
4584 this._hex = hex;
4585 this._value = value;
4586 this._isFixedNumber = true;
4587 Object.freeze(this);
4588 }
4589 _checkFormat(other) {
4590 if (this.format.name !== other.format.name) {
4591 logger$2.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other);
4592 }
4593 }
4594 addUnsafe(other) {
4595 this._checkFormat(other);
4596 const a = parseFixed(this._value, this.format.decimals);
4597 const b = parseFixed(other._value, other.format.decimals);
4598 return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);
4599 }
4600 subUnsafe(other) {
4601 this._checkFormat(other);
4602 const a = parseFixed(this._value, this.format.decimals);
4603 const b = parseFixed(other._value, other.format.decimals);
4604 return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);
4605 }
4606 mulUnsafe(other) {
4607 this._checkFormat(other);
4608 const a = parseFixed(this._value, this.format.decimals);
4609 const b = parseFixed(other._value, other.format.decimals);
4610 return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);
4611 }
4612 divUnsafe(other) {
4613 this._checkFormat(other);
4614 const a = parseFixed(this._value, this.format.decimals);
4615 const b = parseFixed(other._value, other.format.decimals);
4616 return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);
4617 }
4618 // @TODO: Support other rounding algorithms
4619 round(decimals) {
4620 if (decimals == null) {
4621 decimals = 0;
4622 }
4623 if (decimals < 0 || decimals > 80 || (decimals % 1)) {
4624 logger$2.throwArgumentError("invalid decimal count", "decimals", decimals);
4625 }
4626 // If we are already in range, we're done
4627 let comps = this.toString().split(".");
4628 if (comps[1].length <= decimals) {
4629 return this;
4630 }
4631 // Bump the value up by the 0.00...0005
4632 const bump = "0." + zeros.substring(0, decimals) + "5";
4633 comps = this.addUnsafe(FixedNumber.fromString(bump, this.format))._value.split(".");
4634 // Now it is safe to truncate
4635 return FixedNumber.fromString(comps[0] + "." + comps[1].substring(0, decimals));
4636 }
4637 isZero() {
4638 return (this._value === "0.0");
4639 }
4640 toString() { return this._value; }
4641 toHexString(width) {
4642 if (width == null) {
4643 return this._hex;
4644 }
4645 if (width % 8) {
4646 logger$2.throwArgumentError("invalid byte width", "width", width);
4647 }
4648 const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
4649 return hexZeroPad(hex, width / 8);
4650 }
4651 toUnsafeFloat() { return parseFloat(this.toString()); }
4652 toFormat(format) {
4653 return FixedNumber.fromString(this._value, format);
4654 }
4655 static fromValue(value, decimals, format) {
4656 // If decimals looks more like a format, and there is no format, shift the parameters
4657 if (format == null && decimals != null && !isBigNumberish(decimals)) {
4658 format = decimals;
4659 decimals = null;
4660 }
4661 if (decimals == null) {
4662 decimals = 0;
4663 }
4664 if (format == null) {
4665 format = "fixed";
4666 }
4667 return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format));
4668 }
4669 static fromString(value, format) {
4670 if (format == null) {
4671 format = "fixed";
4672 }
4673 const fixedFormat = FixedFormat.from(format);
4674 const numeric = parseFixed(value, fixedFormat.decimals);
4675 if (!fixedFormat.signed && numeric.lt(Zero)) {
4676 throwFault$1("unsigned value cannot be negative", "overflow", "value", value);
4677 }
4678 let hex = null;
4679 if (fixedFormat.signed) {
4680 hex = numeric.toTwos(fixedFormat.width).toHexString();
4681 }
4682 else {
4683 hex = numeric.toHexString();
4684 hex = hexZeroPad(hex, fixedFormat.width / 8);
4685 }
4686 const decimal = formatFixed(numeric, fixedFormat.decimals);
4687 return new FixedNumber(_constructorGuard$1, hex, decimal, fixedFormat);
4688 }
4689 static fromBytes(value, format) {
4690 if (format == null) {
4691 format = "fixed";
4692 }
4693 const fixedFormat = FixedFormat.from(format);
4694 if (arrayify(value).length > fixedFormat.width / 8) {
4695 throw new Error("overflow");
4696 }
4697 let numeric = BigNumber.from(value);
4698 if (fixedFormat.signed) {
4699 numeric = numeric.fromTwos(fixedFormat.width);
4700 }
4701 const hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString();
4702 const decimal = formatFixed(numeric, fixedFormat.decimals);
4703 return new FixedNumber(_constructorGuard$1, hex, decimal, fixedFormat);
4704 }
4705 static from(value, format) {
4706 if (typeof (value) === "string") {
4707 return FixedNumber.fromString(value, format);
4708 }
4709 if (isBytes(value)) {
4710 return FixedNumber.fromBytes(value, format);
4711 }
4712 try {
4713 return FixedNumber.fromValue(value, 0, format);
4714 }
4715 catch (error) {
4716 // Allow NUMERIC_FAULT to bubble up
4717 if (error.code !== Logger.errors.INVALID_ARGUMENT) {
4718 throw error;
4719 }
4720 }
4721 return logger$2.throwArgumentError("invalid FixedNumber value", "value", value);
4722 }
4723 static isFixedNumber(value) {
4724 return !!(value && value._isFixedNumber);
4725 }
4726}
4727
4728const version$3 = "properties/5.0.2";
4729
4730"use strict";
4731var __awaiter = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
4732 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4733 return new (P || (P = Promise))(function (resolve, reject) {
4734 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
4735 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
4736 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
4737 step((generator = generator.apply(thisArg, _arguments || [])).next());
4738 });
4739};
4740const logger$3 = new Logger(version$3);
4741function defineReadOnly(object, name, value) {
4742 Object.defineProperty(object, name, {
4743 enumerable: true,
4744 value: value,
4745 writable: false,
4746 });
4747}
4748// Crawl up the constructor chain to find a static method
4749function getStatic(ctor, key) {
4750 for (let i = 0; i < 32; i++) {
4751 if (ctor[key]) {
4752 return ctor[key];
4753 }
4754 if (!ctor.prototype || typeof (ctor.prototype) !== "object") {
4755 break;
4756 }
4757 ctor = Object.getPrototypeOf(ctor.prototype).constructor;
4758 }
4759 return null;
4760}
4761function resolveProperties(object) {
4762 return __awaiter(this, void 0, void 0, function* () {
4763 const promises = Object.keys(object).map((key) => {
4764 const value = object[key];
4765 return Promise.resolve(value).then((v) => ({ key: key, value: v }));
4766 });
4767 const results = yield Promise.all(promises);
4768 return results.reduce((accum, result) => {
4769 accum[(result.key)] = result.value;
4770 return accum;
4771 }, {});
4772 });
4773}
4774function checkProperties(object, properties) {
4775 if (!object || typeof (object) !== "object") {
4776 logger$3.throwArgumentError("invalid object", "object", object);
4777 }
4778 Object.keys(object).forEach((key) => {
4779 if (!properties[key]) {
4780 logger$3.throwArgumentError("invalid object key - " + key, "transaction:" + key, object);
4781 }
4782 });
4783}
4784function shallowCopy(object) {
4785 const result = {};
4786 for (const key in object) {
4787 result[key] = object[key];
4788 }
4789 return result;
4790}
4791const opaque = { bigint: true, boolean: true, "function": true, number: true, string: true };
4792function _isFrozen(object) {
4793 // Opaque objects are not mutable, so safe to copy by assignment
4794 if (object === undefined || object === null || opaque[typeof (object)]) {
4795 return true;
4796 }
4797 if (Array.isArray(object) || typeof (object) === "object") {
4798 if (!Object.isFrozen(object)) {
4799 return false;
4800 }
4801 const keys = Object.keys(object);
4802 for (let i = 0; i < keys.length; i++) {
4803 if (!_isFrozen(object[keys[i]])) {
4804 return false;
4805 }
4806 }
4807 return true;
4808 }
4809 return logger$3.throwArgumentError(`Cannot deepCopy ${typeof (object)}`, "object", object);
4810}
4811// Returns a new copy of object, such that no properties may be replaced.
4812// New properties may be added only to objects.
4813function _deepCopy(object) {
4814 if (_isFrozen(object)) {
4815 return object;
4816 }
4817 // Arrays are mutable, so we need to create a copy
4818 if (Array.isArray(object)) {
4819 return Object.freeze(object.map((item) => deepCopy(item)));
4820 }
4821 if (typeof (object) === "object") {
4822 const result = {};
4823 for (const key in object) {
4824 const value = object[key];
4825 if (value === undefined) {
4826 continue;
4827 }
4828 defineReadOnly(result, key, deepCopy(value));
4829 }
4830 return result;
4831 }
4832 return logger$3.throwArgumentError(`Cannot deepCopy ${typeof (object)}`, "object", object);
4833}
4834function deepCopy(object) {
4835 return _deepCopy(object);
4836}
4837class Description {
4838 constructor(info) {
4839 for (const key in info) {
4840 this[key] = deepCopy(info[key]);
4841 }
4842 }
4843}
4844
4845const version$4 = "abi/5.0.2";
4846
4847"use strict";
4848const logger$4 = new Logger(version$4);
4849;
4850const _constructorGuard$2 = {};
4851let ModifiersBytes = { calldata: true, memory: true, storage: true };
4852let ModifiersNest = { calldata: true, memory: true };
4853function checkModifier(type, name) {
4854 if (type === "bytes" || type === "string") {
4855 if (ModifiersBytes[name]) {
4856 return true;
4857 }
4858 }
4859 else if (type === "address") {
4860 if (name === "payable") {
4861 return true;
4862 }
4863 }
4864 else if (type.indexOf("[") >= 0 || type === "tuple") {
4865 if (ModifiersNest[name]) {
4866 return true;
4867 }
4868 }
4869 if (ModifiersBytes[name] || name === "payable") {
4870 logger$4.throwArgumentError("invalid modifier", "name", name);
4871 }
4872 return false;
4873}
4874// @TODO: Make sure that children of an indexed tuple are marked with a null indexed
4875function parseParamType(param, allowIndexed) {
4876 let originalParam = param;
4877 function throwError(i) {
4878 logger$4.throwArgumentError(`unexpected character at position ${i}`, "param", param);
4879 }
4880 param = param.replace(/\s/g, " ");
4881 function newNode(parent) {
4882 let node = { type: "", name: "", parent: parent, state: { allowType: true } };
4883 if (allowIndexed) {
4884 node.indexed = false;
4885 }
4886 return node;
4887 }
4888 let parent = { type: "", name: "", state: { allowType: true } };
4889 let node = parent;
4890 for (let i = 0; i < param.length; i++) {
4891 let c = param[i];
4892 switch (c) {
4893 case "(":
4894 if (node.state.allowType && node.type === "") {
4895 node.type = "tuple";
4896 }
4897 else if (!node.state.allowParams) {
4898 throwError(i);
4899 }
4900 node.state.allowType = false;
4901 node.type = verifyType(node.type);
4902 node.components = [newNode(node)];
4903 node = node.components[0];
4904 break;
4905 case ")":
4906 delete node.state;
4907 if (node.name === "indexed") {
4908 if (!allowIndexed) {
4909 throwError(i);
4910 }
4911 node.indexed = true;
4912 node.name = "";
4913 }
4914 if (checkModifier(node.type, node.name)) {
4915 node.name = "";
4916 }
4917 node.type = verifyType(node.type);
4918 let child = node;
4919 node = node.parent;
4920 if (!node) {
4921 throwError(i);
4922 }
4923 delete child.parent;
4924 node.state.allowParams = false;
4925 node.state.allowName = true;
4926 node.state.allowArray = true;
4927 break;
4928 case ",":
4929 delete node.state;
4930 if (node.name === "indexed") {
4931 if (!allowIndexed) {
4932 throwError(i);
4933 }
4934 node.indexed = true;
4935 node.name = "";
4936 }
4937 if (checkModifier(node.type, node.name)) {
4938 node.name = "";
4939 }
4940 node.type = verifyType(node.type);
4941 let sibling = newNode(node.parent);
4942 //{ type: "", name: "", parent: node.parent, state: { allowType: true } };
4943 node.parent.components.push(sibling);
4944 delete node.parent;
4945 node = sibling;
4946 break;
4947 // Hit a space...
4948 case " ":
4949 // If reading type, the type is done and may read a param or name
4950 if (node.state.allowType) {
4951 if (node.type !== "") {
4952 node.type = verifyType(node.type);
4953 delete node.state.allowType;
4954 node.state.allowName = true;
4955 node.state.allowParams = true;
4956 }
4957 }
4958 // If reading name, the name is done
4959 if (node.state.allowName) {
4960 if (node.name !== "") {
4961 if (node.name === "indexed") {
4962 if (!allowIndexed) {
4963 throwError(i);
4964 }
4965 if (node.indexed) {
4966 throwError(i);
4967 }
4968 node.indexed = true;
4969 node.name = "";
4970 }
4971 else if (checkModifier(node.type, node.name)) {
4972 node.name = "";
4973 }
4974 else {
4975 node.state.allowName = false;
4976 }
4977 }
4978 }
4979 break;
4980 case "[":
4981 if (!node.state.allowArray) {
4982 throwError(i);
4983 }
4984 node.type += c;
4985 node.state.allowArray = false;
4986 node.state.allowName = false;
4987 node.state.readArray = true;
4988 break;
4989 case "]":
4990 if (!node.state.readArray) {
4991 throwError(i);
4992 }
4993 node.type += c;
4994 node.state.readArray = false;
4995 node.state.allowArray = true;
4996 node.state.allowName = true;
4997 break;
4998 default:
4999 if (node.state.allowType) {
5000 node.type += c;
5001 node.state.allowParams = true;
5002 node.state.allowArray = true;
5003 }
5004 else if (node.state.allowName) {
5005 node.name += c;
5006 delete node.state.allowArray;
5007 }
5008 else if (node.state.readArray) {
5009 node.type += c;
5010 }
5011 else {
5012 throwError(i);
5013 }
5014 }
5015 }
5016 if (node.parent) {
5017 logger$4.throwArgumentError("unexpected eof", "param", param);
5018 }
5019 delete parent.state;
5020 if (node.name === "indexed") {
5021 if (!allowIndexed) {
5022 throwError(originalParam.length - 7);
5023 }
5024 if (node.indexed) {
5025 throwError(originalParam.length - 7);
5026 }
5027 node.indexed = true;
5028 node.name = "";
5029 }
5030 else if (checkModifier(node.type, node.name)) {
5031 node.name = "";
5032 }
5033 parent.type = verifyType(parent.type);
5034 return parent;
5035}
5036function populate(object, params) {
5037 for (let key in params) {
5038 defineReadOnly(object, key, params[key]);
5039 }
5040}
5041const FormatTypes = Object.freeze({
5042 // Bare formatting, as is needed for computing a sighash of an event or function
5043 sighash: "sighash",
5044 // Human-Readable with Minimal spacing and without names (compact human-readable)
5045 minimal: "minimal",
5046 // Human-Readble with nice spacing, including all names
5047 full: "full",
5048 // JSON-format a la Solidity
5049 json: "json"
5050});
5051const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
5052class ParamType {
5053 constructor(constructorGuard, params) {
5054 if (constructorGuard !== _constructorGuard$2) {
5055 logger$4.throwError("use fromString", Logger.errors.UNSUPPORTED_OPERATION, {
5056 operation: "new ParamType()"
5057 });
5058 }
5059 populate(this, params);
5060 let match = this.type.match(paramTypeArray);
5061 if (match) {
5062 populate(this, {
5063 arrayLength: parseInt(match[2] || "-1"),
5064 arrayChildren: ParamType.fromObject({
5065 type: match[1],
5066 components: this.components
5067 }),
5068 baseType: "array"
5069 });
5070 }
5071 else {
5072 populate(this, {
5073 arrayLength: null,
5074 arrayChildren: null,
5075 baseType: ((this.components != null) ? "tuple" : this.type)
5076 });
5077 }
5078 this._isParamType = true;
5079 Object.freeze(this);
5080 }
5081 // Format the parameter fragment
5082 // - sighash: "(uint256,address)"
5083 // - minimal: "tuple(uint256,address) indexed"
5084 // - full: "tuple(uint256 foo, addres bar) indexed baz"
5085 format(format) {
5086 if (!format) {
5087 format = FormatTypes.sighash;
5088 }
5089 if (!FormatTypes[format]) {
5090 logger$4.throwArgumentError("invalid format type", "format", format);
5091 }
5092 if (format === FormatTypes.json) {
5093 let result = {
5094 type: ((this.baseType === "tuple") ? "tuple" : this.type),
5095 name: (this.name || undefined)
5096 };
5097 if (typeof (this.indexed) === "boolean") {
5098 result.indexed = this.indexed;
5099 }
5100 if (this.components) {
5101 result.components = this.components.map((comp) => JSON.parse(comp.format(format)));
5102 }
5103 return JSON.stringify(result);
5104 }
5105 let result = "";
5106 // Array
5107 if (this.baseType === "array") {
5108 result += this.arrayChildren.format(format);
5109 result += "[" + (this.arrayLength < 0 ? "" : String(this.arrayLength)) + "]";
5110 }
5111 else {
5112 if (this.baseType === "tuple") {
5113 if (format !== FormatTypes.sighash) {
5114 result += this.type;
5115 }
5116 result += "(" + this.components.map((comp) => comp.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ")";
5117 }
5118 else {
5119 result += this.type;
5120 }
5121 }
5122 if (format !== FormatTypes.sighash) {
5123 if (this.indexed === true) {
5124 result += " indexed";
5125 }
5126 if (format === FormatTypes.full && this.name) {
5127 result += " " + this.name;
5128 }
5129 }
5130 return result;
5131 }
5132 static from(value, allowIndexed) {
5133 if (typeof (value) === "string") {
5134 return ParamType.fromString(value, allowIndexed);
5135 }
5136 return ParamType.fromObject(value);
5137 }
5138 static fromObject(value) {
5139 if (ParamType.isParamType(value)) {
5140 return value;
5141 }
5142 return new ParamType(_constructorGuard$2, {
5143 name: (value.name || null),
5144 type: verifyType(value.type),
5145 indexed: ((value.indexed == null) ? null : !!value.indexed),
5146 components: (value.components ? value.components.map(ParamType.fromObject) : null)
5147 });
5148 }
5149 static fromString(value, allowIndexed) {
5150 function ParamTypify(node) {
5151 return ParamType.fromObject({
5152 name: node.name,
5153 type: node.type,
5154 indexed: node.indexed,
5155 components: node.components
5156 });
5157 }
5158 return ParamTypify(parseParamType(value, !!allowIndexed));
5159 }
5160 static isParamType(value) {
5161 return !!(value != null && value._isParamType);
5162 }
5163}
5164;
5165function parseParams(value, allowIndex) {
5166 return splitNesting(value).map((param) => ParamType.fromString(param, allowIndex));
5167}
5168class Fragment {
5169 constructor(constructorGuard, params) {
5170 if (constructorGuard !== _constructorGuard$2) {
5171 logger$4.throwError("use a static from method", Logger.errors.UNSUPPORTED_OPERATION, {
5172 operation: "new Fragment()"
5173 });
5174 }
5175 populate(this, params);
5176 this._isFragment = true;
5177 Object.freeze(this);
5178 }
5179 static from(value) {
5180 if (Fragment.isFragment(value)) {
5181 return value;
5182 }
5183 if (typeof (value) === "string") {
5184 return Fragment.fromString(value);
5185 }
5186 return Fragment.fromObject(value);
5187 }
5188 static fromObject(value) {
5189 if (Fragment.isFragment(value)) {
5190 return value;
5191 }
5192 switch (value.type) {
5193 case "function":
5194 return FunctionFragment.fromObject(value);
5195 case "event":
5196 return EventFragment.fromObject(value);
5197 case "constructor":
5198 return ConstructorFragment.fromObject(value);
5199 case "fallback":
5200 case "receive":
5201 // @TODO: Something? Maybe return a FunctionFragment? A custom DefaultFunctionFragment?
5202 return null;
5203 }
5204 return logger$4.throwArgumentError("invalid fragment object", "value", value);
5205 }
5206 static fromString(value) {
5207 // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
5208 value = value.replace(/\s/g, " ");
5209 value = value.replace(/\(/g, " (").replace(/\)/g, ") ").replace(/\s+/g, " ");
5210 value = value.trim();
5211 if (value.split(" ")[0] === "event") {
5212 return EventFragment.fromString(value.substring(5).trim());
5213 }
5214 else if (value.split(" ")[0] === "function") {
5215 return FunctionFragment.fromString(value.substring(8).trim());
5216 }
5217 else if (value.split("(")[0].trim() === "constructor") {
5218 return ConstructorFragment.fromString(value.trim());
5219 }
5220 return logger$4.throwArgumentError("unsupported fragment", "value", value);
5221 }
5222 static isFragment(value) {
5223 return !!(value && value._isFragment);
5224 }
5225}
5226class EventFragment extends Fragment {
5227 format(format) {
5228 if (!format) {
5229 format = FormatTypes.sighash;
5230 }
5231 if (!FormatTypes[format]) {
5232 logger$4.throwArgumentError("invalid format type", "format", format);
5233 }
5234 if (format === FormatTypes.json) {
5235 return JSON.stringify({
5236 type: "event",
5237 anonymous: this.anonymous,
5238 name: this.name,
5239 inputs: this.inputs.map((input) => JSON.parse(input.format(format)))
5240 });
5241 }
5242 let result = "";
5243 if (format !== FormatTypes.sighash) {
5244 result += "event ";
5245 }
5246 result += this.name + "(" + this.inputs.map((input) => input.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ") ";
5247 if (format !== FormatTypes.sighash) {
5248 if (this.anonymous) {
5249 result += "anonymous ";
5250 }
5251 }
5252 return result.trim();
5253 }
5254 static from(value) {
5255 if (typeof (value) === "string") {
5256 return EventFragment.fromString(value);
5257 }
5258 return EventFragment.fromObject(value);
5259 }
5260 static fromObject(value) {
5261 if (EventFragment.isEventFragment(value)) {
5262 return value;
5263 }
5264 if (value.type !== "event") {
5265 logger$4.throwArgumentError("invalid event object", "value", value);
5266 }
5267 const params = {
5268 name: verifyIdentifier(value.name),
5269 anonymous: value.anonymous,
5270 inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
5271 type: "event"
5272 };
5273 return new EventFragment(_constructorGuard$2, params);
5274 }
5275 static fromString(value) {
5276 let match = value.match(regexParen);
5277 if (!match) {
5278 logger$4.throwArgumentError("invalid event string", "value", value);
5279 }
5280 let anonymous = false;
5281 match[3].split(" ").forEach((modifier) => {
5282 switch (modifier.trim()) {
5283 case "anonymous":
5284 anonymous = true;
5285 break;
5286 case "":
5287 break;
5288 default:
5289 logger$4.warn("unknown modifier: " + modifier);
5290 }
5291 });
5292 return EventFragment.fromObject({
5293 name: match[1].trim(),
5294 anonymous: anonymous,
5295 inputs: parseParams(match[2], true),
5296 type: "event"
5297 });
5298 }
5299 static isEventFragment(value) {
5300 return (value && value._isFragment && value.type === "event");
5301 }
5302}
5303function parseGas(value, params) {
5304 params.gas = null;
5305 let comps = value.split("@");
5306 if (comps.length !== 1) {
5307 if (comps.length > 2) {
5308 logger$4.throwArgumentError("invalid human-readable ABI signature", "value", value);
5309 }
5310 if (!comps[1].match(/^[0-9]+$/)) {
5311 logger$4.throwArgumentError("invalid human-readable ABI signature gas", "value", value);
5312 }
5313 params.gas = BigNumber.from(comps[1]);
5314 return comps[0];
5315 }
5316 return value;
5317}
5318function parseModifiers(value, params) {
5319 params.constant = false;
5320 params.payable = false;
5321 params.stateMutability = "nonpayable";
5322 value.split(" ").forEach((modifier) => {
5323 switch (modifier.trim()) {
5324 case "constant":
5325 params.constant = true;
5326 break;
5327 case "payable":
5328 params.payable = true;
5329 params.stateMutability = "payable";
5330 break;
5331 case "nonpayable":
5332 params.payable = false;
5333 params.stateMutability = "nonpayable";
5334 break;
5335 case "pure":
5336 params.constant = true;
5337 params.stateMutability = "pure";
5338 break;
5339 case "view":
5340 params.constant = true;
5341 params.stateMutability = "view";
5342 break;
5343 case "external":
5344 case "public":
5345 case "":
5346 break;
5347 default:
5348 console.log("unknown modifier: " + modifier);
5349 }
5350 });
5351}
5352function verifyState(value) {
5353 let result = {
5354 constant: false,
5355 payable: true,
5356 stateMutability: "payable"
5357 };
5358 if (value.stateMutability != null) {
5359 result.stateMutability = value.stateMutability;
5360 // Set (and check things are consistent) the constant property
5361 result.constant = (result.stateMutability === "view" || result.stateMutability === "pure");
5362 if (value.constant != null) {
5363 if ((!!value.constant) !== result.constant) {
5364 logger$4.throwArgumentError("cannot have constant function with mutability " + result.stateMutability, "value", value);
5365 }
5366 }
5367 // Set (and check things are consistent) the payable property
5368 result.payable = (result.stateMutability === "payable");
5369 if (value.payable != null) {
5370 if ((!!value.payable) !== result.payable) {
5371 logger$4.throwArgumentError("cannot have payable function with mutability " + result.stateMutability, "value", value);
5372 }
5373 }
5374 }
5375 else if (value.payable != null) {
5376 result.payable = !!value.payable;
5377 // If payable we can assume non-constant; otherwise we can't assume
5378 if (value.constant == null && !result.payable && value.type !== "constructor") {
5379 logger$4.throwArgumentError("unable to determine stateMutability", "value", value);
5380 }
5381 result.constant = !!value.constant;
5382 if (result.constant) {
5383 result.stateMutability = "view";
5384 }
5385 else {
5386 result.stateMutability = (result.payable ? "payable" : "nonpayable");
5387 }
5388 if (result.payable && result.constant) {
5389 logger$4.throwArgumentError("cannot have constant payable function", "value", value);
5390 }
5391 }
5392 else if (value.constant != null) {
5393 result.constant = !!value.constant;
5394 result.payable = !result.constant;
5395 result.stateMutability = (result.constant ? "view" : "payable");
5396 }
5397 else if (value.type !== "constructor") {
5398 logger$4.throwArgumentError("unable to determine stateMutability", "value", value);
5399 }
5400 return result;
5401}
5402class ConstructorFragment extends Fragment {
5403 format(format) {
5404 if (!format) {
5405 format = FormatTypes.sighash;
5406 }
5407 if (!FormatTypes[format]) {
5408 logger$4.throwArgumentError("invalid format type", "format", format);
5409 }
5410 if (format === FormatTypes.json) {
5411 return JSON.stringify({
5412 type: "constructor",
5413 stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
5414 payble: this.payable,
5415 gas: (this.gas ? this.gas.toNumber() : undefined),
5416 inputs: this.inputs.map((input) => JSON.parse(input.format(format)))
5417 });
5418 }
5419 if (format === FormatTypes.sighash) {
5420 logger$4.throwError("cannot format a constructor for sighash", Logger.errors.UNSUPPORTED_OPERATION, {
5421 operation: "format(sighash)"
5422 });
5423 }
5424 let result = "constructor(" + this.inputs.map((input) => input.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ") ";
5425 if (this.stateMutability && this.stateMutability !== "nonpayable") {
5426 result += this.stateMutability + " ";
5427 }
5428 return result.trim();
5429 }
5430 static from(value) {
5431 if (typeof (value) === "string") {
5432 return ConstructorFragment.fromString(value);
5433 }
5434 return ConstructorFragment.fromObject(value);
5435 }
5436 static fromObject(value) {
5437 if (ConstructorFragment.isConstructorFragment(value)) {
5438 return value;
5439 }
5440 if (value.type !== "constructor") {
5441 logger$4.throwArgumentError("invalid constructor object", "value", value);
5442 }
5443 let state = verifyState(value);
5444 if (state.constant) {
5445 logger$4.throwArgumentError("constructor cannot be constant", "value", value);
5446 }
5447 const params = {
5448 name: null,
5449 type: value.type,
5450 inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
5451 payable: state.payable,
5452 stateMutability: state.stateMutability,
5453 gas: (value.gas ? BigNumber.from(value.gas) : null)
5454 };
5455 return new ConstructorFragment(_constructorGuard$2, params);
5456 }
5457 static fromString(value) {
5458 let params = { type: "constructor" };
5459 value = parseGas(value, params);
5460 let parens = value.match(regexParen);
5461 if (!parens || parens[1].trim() !== "constructor") {
5462 logger$4.throwArgumentError("invalid constructor string", "value", value);
5463 }
5464 params.inputs = parseParams(parens[2].trim(), false);
5465 parseModifiers(parens[3].trim(), params);
5466 return ConstructorFragment.fromObject(params);
5467 }
5468 static isConstructorFragment(value) {
5469 return (value && value._isFragment && value.type === "constructor");
5470 }
5471}
5472class FunctionFragment extends ConstructorFragment {
5473 format(format) {
5474 if (!format) {
5475 format = FormatTypes.sighash;
5476 }
5477 if (!FormatTypes[format]) {
5478 logger$4.throwArgumentError("invalid format type", "format", format);
5479 }
5480 if (format === FormatTypes.json) {
5481 return JSON.stringify({
5482 type: "function",
5483 name: this.name,
5484 constant: this.constant,
5485 stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
5486 payble: this.payable,
5487 gas: (this.gas ? this.gas.toNumber() : undefined),
5488 inputs: this.inputs.map((input) => JSON.parse(input.format(format))),
5489 ouputs: this.outputs.map((output) => JSON.parse(output.format(format))),
5490 });
5491 }
5492 let result = "";
5493 if (format !== FormatTypes.sighash) {
5494 result += "function ";
5495 }
5496 result += this.name + "(" + this.inputs.map((input) => input.format(format)).join((format === FormatTypes.full) ? ", " : ",") + ") ";
5497 if (format !== FormatTypes.sighash) {
5498 if (this.stateMutability) {
5499 if (this.stateMutability !== "nonpayable") {
5500 result += (this.stateMutability + " ");
5501 }
5502 }
5503 else if (this.constant) {
5504 result += "view ";
5505 }
5506 if (this.outputs && this.outputs.length) {
5507 result += "returns (" + this.outputs.map((output) => output.format(format)).join(", ") + ") ";
5508 }
5509 if (this.gas != null) {
5510 result += "@" + this.gas.toString() + " ";
5511 }
5512 }
5513 return result.trim();
5514 }
5515 static from(value) {
5516 if (typeof (value) === "string") {
5517 return FunctionFragment.fromString(value);
5518 }
5519 return FunctionFragment.fromObject(value);
5520 }
5521 static fromObject(value) {
5522 if (FunctionFragment.isFunctionFragment(value)) {
5523 return value;
5524 }
5525 if (value.type !== "function") {
5526 logger$4.throwArgumentError("invalid function object", "value", value);
5527 }
5528 let state = verifyState(value);
5529 const params = {
5530 type: value.type,
5531 name: verifyIdentifier(value.name),
5532 constant: state.constant,
5533 inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
5534 outputs: (value.outputs ? value.outputs.map(ParamType.fromObject) : []),
5535 payable: state.payable,
5536 stateMutability: state.stateMutability,
5537 gas: (value.gas ? BigNumber.from(value.gas) : null)
5538 };
5539 return new FunctionFragment(_constructorGuard$2, params);
5540 }
5541 static fromString(value) {
5542 let params = { type: "function" };
5543 value = parseGas(value, params);
5544 let comps = value.split(" returns ");
5545 if (comps.length > 2) {
5546 logger$4.throwArgumentError("invalid function string", "value", value);
5547 }
5548 let parens = comps[0].match(regexParen);
5549 if (!parens) {
5550 logger$4.throwArgumentError("invalid function signature", "value", value);
5551 }
5552 params.name = parens[1].trim();
5553 if (params.name) {
5554 verifyIdentifier(params.name);
5555 }
5556 params.inputs = parseParams(parens[2], false);
5557 parseModifiers(parens[3].trim(), params);
5558 // We have outputs
5559 if (comps.length > 1) {
5560 let returns = comps[1].match(regexParen);
5561 if (returns[1].trim() != "" || returns[3].trim() != "") {
5562 logger$4.throwArgumentError("unexpected tokens", "value", value);
5563 }
5564 params.outputs = parseParams(returns[2], false);
5565 }
5566 else {
5567 params.outputs = [];
5568 }
5569 return FunctionFragment.fromObject(params);
5570 }
5571 static isFunctionFragment(value) {
5572 return (value && value._isFragment && value.type === "function");
5573 }
5574}
5575//export class ErrorFragment extends Fragment {
5576//}
5577//export class StructFragment extends Fragment {
5578//}
5579function verifyType(type) {
5580 // These need to be transformed to their full description
5581 if (type.match(/^uint($|[^1-9])/)) {
5582 type = "uint256" + type.substring(4);
5583 }
5584 else if (type.match(/^int($|[^1-9])/)) {
5585 type = "int256" + type.substring(3);
5586 }
5587 // @TODO: more verification
5588 return type;
5589}
5590const regexIdentifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");
5591function verifyIdentifier(value) {
5592 if (!value || !value.match(regexIdentifier)) {
5593 logger$4.throwArgumentError(`invalid identifier "${value}"`, "value", value);
5594 }
5595 return value;
5596}
5597const regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$");
5598function splitNesting(value) {
5599 value = value.trim();
5600 let result = [];
5601 let accum = "";
5602 let depth = 0;
5603 for (let offset = 0; offset < value.length; offset++) {
5604 let c = value[offset];
5605 if (c === "," && depth === 0) {
5606 result.push(accum);
5607 accum = "";
5608 }
5609 else {
5610 accum += c;
5611 if (c === "(") {
5612 depth++;
5613 }
5614 else if (c === ")") {
5615 depth--;
5616 if (depth === -1) {
5617 logger$4.throwArgumentError("unbalanced parenthesis", "value", value);
5618 }
5619 }
5620 }
5621 }
5622 if (accum) {
5623 result.push(accum);
5624 }
5625 return result;
5626}
5627
5628"use strict";
5629const logger$5 = new Logger(version$4);
5630function checkResultErrors(result) {
5631 // Find the first error (if any)
5632 const errors = [];
5633 const checkErrors = function (path, object) {
5634 if (!Array.isArray(object)) {
5635 return;
5636 }
5637 for (let key in object) {
5638 const childPath = path.slice();
5639 childPath.push(key);
5640 try {
5641 checkErrors(childPath, object[key]);
5642 }
5643 catch (error) {
5644 errors.push({ path: childPath, error: error });
5645 }
5646 }
5647 };
5648 checkErrors([], result);
5649 return errors;
5650}
5651class Coder {
5652 constructor(name, type, localName, dynamic) {
5653 // @TODO: defineReadOnly these
5654 this.name = name;
5655 this.type = type;
5656 this.localName = localName;
5657 this.dynamic = dynamic;
5658 }
5659 _throwError(message, value) {
5660 logger$5.throwArgumentError(message, this.localName, value);
5661 }
5662}
5663class Writer {
5664 constructor(wordSize) {
5665 defineReadOnly(this, "wordSize", wordSize || 32);
5666 this._data = arrayify([]);
5667 this._padding = new Uint8Array(wordSize);
5668 }
5669 get data() { return hexlify(this._data); }
5670 get length() { return this._data.length; }
5671 _writeData(data) {
5672 this._data = concat([this._data, data]);
5673 return data.length;
5674 }
5675 // Arrayish items; padded on the right to wordSize
5676 writeBytes(value) {
5677 let bytes = arrayify(value);
5678 if (bytes.length % this.wordSize) {
5679 bytes = concat([bytes, this._padding.slice(bytes.length % this.wordSize)]);
5680 }
5681 return this._writeData(bytes);
5682 }
5683 _getValue(value) {
5684 let bytes = arrayify(BigNumber.from(value));
5685 if (bytes.length > this.wordSize) {
5686 logger$5.throwError("value out-of-bounds", Logger.errors.BUFFER_OVERRUN, {
5687 length: this.wordSize,
5688 offset: bytes.length
5689 });
5690 }
5691 if (bytes.length % this.wordSize) {
5692 bytes = concat([this._padding.slice(bytes.length % this.wordSize), bytes]);
5693 }
5694 return bytes;
5695 }
5696 // BigNumberish items; padded on the left to wordSize
5697 writeValue(value) {
5698 return this._writeData(this._getValue(value));
5699 }
5700 writeUpdatableValue() {
5701 let offset = this.length;
5702 this.writeValue(0);
5703 return (value) => {
5704 this._data.set(this._getValue(value), offset);
5705 };
5706 }
5707}
5708class Reader {
5709 constructor(data, wordSize, coerceFunc) {
5710 defineReadOnly(this, "_data", arrayify(data));
5711 defineReadOnly(this, "wordSize", wordSize || 32);
5712 defineReadOnly(this, "_coerceFunc", coerceFunc);
5713 this._offset = 0;
5714 }
5715 get data() { return hexlify(this._data); }
5716 get consumed() { return this._offset; }
5717 // The default Coerce function
5718 static coerce(name, value) {
5719 let match = name.match("^u?int([0-9]+)$");
5720 if (match && parseInt(match[1]) <= 48) {
5721 value = value.toNumber();
5722 }
5723 return value;
5724 }
5725 coerce(name, value) {
5726 if (this._coerceFunc) {
5727 return this._coerceFunc(name, value);
5728 }
5729 return Reader.coerce(name, value);
5730 }
5731 _peekBytes(offset, length) {
5732 let alignedLength = Math.ceil(length / this.wordSize) * this.wordSize;
5733 if (this._offset + alignedLength > this._data.length) {
5734 logger$5.throwError("data out-of-bounds", Logger.errors.BUFFER_OVERRUN, {
5735 length: this._data.length,
5736 offset: this._offset + alignedLength
5737 });
5738 }
5739 return this._data.slice(this._offset, this._offset + alignedLength);
5740 }
5741 subReader(offset) {
5742 return new Reader(this._data.slice(this._offset + offset), this.wordSize, this._coerceFunc);
5743 }
5744 readBytes(length) {
5745 let bytes = this._peekBytes(0, length);
5746 this._offset += bytes.length;
5747 // @TODO: Make sure the length..end bytes are all 0?
5748 return bytes.slice(0, length);
5749 }
5750 readValue() {
5751 return BigNumber.from(this.readBytes(this.wordSize));
5752 }
5753}
5754
5755var sha3 = createCommonjsModule(function (module) {
5756/**
5757 * [js-sha3]{@link https://github.com/emn178/js-sha3}
5758 *
5759 * @version 0.5.7
5760 * @author Chen, Yi-Cyuan [emn178@gmail.com]
5761 * @copyright Chen, Yi-Cyuan 2015-2016
5762 * @license MIT
5763 */
5764/*jslint bitwise: true */
5765(function () {
5766 'use strict';
5767
5768 var root = typeof window === 'object' ? window : {};
5769 var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
5770 if (NODE_JS) {
5771 root = commonjsGlobal;
5772 }
5773 var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && 'object' === 'object' && module.exports;
5774 var HEX_CHARS = '0123456789abcdef'.split('');
5775 var SHAKE_PADDING = [31, 7936, 2031616, 520093696];
5776 var KECCAK_PADDING = [1, 256, 65536, 16777216];
5777 var PADDING = [6, 1536, 393216, 100663296];
5778 var SHIFT = [0, 8, 16, 24];
5779 var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
5780 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,
5781 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,
5782 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
5783 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
5784 var BITS = [224, 256, 384, 512];
5785 var SHAKE_BITS = [128, 256];
5786 var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array'];
5787
5788 var createOutputMethod = function (bits, padding, outputType) {
5789 return function (message) {
5790 return new Keccak(bits, padding, bits).update(message)[outputType]();
5791 };
5792 };
5793
5794 var createShakeOutputMethod = function (bits, padding, outputType) {
5795 return function (message, outputBits) {
5796 return new Keccak(bits, padding, outputBits).update(message)[outputType]();
5797 };
5798 };
5799
5800 var createMethod = function (bits, padding) {
5801 var method = createOutputMethod(bits, padding, 'hex');
5802 method.create = function () {
5803 return new Keccak(bits, padding, bits);
5804 };
5805 method.update = function (message) {
5806 return method.create().update(message);
5807 };
5808 for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
5809 var type = OUTPUT_TYPES[i];
5810 method[type] = createOutputMethod(bits, padding, type);
5811 }
5812 return method;
5813 };
5814
5815 var createShakeMethod = function (bits, padding) {
5816 var method = createShakeOutputMethod(bits, padding, 'hex');
5817 method.create = function (outputBits) {
5818 return new Keccak(bits, padding, outputBits);
5819 };
5820 method.update = function (message, outputBits) {
5821 return method.create(outputBits).update(message);
5822 };
5823 for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
5824 var type = OUTPUT_TYPES[i];
5825 method[type] = createShakeOutputMethod(bits, padding, type);
5826 }
5827 return method;
5828 };
5829
5830 var algorithms = [
5831 {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod},
5832 {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod},
5833 {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod}
5834 ];
5835
5836 var methods = {}, methodNames = [];
5837
5838 for (var i = 0; i < algorithms.length; ++i) {
5839 var algorithm = algorithms[i];
5840 var bits = algorithm.bits;
5841 for (var j = 0; j < bits.length; ++j) {
5842 var methodName = algorithm.name +'_' + bits[j];
5843 methodNames.push(methodName);
5844 methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);
5845 }
5846 }
5847
5848 function Keccak(bits, padding, outputBits) {
5849 this.blocks = [];
5850 this.s = [];
5851 this.padding = padding;
5852 this.outputBits = outputBits;
5853 this.reset = true;
5854 this.block = 0;
5855 this.start = 0;
5856 this.blockCount = (1600 - (bits << 1)) >> 5;
5857 this.byteCount = this.blockCount << 2;
5858 this.outputBlocks = outputBits >> 5;
5859 this.extraBytes = (outputBits & 31) >> 3;
5860
5861 for (var i = 0; i < 50; ++i) {
5862 this.s[i] = 0;
5863 }
5864 }
5865
5866 Keccak.prototype.update = function (message) {
5867 var notString = typeof message !== 'string';
5868 if (notString && message.constructor === ArrayBuffer) {
5869 message = new Uint8Array(message);
5870 }
5871 var length = message.length, blocks = this.blocks, byteCount = this.byteCount,
5872 blockCount = this.blockCount, index = 0, s = this.s, i, code;
5873
5874 while (index < length) {
5875 if (this.reset) {
5876 this.reset = false;
5877 blocks[0] = this.block;
5878 for (i = 1; i < blockCount + 1; ++i) {
5879 blocks[i] = 0;
5880 }
5881 }
5882 if (notString) {
5883 for (i = this.start; index < length && i < byteCount; ++index) {
5884 blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
5885 }
5886 } else {
5887 for (i = this.start; index < length && i < byteCount; ++index) {
5888 code = message.charCodeAt(index);
5889 if (code < 0x80) {
5890 blocks[i >> 2] |= code << SHIFT[i++ & 3];
5891 } else if (code < 0x800) {
5892 blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
5893 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
5894 } else if (code < 0xd800 || code >= 0xe000) {
5895 blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
5896 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
5897 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
5898 } else {
5899 code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
5900 blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
5901 blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
5902 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
5903 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
5904 }
5905 }
5906 }
5907 this.lastByteIndex = i;
5908 if (i >= byteCount) {
5909 this.start = i - byteCount;
5910 this.block = blocks[blockCount];
5911 for (i = 0; i < blockCount; ++i) {
5912 s[i] ^= blocks[i];
5913 }
5914 f(s);
5915 this.reset = true;
5916 } else {
5917 this.start = i;
5918 }
5919 }
5920 return this;
5921 };
5922
5923 Keccak.prototype.finalize = function () {
5924 var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
5925 blocks[i >> 2] |= this.padding[i & 3];
5926 if (this.lastByteIndex === this.byteCount) {
5927 blocks[0] = blocks[blockCount];
5928 for (i = 1; i < blockCount + 1; ++i) {
5929 blocks[i] = 0;
5930 }
5931 }
5932 blocks[blockCount - 1] |= 0x80000000;
5933 for (i = 0; i < blockCount; ++i) {
5934 s[i] ^= blocks[i];
5935 }
5936 f(s);
5937 };
5938
5939 Keccak.prototype.toString = Keccak.prototype.hex = function () {
5940 this.finalize();
5941
5942 var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
5943 extraBytes = this.extraBytes, i = 0, j = 0;
5944 var hex = '', block;
5945 while (j < outputBlocks) {
5946 for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
5947 block = s[i];
5948 hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +
5949 HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +
5950 HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +
5951 HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
5952 }
5953 if (j % blockCount === 0) {
5954 f(s);
5955 i = 0;
5956 }
5957 }
5958 if (extraBytes) {
5959 block = s[i];
5960 if (extraBytes > 0) {
5961 hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
5962 }
5963 if (extraBytes > 1) {
5964 hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
5965 }
5966 if (extraBytes > 2) {
5967 hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
5968 }
5969 }
5970 return hex;
5971 };
5972
5973 Keccak.prototype.arrayBuffer = function () {
5974 this.finalize();
5975
5976 var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
5977 extraBytes = this.extraBytes, i = 0, j = 0;
5978 var bytes = this.outputBits >> 3;
5979 var buffer;
5980 if (extraBytes) {
5981 buffer = new ArrayBuffer((outputBlocks + 1) << 2);
5982 } else {
5983 buffer = new ArrayBuffer(bytes);
5984 }
5985 var array = new Uint32Array(buffer);
5986 while (j < outputBlocks) {
5987 for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
5988 array[j] = s[i];
5989 }
5990 if (j % blockCount === 0) {
5991 f(s);
5992 }
5993 }
5994 if (extraBytes) {
5995 array[i] = s[i];
5996 buffer = buffer.slice(0, bytes);
5997 }
5998 return buffer;
5999 };
6000
6001 Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
6002
6003 Keccak.prototype.digest = Keccak.prototype.array = function () {
6004 this.finalize();
6005
6006 var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
6007 extraBytes = this.extraBytes, i = 0, j = 0;
6008 var array = [], offset, block;
6009 while (j < outputBlocks) {
6010 for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
6011 offset = j << 2;
6012 block = s[i];
6013 array[offset] = block & 0xFF;
6014 array[offset + 1] = (block >> 8) & 0xFF;
6015 array[offset + 2] = (block >> 16) & 0xFF;
6016 array[offset + 3] = (block >> 24) & 0xFF;
6017 }
6018 if (j % blockCount === 0) {
6019 f(s);
6020 }
6021 }
6022 if (extraBytes) {
6023 offset = j << 2;
6024 block = s[i];
6025 if (extraBytes > 0) {
6026 array[offset] = block & 0xFF;
6027 }
6028 if (extraBytes > 1) {
6029 array[offset + 1] = (block >> 8) & 0xFF;
6030 }
6031 if (extraBytes > 2) {
6032 array[offset + 2] = (block >> 16) & 0xFF;
6033 }
6034 }
6035 return array;
6036 };
6037
6038 var f = function (s) {
6039 var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,
6040 b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,
6041 b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,
6042 b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
6043 for (n = 0; n < 48; n += 2) {
6044 c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
6045 c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
6046 c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
6047 c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
6048 c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
6049 c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
6050 c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
6051 c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
6052 c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
6053 c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
6054
6055 h = c8 ^ ((c2 << 1) | (c3 >>> 31));
6056 l = c9 ^ ((c3 << 1) | (c2 >>> 31));
6057 s[0] ^= h;
6058 s[1] ^= l;
6059 s[10] ^= h;
6060 s[11] ^= l;
6061 s[20] ^= h;
6062 s[21] ^= l;
6063 s[30] ^= h;
6064 s[31] ^= l;
6065 s[40] ^= h;
6066 s[41] ^= l;
6067 h = c0 ^ ((c4 << 1) | (c5 >>> 31));
6068 l = c1 ^ ((c5 << 1) | (c4 >>> 31));
6069 s[2] ^= h;
6070 s[3] ^= l;
6071 s[12] ^= h;
6072 s[13] ^= l;
6073 s[22] ^= h;
6074 s[23] ^= l;
6075 s[32] ^= h;
6076 s[33] ^= l;
6077 s[42] ^= h;
6078 s[43] ^= l;
6079 h = c2 ^ ((c6 << 1) | (c7 >>> 31));
6080 l = c3 ^ ((c7 << 1) | (c6 >>> 31));
6081 s[4] ^= h;
6082 s[5] ^= l;
6083 s[14] ^= h;
6084 s[15] ^= l;
6085 s[24] ^= h;
6086 s[25] ^= l;
6087 s[34] ^= h;
6088 s[35] ^= l;
6089 s[44] ^= h;
6090 s[45] ^= l;
6091 h = c4 ^ ((c8 << 1) | (c9 >>> 31));
6092 l = c5 ^ ((c9 << 1) | (c8 >>> 31));
6093 s[6] ^= h;
6094 s[7] ^= l;
6095 s[16] ^= h;
6096 s[17] ^= l;
6097 s[26] ^= h;
6098 s[27] ^= l;
6099 s[36] ^= h;
6100 s[37] ^= l;
6101 s[46] ^= h;
6102 s[47] ^= l;
6103 h = c6 ^ ((c0 << 1) | (c1 >>> 31));
6104 l = c7 ^ ((c1 << 1) | (c0 >>> 31));
6105 s[8] ^= h;
6106 s[9] ^= l;
6107 s[18] ^= h;
6108 s[19] ^= l;
6109 s[28] ^= h;
6110 s[29] ^= l;
6111 s[38] ^= h;
6112 s[39] ^= l;
6113 s[48] ^= h;
6114 s[49] ^= l;
6115
6116 b0 = s[0];
6117 b1 = s[1];
6118 b32 = (s[11] << 4) | (s[10] >>> 28);
6119 b33 = (s[10] << 4) | (s[11] >>> 28);
6120 b14 = (s[20] << 3) | (s[21] >>> 29);
6121 b15 = (s[21] << 3) | (s[20] >>> 29);
6122 b46 = (s[31] << 9) | (s[30] >>> 23);
6123 b47 = (s[30] << 9) | (s[31] >>> 23);
6124 b28 = (s[40] << 18) | (s[41] >>> 14);
6125 b29 = (s[41] << 18) | (s[40] >>> 14);
6126 b20 = (s[2] << 1) | (s[3] >>> 31);
6127 b21 = (s[3] << 1) | (s[2] >>> 31);
6128 b2 = (s[13] << 12) | (s[12] >>> 20);
6129 b3 = (s[12] << 12) | (s[13] >>> 20);
6130 b34 = (s[22] << 10) | (s[23] >>> 22);
6131 b35 = (s[23] << 10) | (s[22] >>> 22);
6132 b16 = (s[33] << 13) | (s[32] >>> 19);
6133 b17 = (s[32] << 13) | (s[33] >>> 19);
6134 b48 = (s[42] << 2) | (s[43] >>> 30);
6135 b49 = (s[43] << 2) | (s[42] >>> 30);
6136 b40 = (s[5] << 30) | (s[4] >>> 2);
6137 b41 = (s[4] << 30) | (s[5] >>> 2);
6138 b22 = (s[14] << 6) | (s[15] >>> 26);
6139 b23 = (s[15] << 6) | (s[14] >>> 26);
6140 b4 = (s[25] << 11) | (s[24] >>> 21);
6141 b5 = (s[24] << 11) | (s[25] >>> 21);
6142 b36 = (s[34] << 15) | (s[35] >>> 17);
6143 b37 = (s[35] << 15) | (s[34] >>> 17);
6144 b18 = (s[45] << 29) | (s[44] >>> 3);
6145 b19 = (s[44] << 29) | (s[45] >>> 3);
6146 b10 = (s[6] << 28) | (s[7] >>> 4);
6147 b11 = (s[7] << 28) | (s[6] >>> 4);
6148 b42 = (s[17] << 23) | (s[16] >>> 9);
6149 b43 = (s[16] << 23) | (s[17] >>> 9);
6150 b24 = (s[26] << 25) | (s[27] >>> 7);
6151 b25 = (s[27] << 25) | (s[26] >>> 7);
6152 b6 = (s[36] << 21) | (s[37] >>> 11);
6153 b7 = (s[37] << 21) | (s[36] >>> 11);
6154 b38 = (s[47] << 24) | (s[46] >>> 8);
6155 b39 = (s[46] << 24) | (s[47] >>> 8);
6156 b30 = (s[8] << 27) | (s[9] >>> 5);
6157 b31 = (s[9] << 27) | (s[8] >>> 5);
6158 b12 = (s[18] << 20) | (s[19] >>> 12);
6159 b13 = (s[19] << 20) | (s[18] >>> 12);
6160 b44 = (s[29] << 7) | (s[28] >>> 25);
6161 b45 = (s[28] << 7) | (s[29] >>> 25);
6162 b26 = (s[38] << 8) | (s[39] >>> 24);
6163 b27 = (s[39] << 8) | (s[38] >>> 24);
6164 b8 = (s[48] << 14) | (s[49] >>> 18);
6165 b9 = (s[49] << 14) | (s[48] >>> 18);
6166
6167 s[0] = b0 ^ (~b2 & b4);
6168 s[1] = b1 ^ (~b3 & b5);
6169 s[10] = b10 ^ (~b12 & b14);
6170 s[11] = b11 ^ (~b13 & b15);
6171 s[20] = b20 ^ (~b22 & b24);
6172 s[21] = b21 ^ (~b23 & b25);
6173 s[30] = b30 ^ (~b32 & b34);
6174 s[31] = b31 ^ (~b33 & b35);
6175 s[40] = b40 ^ (~b42 & b44);
6176 s[41] = b41 ^ (~b43 & b45);
6177 s[2] = b2 ^ (~b4 & b6);
6178 s[3] = b3 ^ (~b5 & b7);
6179 s[12] = b12 ^ (~b14 & b16);
6180 s[13] = b13 ^ (~b15 & b17);
6181 s[22] = b22 ^ (~b24 & b26);
6182 s[23] = b23 ^ (~b25 & b27);
6183 s[32] = b32 ^ (~b34 & b36);
6184 s[33] = b33 ^ (~b35 & b37);
6185 s[42] = b42 ^ (~b44 & b46);
6186 s[43] = b43 ^ (~b45 & b47);
6187 s[4] = b4 ^ (~b6 & b8);
6188 s[5] = b5 ^ (~b7 & b9);
6189 s[14] = b14 ^ (~b16 & b18);
6190 s[15] = b15 ^ (~b17 & b19);
6191 s[24] = b24 ^ (~b26 & b28);
6192 s[25] = b25 ^ (~b27 & b29);
6193 s[34] = b34 ^ (~b36 & b38);
6194 s[35] = b35 ^ (~b37 & b39);
6195 s[44] = b44 ^ (~b46 & b48);
6196 s[45] = b45 ^ (~b47 & b49);
6197 s[6] = b6 ^ (~b8 & b0);
6198 s[7] = b7 ^ (~b9 & b1);
6199 s[16] = b16 ^ (~b18 & b10);
6200 s[17] = b17 ^ (~b19 & b11);
6201 s[26] = b26 ^ (~b28 & b20);
6202 s[27] = b27 ^ (~b29 & b21);
6203 s[36] = b36 ^ (~b38 & b30);
6204 s[37] = b37 ^ (~b39 & b31);
6205 s[46] = b46 ^ (~b48 & b40);
6206 s[47] = b47 ^ (~b49 & b41);
6207 s[8] = b8 ^ (~b0 & b2);
6208 s[9] = b9 ^ (~b1 & b3);
6209 s[18] = b18 ^ (~b10 & b12);
6210 s[19] = b19 ^ (~b11 & b13);
6211 s[28] = b28 ^ (~b20 & b22);
6212 s[29] = b29 ^ (~b21 & b23);
6213 s[38] = b38 ^ (~b30 & b32);
6214 s[39] = b39 ^ (~b31 & b33);
6215 s[48] = b48 ^ (~b40 & b42);
6216 s[49] = b49 ^ (~b41 & b43);
6217
6218 s[0] ^= RC[n];
6219 s[1] ^= RC[n + 1];
6220 }
6221 };
6222
6223 if (COMMON_JS) {
6224 module.exports = methods;
6225 } else {
6226 for (var i = 0; i < methodNames.length; ++i) {
6227 root[methodNames[i]] = methods[methodNames[i]];
6228 }
6229 }
6230})();
6231});
6232
6233"use strict";
6234function keccak256(data) {
6235 return '0x' + sha3.keccak_256(arrayify(data));
6236}
6237
6238const version$5 = "rlp/5.0.2";
6239
6240"use strict";
6241const logger$6 = new Logger(version$5);
6242function arrayifyInteger(value) {
6243 const result = [];
6244 while (value) {
6245 result.unshift(value & 0xff);
6246 value >>= 8;
6247 }
6248 return result;
6249}
6250function unarrayifyInteger(data, offset, length) {
6251 let result = 0;
6252 for (let i = 0; i < length; i++) {
6253 result = (result * 256) + data[offset + i];
6254 }
6255 return result;
6256}
6257function _encode(object) {
6258 if (Array.isArray(object)) {
6259 let payload = [];
6260 object.forEach(function (child) {
6261 payload = payload.concat(_encode(child));
6262 });
6263 if (payload.length <= 55) {
6264 payload.unshift(0xc0 + payload.length);
6265 return payload;
6266 }
6267 const length = arrayifyInteger(payload.length);
6268 length.unshift(0xf7 + length.length);
6269 return length.concat(payload);
6270 }
6271 if (!isBytesLike(object)) {
6272 logger$6.throwArgumentError("RLP object must be BytesLike", "object", object);
6273 }
6274 const data = Array.prototype.slice.call(arrayify(object));
6275 if (data.length === 1 && data[0] <= 0x7f) {
6276 return data;
6277 }
6278 else if (data.length <= 55) {
6279 data.unshift(0x80 + data.length);
6280 return data;
6281 }
6282 const length = arrayifyInteger(data.length);
6283 length.unshift(0xb7 + length.length);
6284 return length.concat(data);
6285}
6286function encode(object) {
6287 return hexlify(_encode(object));
6288}
6289function _decodeChildren(data, offset, childOffset, length) {
6290 const result = [];
6291 while (childOffset < offset + 1 + length) {
6292 const decoded = _decode(data, childOffset);
6293 result.push(decoded.result);
6294 childOffset += decoded.consumed;
6295 if (childOffset > offset + 1 + length) {
6296 logger$6.throwError("child data too short", Logger.errors.BUFFER_OVERRUN, {});
6297 }
6298 }
6299 return { consumed: (1 + length), result: result };
6300}
6301// returns { consumed: number, result: Object }
6302function _decode(data, offset) {
6303 if (data.length === 0) {
6304 logger$6.throwError("data too short", Logger.errors.BUFFER_OVERRUN, {});
6305 }
6306 // Array with extra length prefix
6307 if (data[offset] >= 0xf8) {
6308 const lengthLength = data[offset] - 0xf7;
6309 if (offset + 1 + lengthLength > data.length) {
6310 logger$6.throwError("data short segment too short", Logger.errors.BUFFER_OVERRUN, {});
6311 }
6312 const length = unarrayifyInteger(data, offset + 1, lengthLength);
6313 if (offset + 1 + lengthLength + length > data.length) {
6314 logger$6.throwError("data long segment too short", Logger.errors.BUFFER_OVERRUN, {});
6315 }
6316 return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);
6317 }
6318 else if (data[offset] >= 0xc0) {
6319 const length = data[offset] - 0xc0;
6320 if (offset + 1 + length > data.length) {
6321 logger$6.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {});
6322 }
6323 return _decodeChildren(data, offset, offset + 1, length);
6324 }
6325 else if (data[offset] >= 0xb8) {
6326 const lengthLength = data[offset] - 0xb7;
6327 if (offset + 1 + lengthLength > data.length) {
6328 logger$6.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {});
6329 }
6330 const length = unarrayifyInteger(data, offset + 1, lengthLength);
6331 if (offset + 1 + lengthLength + length > data.length) {
6332 logger$6.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {});
6333 }
6334 const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));
6335 return { consumed: (1 + lengthLength + length), result: result };
6336 }
6337 else if (data[offset] >= 0x80) {
6338 const length = data[offset] - 0x80;
6339 if (offset + 1 + length > data.length) {
6340 logger$6.throwError("data too short", Logger.errors.BUFFER_OVERRUN, {});
6341 }
6342 const result = hexlify(data.slice(offset + 1, offset + 1 + length));
6343 return { consumed: (1 + length), result: result };
6344 }
6345 return { consumed: 1, result: hexlify(data[offset]) };
6346}
6347function decode(data) {
6348 const bytes = arrayify(data);
6349 const decoded = _decode(bytes, 0);
6350 if (decoded.consumed !== bytes.length) {
6351 logger$6.throwArgumentError("invalid rlp data", "data", data);
6352 }
6353 return decoded.result;
6354}
6355
6356var index = /*#__PURE__*/Object.freeze({
6357 encode: encode,
6358 decode: decode
6359});
6360
6361const version$6 = "address/5.0.2";
6362
6363"use strict";
6364const logger$7 = new Logger(version$6);
6365function getChecksumAddress(address) {
6366 if (!isHexString(address, 20)) {
6367 logger$7.throwArgumentError("invalid address", "address", address);
6368 }
6369 address = address.toLowerCase();
6370 const chars = address.substring(2).split("");
6371 const expanded = new Uint8Array(40);
6372 for (let i = 0; i < 40; i++) {
6373 expanded[i] = chars[i].charCodeAt(0);
6374 }
6375 const hashed = arrayify(keccak256(expanded));
6376 for (let i = 0; i < 40; i += 2) {
6377 if ((hashed[i >> 1] >> 4) >= 8) {
6378 chars[i] = chars[i].toUpperCase();
6379 }
6380 if ((hashed[i >> 1] & 0x0f) >= 8) {
6381 chars[i + 1] = chars[i + 1].toUpperCase();
6382 }
6383 }
6384 return "0x" + chars.join("");
6385}
6386// Shims for environments that are missing some required constants and functions
6387const MAX_SAFE_INTEGER = 0x1fffffffffffff;
6388function log10(x) {
6389 if (Math.log10) {
6390 return Math.log10(x);
6391 }
6392 return Math.log(x) / Math.LN10;
6393}
6394// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
6395// Create lookup table
6396const ibanLookup = {};
6397for (let i = 0; i < 10; i++) {
6398 ibanLookup[String(i)] = String(i);
6399}
6400for (let i = 0; i < 26; i++) {
6401 ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
6402}
6403// How many decimal digits can we process? (for 64-bit float, this is 15)
6404const safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));
6405function ibanChecksum(address) {
6406 address = address.toUpperCase();
6407 address = address.substring(4) + address.substring(0, 2) + "00";
6408 let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join("");
6409 // Javascript can handle integers safely up to 15 (decimal) digits
6410 while (expanded.length >= safeDigits) {
6411 let block = expanded.substring(0, safeDigits);
6412 expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
6413 }
6414 let checksum = String(98 - (parseInt(expanded, 10) % 97));
6415 while (checksum.length < 2) {
6416 checksum = "0" + checksum;
6417 }
6418 return checksum;
6419}
6420;
6421function getAddress(address) {
6422 let result = null;
6423 if (typeof (address) !== "string") {
6424 logger$7.throwArgumentError("invalid address", "address", address);
6425 }
6426 if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
6427 // Missing the 0x prefix
6428 if (address.substring(0, 2) !== "0x") {
6429 address = "0x" + address;
6430 }
6431 result = getChecksumAddress(address);
6432 // It is a checksummed address with a bad checksum
6433 if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) {
6434 logger$7.throwArgumentError("bad address checksum", "address", address);
6435 }
6436 // Maybe ICAP? (we only support direct mode)
6437 }
6438 else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
6439 // It is an ICAP address with a bad checksum
6440 if (address.substring(2, 4) !== ibanChecksum(address)) {
6441 logger$7.throwArgumentError("bad icap checksum", "address", address);
6442 }
6443 result = (new bn_1(address.substring(4), 36)).toString(16);
6444 while (result.length < 40) {
6445 result = "0" + result;
6446 }
6447 result = getChecksumAddress("0x" + result);
6448 }
6449 else {
6450 logger$7.throwArgumentError("invalid address", "address", address);
6451 }
6452 return result;
6453}
6454function isAddress(address) {
6455 try {
6456 getAddress(address);
6457 return true;
6458 }
6459 catch (error) { }
6460 return false;
6461}
6462function getIcapAddress(address) {
6463 let base36 = (new bn_1(getAddress(address).substring(2), 16)).toString(36).toUpperCase();
6464 while (base36.length < 30) {
6465 base36 = "0" + base36;
6466 }
6467 return "XE" + ibanChecksum("XE00" + base36) + base36;
6468}
6469// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
6470function getContractAddress(transaction) {
6471 let from = null;
6472 try {
6473 from = getAddress(transaction.from);
6474 }
6475 catch (error) {
6476 logger$7.throwArgumentError("missing from address", "transaction", transaction);
6477 }
6478 const nonce = stripZeros(arrayify(BigNumber.from(transaction.nonce).toHexString()));
6479 return getAddress(hexDataSlice(keccak256(encode([from, nonce])), 12));
6480}
6481function getCreate2Address(from, salt, initCodeHash) {
6482 if (hexDataLength(salt) !== 32) {
6483 logger$7.throwArgumentError("salt must be 32 bytes", "salt", salt);
6484 }
6485 if (hexDataLength(initCodeHash) !== 32) {
6486 logger$7.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", initCodeHash);
6487 }
6488 return getAddress(hexDataSlice(keccak256(concat(["0xff", getAddress(from), salt, initCodeHash])), 12));
6489}
6490
6491"use strict";
6492class AddressCoder extends Coder {
6493 constructor(localName) {
6494 super("address", "address", localName, false);
6495 }
6496 encode(writer, value) {
6497 try {
6498 getAddress(value);
6499 }
6500 catch (error) {
6501 this._throwError(error.message, value);
6502 }
6503 return writer.writeValue(value);
6504 }
6505 decode(reader) {
6506 return getAddress(hexZeroPad(reader.readValue().toHexString(), 20));
6507 }
6508}
6509
6510"use strict";
6511// Clones the functionality of an existing Coder, but without a localName
6512class AnonymousCoder extends Coder {
6513 constructor(coder) {
6514 super(coder.name, coder.type, undefined, coder.dynamic);
6515 this.coder = coder;
6516 }
6517 encode(writer, value) {
6518 return this.coder.encode(writer, value);
6519 }
6520 decode(reader) {
6521 return this.coder.decode(reader);
6522 }
6523}
6524
6525"use strict";
6526const logger$8 = new Logger(version$4);
6527function pack(writer, coders, values) {
6528 let arrayValues = null;
6529 if (Array.isArray(values)) {
6530 arrayValues = values;
6531 }
6532 else if (values && typeof (values) === "object") {
6533 let unique = {};
6534 arrayValues = coders.map((coder) => {
6535 const name = coder.localName;
6536 if (!name) {
6537 logger$8.throwError("cannot encode object for signature with missing names", Logger.errors.INVALID_ARGUMENT, {
6538 argument: "values",
6539 coder: coder,
6540 value: values
6541 });
6542 }
6543 if (unique[name]) {
6544 logger$8.throwError("cannot encode object for signature with duplicate names", Logger.errors.INVALID_ARGUMENT, {
6545 argument: "values",
6546 coder: coder,
6547 value: values
6548 });
6549 }
6550 unique[name] = true;
6551 return values[name];
6552 });
6553 }
6554 else {
6555 logger$8.throwArgumentError("invalid tuple value", "tuple", values);
6556 }
6557 if (coders.length !== arrayValues.length) {
6558 logger$8.throwArgumentError("types/value length mismatch", "tuple", values);
6559 }
6560 let staticWriter = new Writer(writer.wordSize);
6561 let dynamicWriter = new Writer(writer.wordSize);
6562 let updateFuncs = [];
6563 coders.forEach((coder, index) => {
6564 let value = arrayValues[index];
6565 if (coder.dynamic) {
6566 // Get current dynamic offset (for the future pointer)
6567 let dynamicOffset = dynamicWriter.length;
6568 // Encode the dynamic value into the dynamicWriter
6569 coder.encode(dynamicWriter, value);
6570 // Prepare to populate the correct offset once we are done
6571 let updateFunc = staticWriter.writeUpdatableValue();
6572 updateFuncs.push((baseOffset) => {
6573 updateFunc(baseOffset + dynamicOffset);
6574 });
6575 }
6576 else {
6577 coder.encode(staticWriter, value);
6578 }
6579 });
6580 // Backfill all the dynamic offsets, now that we know the static length
6581 updateFuncs.forEach((func) => { func(staticWriter.length); });
6582 let length = writer.writeBytes(staticWriter.data);
6583 length += writer.writeBytes(dynamicWriter.data);
6584 return length;
6585}
6586function unpack(reader, coders) {
6587 let values = [];
6588 // A reader anchored to this base
6589 let baseReader = reader.subReader(0);
6590 // The amount of dynamic data read; to consume later to synchronize
6591 let dynamicLength = 0;
6592 coders.forEach((coder) => {
6593 let value = null;
6594 if (coder.dynamic) {
6595 let offset = reader.readValue();
6596 let offsetReader = baseReader.subReader(offset.toNumber());
6597 try {
6598 value = coder.decode(offsetReader);
6599 }
6600 catch (error) {
6601 // Cannot recover from this
6602 if (error.code === Logger.errors.BUFFER_OVERRUN) {
6603 throw error;
6604 }
6605 value = error;
6606 value.baseType = coder.name;
6607 value.name = coder.localName;
6608 value.type = coder.type;
6609 }
6610 dynamicLength += offsetReader.consumed;
6611 }
6612 else {
6613 try {
6614 value = coder.decode(reader);
6615 }
6616 catch (error) {
6617 // Cannot recover from this
6618 if (error.code === Logger.errors.BUFFER_OVERRUN) {
6619 throw error;
6620 }
6621 value = error;
6622 value.baseType = coder.name;
6623 value.name = coder.localName;
6624 value.type = coder.type;
6625 }
6626 }
6627 if (value != undefined) {
6628 values.push(value);
6629 }
6630 });
6631 // @TODO: get rid of this an see if it still works?
6632 // Consume the dynamic components in the main reader
6633 reader.readBytes(dynamicLength);
6634 // We only output named properties for uniquely named coders
6635 const uniqueNames = coders.reduce((accum, coder) => {
6636 const name = coder.localName;
6637 if (name) {
6638 if (!accum[name]) {
6639 accum[name] = 0;
6640 }
6641 accum[name]++;
6642 }
6643 return accum;
6644 }, {});
6645 // Add any named parameters (i.e. tuples)
6646 coders.forEach((coder, index) => {
6647 let name = coder.localName;
6648 if (!name || uniqueNames[name] !== 1) {
6649 return;
6650 }
6651 if (name === "length") {
6652 name = "_length";
6653 }
6654 if (values[name] != null) {
6655 return;
6656 }
6657 const value = values[index];
6658 if (value instanceof Error) {
6659 Object.defineProperty(values, name, {
6660 get: () => { throw value; }
6661 });
6662 }
6663 else {
6664 values[name] = value;
6665 }
6666 });
6667 for (let i = 0; i < values.length; i++) {
6668 const value = values[i];
6669 if (value instanceof Error) {
6670 Object.defineProperty(values, i, {
6671 get: () => { throw value; }
6672 });
6673 }
6674 }
6675 return Object.freeze(values);
6676}
6677class ArrayCoder extends Coder {
6678 constructor(coder, length, localName) {
6679 const type = (coder.type + "[" + (length >= 0 ? length : "") + "]");
6680 const dynamic = (length === -1 || coder.dynamic);
6681 super("array", type, localName, dynamic);
6682 this.coder = coder;
6683 this.length = length;
6684 }
6685 encode(writer, value) {
6686 if (!Array.isArray(value)) {
6687 this._throwError("expected array value", value);
6688 }
6689 let count = this.length;
6690 if (count === -1) {
6691 count = value.length;
6692 writer.writeValue(value.length);
6693 }
6694 logger$8.checkArgumentCount(count, value.length, "coder array" + (this.localName ? (" " + this.localName) : ""));
6695 let coders = [];
6696 for (let i = 0; i < value.length; i++) {
6697 coders.push(this.coder);
6698 }
6699 return pack(writer, coders, value);
6700 }
6701 decode(reader) {
6702 let count = this.length;
6703 if (count === -1) {
6704 count = reader.readValue().toNumber();
6705 }
6706 let coders = [];
6707 for (let i = 0; i < count; i++) {
6708 coders.push(new AnonymousCoder(this.coder));
6709 }
6710 return reader.coerce(this.name, unpack(reader, coders));
6711 }
6712}
6713
6714"use strict";
6715class BooleanCoder extends Coder {
6716 constructor(localName) {
6717 super("bool", "bool", localName, false);
6718 }
6719 encode(writer, value) {
6720 return writer.writeValue(value ? 1 : 0);
6721 }
6722 decode(reader) {
6723 return reader.coerce(this.type, !reader.readValue().isZero());
6724 }
6725}
6726
6727"use strict";
6728class DynamicBytesCoder extends Coder {
6729 constructor(type, localName) {
6730 super(type, type, localName, true);
6731 }
6732 encode(writer, value) {
6733 value = arrayify(value);
6734 let length = writer.writeValue(value.length);
6735 length += writer.writeBytes(value);
6736 return length;
6737 }
6738 decode(reader) {
6739 return reader.readBytes(reader.readValue().toNumber());
6740 }
6741}
6742class BytesCoder extends DynamicBytesCoder {
6743 constructor(localName) {
6744 super("bytes", localName);
6745 }
6746 decode(reader) {
6747 return reader.coerce(this.name, hexlify(super.decode(reader)));
6748 }
6749}
6750
6751"use strict";
6752// @TODO: Merge this with bytes
6753class FixedBytesCoder extends Coder {
6754 constructor(size, localName) {
6755 let name = "bytes" + String(size);
6756 super(name, name, localName, false);
6757 this.size = size;
6758 }
6759 encode(writer, value) {
6760 let data = arrayify(value);
6761 if (data.length !== this.size) {
6762 this._throwError("incorrect data length", value);
6763 }
6764 return writer.writeBytes(data);
6765 }
6766 decode(reader) {
6767 return reader.coerce(this.name, hexlify(reader.readBytes(this.size)));
6768 }
6769}
6770
6771"use strict";
6772class NullCoder extends Coder {
6773 constructor(localName) {
6774 super("null", "", localName, false);
6775 }
6776 encode(writer, value) {
6777 if (value != null) {
6778 this._throwError("not null", value);
6779 }
6780 return writer.writeBytes([]);
6781 }
6782 decode(reader) {
6783 reader.readBytes(0);
6784 return reader.coerce(this.name, null);
6785 }
6786}
6787
6788"use strict";
6789const AddressZero = "0x0000000000000000000000000000000000000000";
6790const HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000";
6791// NFKC (composed) // (decomposed)
6792const EtherSymbol = "\u039e"; // "\uD835\uDF63";
6793const NegativeOne$1 = BigNumber.from(-1);
6794const Zero$1 = BigNumber.from(0);
6795const One = BigNumber.from(1);
6796const Two = BigNumber.from(2);
6797const WeiPerEther = BigNumber.from("1000000000000000000");
6798const MaxUint256 = BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
6799
6800var index$1 = /*#__PURE__*/Object.freeze({
6801 AddressZero: AddressZero,
6802 HashZero: HashZero,
6803 EtherSymbol: EtherSymbol,
6804 NegativeOne: NegativeOne$1,
6805 Zero: Zero$1,
6806 One: One,
6807 Two: Two,
6808 WeiPerEther: WeiPerEther,
6809 MaxUint256: MaxUint256
6810});
6811
6812"use strict";
6813class NumberCoder extends Coder {
6814 constructor(size, signed, localName) {
6815 const name = ((signed ? "int" : "uint") + (size * 8));
6816 super(name, name, localName, false);
6817 this.size = size;
6818 this.signed = signed;
6819 }
6820 encode(writer, value) {
6821 let v = BigNumber.from(value);
6822 // Check bounds are safe for encoding
6823 let maxUintValue = MaxUint256.mask(writer.wordSize * 8);
6824 if (this.signed) {
6825 let bounds = maxUintValue.mask(this.size * 8 - 1);
6826 if (v.gt(bounds) || v.lt(bounds.add(One).mul(NegativeOne$1))) {
6827 this._throwError("value out-of-bounds", value);
6828 }
6829 }
6830 else if (v.lt(Zero$1) || v.gt(maxUintValue.mask(this.size * 8))) {
6831 this._throwError("value out-of-bounds", value);
6832 }
6833 v = v.toTwos(this.size * 8).mask(this.size * 8);
6834 if (this.signed) {
6835 v = v.fromTwos(this.size * 8).toTwos(8 * writer.wordSize);
6836 }
6837 return writer.writeValue(v);
6838 }
6839 decode(reader) {
6840 let value = reader.readValue().mask(this.size * 8);
6841 if (this.signed) {
6842 value = value.fromTwos(this.size * 8);
6843 }
6844 return reader.coerce(this.name, value);
6845 }
6846}
6847
6848const version$7 = "strings/5.0.2";
6849
6850"use strict";
6851const logger$9 = new Logger(version$7);
6852///////////////////////////////
6853var UnicodeNormalizationForm;
6854(function (UnicodeNormalizationForm) {
6855 UnicodeNormalizationForm["current"] = "";
6856 UnicodeNormalizationForm["NFC"] = "NFC";
6857 UnicodeNormalizationForm["NFD"] = "NFD";
6858 UnicodeNormalizationForm["NFKC"] = "NFKC";
6859 UnicodeNormalizationForm["NFKD"] = "NFKD";
6860})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {}));
6861;
6862var Utf8ErrorReason;
6863(function (Utf8ErrorReason) {
6864 // A continuation byte was present where there was nothing to continue
6865 // - offset = the index the codepoint began in
6866 Utf8ErrorReason["UNEXPECTED_CONTINUE"] = "unexpected continuation byte";
6867 // An invalid (non-continuation) byte to start a UTF-8 codepoint was found
6868 // - offset = the index the codepoint began in
6869 Utf8ErrorReason["BAD_PREFIX"] = "bad codepoint prefix";
6870 // The string is too short to process the expected codepoint
6871 // - offset = the index the codepoint began in
6872 Utf8ErrorReason["OVERRUN"] = "string overrun";
6873 // A missing continuation byte was expected but not found
6874 // - offset = the index the continuation byte was expected at
6875 Utf8ErrorReason["MISSING_CONTINUE"] = "missing continuation byte";
6876 // The computed code point is outside the range for UTF-8
6877 // - offset = start of this codepoint
6878 // - badCodepoint = the computed codepoint; outside the UTF-8 range
6879 Utf8ErrorReason["OUT_OF_RANGE"] = "out of UTF-8 range";
6880 // UTF-8 strings may not contain UTF-16 surrogate pairs
6881 // - offset = start of this codepoint
6882 // - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range
6883 Utf8ErrorReason["UTF16_SURROGATE"] = "UTF-16 surrogate";
6884 // The string is an overlong reperesentation
6885 // - offset = start of this codepoint
6886 // - badCodepoint = the computed codepoint; already bounds checked
6887 Utf8ErrorReason["OVERLONG"] = "overlong representation";
6888})(Utf8ErrorReason || (Utf8ErrorReason = {}));
6889;
6890function errorFunc(reason, offset, bytes, output, badCodepoint) {
6891 return logger$9.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes);
6892}
6893function ignoreFunc(reason, offset, bytes, output, badCodepoint) {
6894 // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes
6895 if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) {
6896 let i = 0;
6897 for (let o = offset + 1; o < bytes.length; o++) {
6898 if (bytes[o] >> 6 !== 0x02) {
6899 break;
6900 }
6901 i++;
6902 }
6903 return i;
6904 }
6905 // This byte runs us past the end of the string, so just jump to the end
6906 // (but the first byte was read already read and therefore skipped)
6907 if (reason === Utf8ErrorReason.OVERRUN) {
6908 return bytes.length - offset - 1;
6909 }
6910 // Nothing to skip
6911 return 0;
6912}
6913function replaceFunc(reason, offset, bytes, output, badCodepoint) {
6914 // Overlong representations are otherwise "valid" code points; just non-deistingtished
6915 if (reason === Utf8ErrorReason.OVERLONG) {
6916 output.push(badCodepoint);
6917 return 0;
6918 }
6919 // Put the replacement character into the output
6920 output.push(0xfffd);
6921 // Otherwise, process as if ignoring errors
6922 return ignoreFunc(reason, offset, bytes, output, badCodepoint);
6923}
6924// Common error handing strategies
6925const Utf8ErrorFuncs = Object.freeze({
6926 error: errorFunc,
6927 ignore: ignoreFunc,
6928 replace: replaceFunc
6929});
6930// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
6931function getUtf8CodePoints(bytes, onError) {
6932 if (onError == null) {
6933 onError = Utf8ErrorFuncs.error;
6934 }
6935 bytes = arrayify(bytes);
6936 const result = [];
6937 let i = 0;
6938 // Invalid bytes are ignored
6939 while (i < bytes.length) {
6940 const c = bytes[i++];
6941 // 0xxx xxxx
6942 if (c >> 7 === 0) {
6943 result.push(c);
6944 continue;
6945 }
6946 // Multibyte; how many bytes left for this character?
6947 let extraLength = null;
6948 let overlongMask = null;
6949 // 110x xxxx 10xx xxxx
6950 if ((c & 0xe0) === 0xc0) {
6951 extraLength = 1;
6952 overlongMask = 0x7f;
6953 // 1110 xxxx 10xx xxxx 10xx xxxx
6954 }
6955 else if ((c & 0xf0) === 0xe0) {
6956 extraLength = 2;
6957 overlongMask = 0x7ff;
6958 // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
6959 }
6960 else if ((c & 0xf8) === 0xf0) {
6961 extraLength = 3;
6962 overlongMask = 0xffff;
6963 }
6964 else {
6965 if ((c & 0xc0) === 0x80) {
6966 i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes, result);
6967 }
6968 else {
6969 i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes, result);
6970 }
6971 continue;
6972 }
6973 // Do we have enough bytes in our data?
6974 if (i - 1 + extraLength >= bytes.length) {
6975 i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes, result);
6976 continue;
6977 }
6978 // Remove the length prefix from the char
6979 let res = c & ((1 << (8 - extraLength - 1)) - 1);
6980 for (let j = 0; j < extraLength; j++) {
6981 let nextChar = bytes[i];
6982 // Invalid continuation byte
6983 if ((nextChar & 0xc0) != 0x80) {
6984 i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes, result);
6985 res = null;
6986 break;
6987 }
6988 ;
6989 res = (res << 6) | (nextChar & 0x3f);
6990 i++;
6991 }
6992 // See above loop for invalid contimuation byte
6993 if (res === null) {
6994 continue;
6995 }
6996 // Maximum code point
6997 if (res > 0x10ffff) {
6998 i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes, result, res);
6999 continue;
7000 }
7001 // Reserved for UTF-16 surrogate halves
7002 if (res >= 0xd800 && res <= 0xdfff) {
7003 i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes, result, res);
7004 continue;
7005 }
7006 // Check for overlong sequences (more bytes than needed)
7007 if (res <= overlongMask) {
7008 i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes, result, res);
7009 continue;
7010 }
7011 result.push(res);
7012 }
7013 return result;
7014}
7015// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
7016function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) {
7017 if (form != UnicodeNormalizationForm.current) {
7018 logger$9.checkNormalize();
7019 str = str.normalize(form);
7020 }
7021 let result = [];
7022 for (let i = 0; i < str.length; i++) {
7023 const c = str.charCodeAt(i);
7024 if (c < 0x80) {
7025 result.push(c);
7026 }
7027 else if (c < 0x800) {
7028 result.push((c >> 6) | 0xc0);
7029 result.push((c & 0x3f) | 0x80);
7030 }
7031 else if ((c & 0xfc00) == 0xd800) {
7032 i++;
7033 const c2 = str.charCodeAt(i);
7034 if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) {
7035 throw new Error("invalid utf-8 string");
7036 }
7037 // Surrogate Pair
7038 const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
7039 result.push((pair >> 18) | 0xf0);
7040 result.push(((pair >> 12) & 0x3f) | 0x80);
7041 result.push(((pair >> 6) & 0x3f) | 0x80);
7042 result.push((pair & 0x3f) | 0x80);
7043 }
7044 else {
7045 result.push((c >> 12) | 0xe0);
7046 result.push(((c >> 6) & 0x3f) | 0x80);
7047 result.push((c & 0x3f) | 0x80);
7048 }
7049 }
7050 return arrayify(result);
7051}
7052;
7053function escapeChar(value) {
7054 const hex = ("0000" + value.toString(16));
7055 return "\\u" + hex.substring(hex.length - 4);
7056}
7057function _toEscapedUtf8String(bytes, onError) {
7058 return '"' + getUtf8CodePoints(bytes, onError).map((codePoint) => {
7059 if (codePoint < 256) {
7060 switch (codePoint) {
7061 case 8: return "\\b";
7062 case 9: return "\\t";
7063 case 10: return "\\n";
7064 case 13: return "\\r";
7065 case 34: return "\\\"";
7066 case 92: return "\\\\";
7067 }
7068 if (codePoint >= 32 && codePoint < 127) {
7069 return String.fromCharCode(codePoint);
7070 }
7071 }
7072 if (codePoint <= 0xffff) {
7073 return escapeChar(codePoint);
7074 }
7075 codePoint -= 0x10000;
7076 return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00);
7077 }).join("") + '"';
7078}
7079function _toUtf8String(codePoints) {
7080 return codePoints.map((codePoint) => {
7081 if (codePoint <= 0xffff) {
7082 return String.fromCharCode(codePoint);
7083 }
7084 codePoint -= 0x10000;
7085 return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));
7086 }).join("");
7087}
7088function toUtf8String(bytes, onError) {
7089 return _toUtf8String(getUtf8CodePoints(bytes, onError));
7090}
7091function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) {
7092 return getUtf8CodePoints(toUtf8Bytes(str, form));
7093}
7094
7095"use strict";
7096function formatBytes32String(text) {
7097 // Get the bytes
7098 const bytes = toUtf8Bytes(text);
7099 // Check we have room for null-termination
7100 if (bytes.length > 31) {
7101 throw new Error("bytes32 string must be less than 32 bytes");
7102 }
7103 // Zero-pad (implicitly null-terminates)
7104 return hexlify(concat([bytes, HashZero]).slice(0, 32));
7105}
7106function parseBytes32String(bytes) {
7107 const data = arrayify(bytes);
7108 // Must be 32 bytes with a null-termination
7109 if (data.length !== 32) {
7110 throw new Error("invalid bytes32 - not 32 bytes long");
7111 }
7112 if (data[31] !== 0) {
7113 throw new Error("invalid bytes32 string - no null terminator");
7114 }
7115 // Find the null termination
7116 let length = 31;
7117 while (data[length - 1] === 0) {
7118 length--;
7119 }
7120 // Determine the string value
7121 return toUtf8String(data.slice(0, length));
7122}
7123
7124"use strict";
7125function bytes2(data) {
7126 if ((data.length % 4) !== 0) {
7127 throw new Error("bad data");
7128 }
7129 let result = [];
7130 for (let i = 0; i < data.length; i += 4) {
7131 result.push(parseInt(data.substring(i, i + 4), 16));
7132 }
7133 return result;
7134}
7135function createTable(data, func) {
7136 if (!func) {
7137 func = function (value) { return [parseInt(value, 16)]; };
7138 }
7139 let lo = 0;
7140 let result = {};
7141 data.split(",").forEach((pair) => {
7142 let comps = pair.split(":");
7143 lo += parseInt(comps[0], 16);
7144 result[lo] = func(comps[1]);
7145 });
7146 return result;
7147}
7148function createRangeTable(data) {
7149 let hi = 0;
7150 return data.split(",").map((v) => {
7151 let comps = v.split("-");
7152 if (comps.length === 1) {
7153 comps[1] = "0";
7154 }
7155 else if (comps[1] === "") {
7156 comps[1] = "1";
7157 }
7158 let lo = hi + parseInt(comps[0], 16);
7159 hi = parseInt(comps[1], 16);
7160 return { l: lo, h: hi };
7161 });
7162}
7163function matchMap(value, ranges) {
7164 let lo = 0;
7165 for (let i = 0; i < ranges.length; i++) {
7166 let range = ranges[i];
7167 lo += range.l;
7168 if (value >= lo && value <= lo + range.h && ((value - lo) % (range.d || 1)) === 0) {
7169 if (range.e && range.e.indexOf(value - lo) !== -1) {
7170 continue;
7171 }
7172 return range;
7173 }
7174 }
7175 return null;
7176}
7177const Table_A_1_ranges = createRangeTable("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d");
7178// @TODO: Make this relative...
7179const Table_B_1_flags = "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((v) => parseInt(v, 16));
7180const Table_B_2_ranges = [
7181 { h: 25, s: 32, l: 65 },
7182 { h: 30, s: 32, e: [23], l: 127 },
7183 { h: 54, s: 1, e: [48], l: 64, d: 2 },
7184 { h: 14, s: 1, l: 57, d: 2 },
7185 { h: 44, s: 1, l: 17, d: 2 },
7186 { h: 10, s: 1, e: [2, 6, 8], l: 61, d: 2 },
7187 { h: 16, s: 1, l: 68, d: 2 },
7188 { h: 84, s: 1, e: [18, 24, 66], l: 19, d: 2 },
7189 { h: 26, s: 32, e: [17], l: 435 },
7190 { h: 22, s: 1, l: 71, d: 2 },
7191 { h: 15, s: 80, l: 40 },
7192 { h: 31, s: 32, l: 16 },
7193 { h: 32, s: 1, l: 80, d: 2 },
7194 { h: 52, s: 1, l: 42, d: 2 },
7195 { h: 12, s: 1, l: 55, d: 2 },
7196 { h: 40, s: 1, e: [38], l: 15, d: 2 },
7197 { h: 14, s: 1, l: 48, d: 2 },
7198 { h: 37, s: 48, l: 49 },
7199 { h: 148, s: 1, l: 6351, d: 2 },
7200 { h: 88, s: 1, l: 160, d: 2 },
7201 { h: 15, s: 16, l: 704 },
7202 { h: 25, s: 26, l: 854 },
7203 { h: 25, s: 32, l: 55915 },
7204 { h: 37, s: 40, l: 1247 },
7205 { h: 25, s: -119711, l: 53248 },
7206 { h: 25, s: -119763, l: 52 },
7207 { h: 25, s: -119815, l: 52 },
7208 { h: 25, s: -119867, e: [1, 4, 5, 7, 8, 11, 12, 17], l: 52 },
7209 { h: 25, s: -119919, l: 52 },
7210 { h: 24, s: -119971, e: [2, 7, 8, 17], l: 52 },
7211 { h: 24, s: -120023, e: [2, 7, 13, 15, 16, 17], l: 52 },
7212 { h: 25, s: -120075, l: 52 },
7213 { h: 25, s: -120127, l: 52 },
7214 { h: 25, s: -120179, l: 52 },
7215 { h: 25, s: -120231, l: 52 },
7216 { h: 25, s: -120283, l: 52 },
7217 { h: 25, s: -120335, l: 52 },
7218 { h: 24, s: -119543, e: [17], l: 56 },
7219 { h: 24, s: -119601, e: [17], l: 58 },
7220 { h: 24, s: -119659, e: [17], l: 58 },
7221 { h: 24, s: -119717, e: [17], l: 58 },
7222 { h: 24, s: -119775, e: [17], l: 58 }
7223];
7224const Table_B_2_lut_abs = createTable("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3");
7225const Table_B_2_lut_rel = createTable("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7");
7226const Table_B_2_complex = createTable("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", bytes2);
7227const Table_C_ranges = createRangeTable("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");
7228function flatten(values) {
7229 return values.reduce((accum, value) => {
7230 value.forEach((value) => { accum.push(value); });
7231 return accum;
7232 }, []);
7233}
7234function _nameprepTableA1(codepoint) {
7235 return !!matchMap(codepoint, Table_A_1_ranges);
7236}
7237function _nameprepTableB2(codepoint) {
7238 let range = matchMap(codepoint, Table_B_2_ranges);
7239 if (range) {
7240 return [codepoint + range.s];
7241 }
7242 let codes = Table_B_2_lut_abs[codepoint];
7243 if (codes) {
7244 return codes;
7245 }
7246 let shift = Table_B_2_lut_rel[codepoint];
7247 if (shift) {
7248 return [codepoint + shift[0]];
7249 }
7250 let complex = Table_B_2_complex[codepoint];
7251 if (complex) {
7252 return complex;
7253 }
7254 return null;
7255}
7256function _nameprepTableC(codepoint) {
7257 return !!matchMap(codepoint, Table_C_ranges);
7258}
7259function nameprep(value) {
7260 // This allows platforms with incomplete normalize to bypass
7261 // it for very basic names which the built-in toLowerCase
7262 // will certainly handle correctly
7263 if (value.match(/^[a-z0-9-]*$/i) && value.length <= 59) {
7264 return value.toLowerCase();
7265 }
7266 // Get the code points (keeping the current normalization)
7267 let codes = toUtf8CodePoints(value);
7268 codes = flatten(codes.map((code) => {
7269 // Substitute Table B.1 (Maps to Nothing)
7270 if (Table_B_1_flags.indexOf(code) >= 0) {
7271 return [];
7272 }
7273 if (code >= 0xfe00 && code <= 0xfe0f) {
7274 return [];
7275 }
7276 // Substitute Table B.2 (Case Folding)
7277 let codesTableB2 = _nameprepTableB2(code);
7278 if (codesTableB2) {
7279 return codesTableB2;
7280 }
7281 // No Substitution
7282 return [code];
7283 }));
7284 // Normalize using form KC
7285 codes = toUtf8CodePoints(_toUtf8String(codes), UnicodeNormalizationForm.NFKC);
7286 // Prohibit Tables C.1.2, C.2.2, C.3, C.4, C.5, C.6, C.7, C.8, C.9
7287 codes.forEach((code) => {
7288 if (_nameprepTableC(code)) {
7289 throw new Error("STRINGPREP_CONTAINS_PROHIBITED");
7290 }
7291 });
7292 // Prohibit Unassigned Code Points (Table A.1)
7293 codes.forEach((code) => {
7294 if (_nameprepTableA1(code)) {
7295 throw new Error("STRINGPREP_CONTAINS_UNASSIGNED");
7296 }
7297 });
7298 // IDNA extras
7299 let name = _toUtf8String(codes);
7300 // IDNA: 4.2.3.1
7301 if (name.substring(0, 1) === "-" || name.substring(2, 4) === "--" || name.substring(name.length - 1) === "-") {
7302 throw new Error("invalid hyphen");
7303 }
7304 // IDNA: 4.2.4
7305 if (name.length > 63) {
7306 throw new Error("too long");
7307 }
7308 return name;
7309}
7310
7311"use strict";
7312
7313"use strict";
7314class StringCoder extends DynamicBytesCoder {
7315 constructor(localName) {
7316 super("string", localName);
7317 }
7318 encode(writer, value) {
7319 return super.encode(writer, toUtf8Bytes(value));
7320 }
7321 decode(reader) {
7322 return toUtf8String(super.decode(reader));
7323 }
7324}
7325
7326"use strict";
7327class TupleCoder extends Coder {
7328 constructor(coders, localName) {
7329 let dynamic = false;
7330 const types = [];
7331 coders.forEach((coder) => {
7332 if (coder.dynamic) {
7333 dynamic = true;
7334 }
7335 types.push(coder.type);
7336 });
7337 const type = ("tuple(" + types.join(",") + ")");
7338 super("tuple", type, localName, dynamic);
7339 this.coders = coders;
7340 }
7341 encode(writer, value) {
7342 return pack(writer, this.coders, value);
7343 }
7344 decode(reader) {
7345 return reader.coerce(this.name, unpack(reader, this.coders));
7346 }
7347}
7348
7349"use strict";
7350const logger$a = new Logger(version$4);
7351const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
7352const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
7353class AbiCoder {
7354 constructor(coerceFunc) {
7355 logger$a.checkNew(new.target, AbiCoder);
7356 defineReadOnly(this, "coerceFunc", coerceFunc || null);
7357 }
7358 _getCoder(param) {
7359 switch (param.baseType) {
7360 case "address":
7361 return new AddressCoder(param.name);
7362 case "bool":
7363 return new BooleanCoder(param.name);
7364 case "string":
7365 return new StringCoder(param.name);
7366 case "bytes":
7367 return new BytesCoder(param.name);
7368 case "array":
7369 return new ArrayCoder(this._getCoder(param.arrayChildren), param.arrayLength, param.name);
7370 case "tuple":
7371 return new TupleCoder((param.components || []).map((component) => {
7372 return this._getCoder(component);
7373 }), param.name);
7374 case "":
7375 return new NullCoder(param.name);
7376 }
7377 // u?int[0-9]*
7378 let match = param.type.match(paramTypeNumber);
7379 if (match) {
7380 let size = parseInt(match[2] || "256");
7381 if (size === 0 || size > 256 || (size % 8) !== 0) {
7382 logger$a.throwArgumentError("invalid " + match[1] + " bit length", "param", param);
7383 }
7384 return new NumberCoder(size / 8, (match[1] === "int"), param.name);
7385 }
7386 // bytes[0-9]+
7387 match = param.type.match(paramTypeBytes);
7388 if (match) {
7389 let size = parseInt(match[1]);
7390 if (size === 0 || size > 32) {
7391 logger$a.throwArgumentError("invalid bytes length", "param", param);
7392 }
7393 return new FixedBytesCoder(size, param.name);
7394 }
7395 return logger$a.throwArgumentError("invalid type", "type", param.type);
7396 }
7397 _getWordSize() { return 32; }
7398 _getReader(data) {
7399 return new Reader(data, this._getWordSize(), this.coerceFunc);
7400 }
7401 _getWriter() {
7402 return new Writer(this._getWordSize());
7403 }
7404 encode(types, values) {
7405 if (types.length !== values.length) {
7406 logger$a.throwError("types/values length mismatch", Logger.errors.INVALID_ARGUMENT, {
7407 count: { types: types.length, values: values.length },
7408 value: { types: types, values: values }
7409 });
7410 }
7411 const coders = types.map((type) => this._getCoder(ParamType.from(type)));
7412 const coder = (new TupleCoder(coders, "_"));
7413 const writer = this._getWriter();
7414 coder.encode(writer, values);
7415 return writer.data;
7416 }
7417 decode(types, data) {
7418 const coders = types.map((type) => this._getCoder(ParamType.from(type)));
7419 const coder = new TupleCoder(coders, "_");
7420 return coder.decode(this._getReader(arrayify(data)));
7421 }
7422}
7423const defaultAbiCoder = new AbiCoder();
7424
7425const version$8 = "hash/5.0.2";
7426
7427"use strict";
7428const logger$b = new Logger(version$8);
7429///////////////////////////////
7430const Zeros = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
7431const Partition = new RegExp("^((.*)\\.)?([^.]+)$");
7432function isValidName(name) {
7433 try {
7434 const comps = name.split(".");
7435 for (let i = 0; i < comps.length; i++) {
7436 if (nameprep(comps[i]).length === 0) {
7437 throw new Error("empty");
7438 }
7439 }
7440 return true;
7441 }
7442 catch (error) { }
7443 return false;
7444}
7445function namehash(name) {
7446 /* istanbul ignore if */
7447 if (typeof (name) !== "string") {
7448 logger$b.throwArgumentError("invalid address - " + String(name), "name", name);
7449 }
7450 let result = Zeros;
7451 while (name.length) {
7452 const partition = name.match(Partition);
7453 const label = toUtf8Bytes(nameprep(partition[3]));
7454 result = keccak256(concat([result, keccak256(label)]));
7455 name = partition[2] || "";
7456 }
7457 return hexlify(result);
7458}
7459function id(text) {
7460 return keccak256(toUtf8Bytes(text));
7461}
7462const messagePrefix = "\x19Ethereum Signed Message:\n";
7463function hashMessage(message) {
7464 if (typeof (message) === "string") {
7465 message = toUtf8Bytes(message);
7466 }
7467 return keccak256(concat([
7468 toUtf8Bytes(messagePrefix),
7469 toUtf8Bytes(String(message.length)),
7470 message
7471 ]));
7472}
7473
7474"use strict";
7475const logger$c = new Logger(version$4);
7476class LogDescription extends Description {
7477}
7478class TransactionDescription extends Description {
7479}
7480class Indexed extends Description {
7481 static isIndexed(value) {
7482 return !!(value && value._isIndexed);
7483 }
7484}
7485function wrapAccessError(property, error) {
7486 const wrap = new Error(`deferred error during ABI decoding triggered accessing ${property}`);
7487 wrap.error = error;
7488 return wrap;
7489}
7490/*
7491function checkNames(fragment: Fragment, type: "input" | "output", params: Array<ParamType>): void {
7492 params.reduce((accum, param) => {
7493 if (param.name) {
7494 if (accum[param.name]) {
7495 logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment);
7496 }
7497 accum[param.name] = true;
7498 }
7499 return accum;
7500 }, <{ [ name: string ]: boolean }>{ });
7501}
7502*/
7503class Interface {
7504 constructor(fragments) {
7505 logger$c.checkNew(new.target, Interface);
7506 let abi = [];
7507 if (typeof (fragments) === "string") {
7508 abi = JSON.parse(fragments);
7509 }
7510 else {
7511 abi = fragments;
7512 }
7513 defineReadOnly(this, "fragments", abi.map((fragment) => {
7514 return Fragment.from(fragment);
7515 }).filter((fragment) => (fragment != null)));
7516 defineReadOnly(this, "_abiCoder", getStatic((new.target), "getAbiCoder")());
7517 defineReadOnly(this, "functions", {});
7518 defineReadOnly(this, "errors", {});
7519 defineReadOnly(this, "events", {});
7520 defineReadOnly(this, "structs", {});
7521 // Add all fragments by their signature
7522 this.fragments.forEach((fragment) => {
7523 let bucket = null;
7524 switch (fragment.type) {
7525 case "constructor":
7526 if (this.deploy) {
7527 logger$c.warn("duplicate definition - constructor");
7528 return;
7529 }
7530 //checkNames(fragment, "input", fragment.inputs);
7531 defineReadOnly(this, "deploy", fragment);
7532 return;
7533 case "function":
7534 //checkNames(fragment, "input", fragment.inputs);
7535 //checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
7536 bucket = this.functions;
7537 break;
7538 case "event":
7539 //checkNames(fragment, "input", fragment.inputs);
7540 bucket = this.events;
7541 break;
7542 default:
7543 return;
7544 }
7545 let signature = fragment.format();
7546 if (bucket[signature]) {
7547 logger$c.warn("duplicate definition - " + signature);
7548 return;
7549 }
7550 bucket[signature] = fragment;
7551 });
7552 // If we do not have a constructor add a default
7553 if (!this.deploy) {
7554 defineReadOnly(this, "deploy", ConstructorFragment.from({
7555 payable: false,
7556 type: "constructor"
7557 }));
7558 }
7559 defineReadOnly(this, "_isInterface", true);
7560 }
7561 format(format) {
7562 if (!format) {
7563 format = FormatTypes.full;
7564 }
7565 if (format === FormatTypes.sighash) {
7566 logger$c.throwArgumentError("interface does not support formatting sighash", "format", format);
7567 }
7568 const abi = this.fragments.map((fragment) => fragment.format(format));
7569 // We need to re-bundle the JSON fragments a bit
7570 if (format === FormatTypes.json) {
7571 return JSON.stringify(abi.map((j) => JSON.parse(j)));
7572 }
7573 return abi;
7574 }
7575 // Sub-classes can override these to handle other blockchains
7576 static getAbiCoder() {
7577 return defaultAbiCoder;
7578 }
7579 static getAddress(address) {
7580 return getAddress(address);
7581 }
7582 static getSighash(functionFragment) {
7583 return hexDataSlice(id(functionFragment.format()), 0, 4);
7584 }
7585 static getEventTopic(eventFragment) {
7586 return id(eventFragment.format());
7587 }
7588 // Find a function definition by any means necessary (unless it is ambiguous)
7589 getFunction(nameOrSignatureOrSighash) {
7590 if (isHexString(nameOrSignatureOrSighash)) {
7591 for (const name in this.functions) {
7592 if (nameOrSignatureOrSighash === this.getSighash(name)) {
7593 return this.functions[name];
7594 }
7595 }
7596 logger$c.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash);
7597 }
7598 // It is a bare name, look up the function (will return null if ambiguous)
7599 if (nameOrSignatureOrSighash.indexOf("(") === -1) {
7600 const name = nameOrSignatureOrSighash.trim();
7601 const matching = Object.keys(this.functions).filter((f) => (f.split("(" /* fix:) */)[0] === name));
7602 if (matching.length === 0) {
7603 logger$c.throwArgumentError("no matching function", "name", name);
7604 }
7605 else if (matching.length > 1) {
7606 logger$c.throwArgumentError("multiple matching functions", "name", name);
7607 }
7608 return this.functions[matching[0]];
7609 }
7610 // Normlize the signature and lookup the function
7611 const result = this.functions[FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
7612 if (!result) {
7613 logger$c.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash);
7614 }
7615 return result;
7616 }
7617 // Find an event definition by any means necessary (unless it is ambiguous)
7618 getEvent(nameOrSignatureOrTopic) {
7619 if (isHexString(nameOrSignatureOrTopic)) {
7620 const topichash = nameOrSignatureOrTopic.toLowerCase();
7621 for (const name in this.events) {
7622 if (topichash === this.getEventTopic(name)) {
7623 return this.events[name];
7624 }
7625 }
7626 logger$c.throwArgumentError("no matching event", "topichash", topichash);
7627 }
7628 // It is a bare name, look up the function (will return null if ambiguous)
7629 if (nameOrSignatureOrTopic.indexOf("(") === -1) {
7630 const name = nameOrSignatureOrTopic.trim();
7631 const matching = Object.keys(this.events).filter((f) => (f.split("(" /* fix:) */)[0] === name));
7632 if (matching.length === 0) {
7633 logger$c.throwArgumentError("no matching event", "name", name);
7634 }
7635 else if (matching.length > 1) {
7636 logger$c.throwArgumentError("multiple matching events", "name", name);
7637 }
7638 return this.events[matching[0]];
7639 }
7640 // Normlize the signature and lookup the function
7641 const result = this.events[EventFragment.fromString(nameOrSignatureOrTopic).format()];
7642 if (!result) {
7643 logger$c.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic);
7644 }
7645 return result;
7646 }
7647 // Get the sighash (the bytes4 selector) used by Solidity to identify a function
7648 getSighash(functionFragment) {
7649 if (typeof (functionFragment) === "string") {
7650 functionFragment = this.getFunction(functionFragment);
7651 }
7652 return getStatic(this.constructor, "getSighash")(functionFragment);
7653 }
7654 // Get the topic (the bytes32 hash) used by Solidity to identify an event
7655 getEventTopic(eventFragment) {
7656 if (typeof (eventFragment) === "string") {
7657 eventFragment = this.getEvent(eventFragment);
7658 }
7659 return getStatic(this.constructor, "getEventTopic")(eventFragment);
7660 }
7661 _decodeParams(params, data) {
7662 return this._abiCoder.decode(params, data);
7663 }
7664 _encodeParams(params, values) {
7665 return this._abiCoder.encode(params, values);
7666 }
7667 encodeDeploy(values) {
7668 return this._encodeParams(this.deploy.inputs, values || []);
7669 }
7670 // Decode the data for a function call (e.g. tx.data)
7671 decodeFunctionData(functionFragment, data) {
7672 if (typeof (functionFragment) === "string") {
7673 functionFragment = this.getFunction(functionFragment);
7674 }
7675 const bytes = arrayify(data);
7676 if (hexlify(bytes.slice(0, 4)) !== this.getSighash(functionFragment)) {
7677 logger$c.throwArgumentError(`data signature does not match function ${functionFragment.name}.`, "data", hexlify(bytes));
7678 }
7679 return this._decodeParams(functionFragment.inputs, bytes.slice(4));
7680 }
7681 // Encode the data for a function call (e.g. tx.data)
7682 encodeFunctionData(functionFragment, values) {
7683 if (typeof (functionFragment) === "string") {
7684 functionFragment = this.getFunction(functionFragment);
7685 }
7686 return hexlify(concat([
7687 this.getSighash(functionFragment),
7688 this._encodeParams(functionFragment.inputs, values || [])
7689 ]));
7690 }
7691 // Decode the result from a function call (e.g. from eth_call)
7692 decodeFunctionResult(functionFragment, data) {
7693 if (typeof (functionFragment) === "string") {
7694 functionFragment = this.getFunction(functionFragment);
7695 }
7696 let bytes = arrayify(data);
7697 let reason = null;
7698 let errorSignature = null;
7699 switch (bytes.length % this._abiCoder._getWordSize()) {
7700 case 0:
7701 try {
7702 return this._abiCoder.decode(functionFragment.outputs, bytes);
7703 }
7704 catch (error) { }
7705 break;
7706 case 4:
7707 if (hexlify(bytes.slice(0, 4)) === "0x08c379a0") {
7708 errorSignature = "Error(string)";
7709 reason = this._abiCoder.decode(["string"], bytes.slice(4))[0];
7710 }
7711 break;
7712 }
7713 return logger$c.throwError("call revert exception", Logger.errors.CALL_EXCEPTION, {
7714 method: functionFragment.format(),
7715 errorSignature: errorSignature,
7716 errorArgs: [reason],
7717 reason: reason
7718 });
7719 }
7720 // Encode the result for a function call (e.g. for eth_call)
7721 encodeFunctionResult(functionFragment, values) {
7722 if (typeof (functionFragment) === "string") {
7723 functionFragment = this.getFunction(functionFragment);
7724 }
7725 return hexlify(this._abiCoder.encode(functionFragment.outputs, values || []));
7726 }
7727 // Create the filter for the event with search criteria (e.g. for eth_filterLog)
7728 encodeFilterTopics(eventFragment, values) {
7729 if (typeof (eventFragment) === "string") {
7730 eventFragment = this.getEvent(eventFragment);
7731 }
7732 if (values.length > eventFragment.inputs.length) {
7733 logger$c.throwError("too many arguments for " + eventFragment.format(), Logger.errors.UNEXPECTED_ARGUMENT, {
7734 argument: "values",
7735 value: values
7736 });
7737 }
7738 let topics = [];
7739 if (!eventFragment.anonymous) {
7740 topics.push(this.getEventTopic(eventFragment));
7741 }
7742 const encodeTopic = (param, value) => {
7743 if (param.type === "string") {
7744 return id(value);
7745 }
7746 else if (param.type === "bytes") {
7747 return keccak256(hexlify(value));
7748 }
7749 // Check addresses are valid
7750 if (param.type === "address") {
7751 this._abiCoder.encode(["address"], [value]);
7752 }
7753 return hexZeroPad(hexlify(value), 32);
7754 };
7755 values.forEach((value, index) => {
7756 let param = eventFragment.inputs[index];
7757 if (!param.indexed) {
7758 if (value != null) {
7759 logger$c.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
7760 }
7761 return;
7762 }
7763 if (value == null) {
7764 topics.push(null);
7765 }
7766 else if (param.baseType === "array" || param.baseType === "tuple") {
7767 logger$c.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
7768 }
7769 else if (Array.isArray(value)) {
7770 topics.push(value.map((value) => encodeTopic(param, value)));
7771 }
7772 else {
7773 topics.push(encodeTopic(param, value));
7774 }
7775 });
7776 // Trim off trailing nulls
7777 while (topics.length && topics[topics.length - 1] === null) {
7778 topics.pop();
7779 }
7780 return topics;
7781 }
7782 encodeEventLog(eventFragment, values) {
7783 if (typeof (eventFragment) === "string") {
7784 eventFragment = this.getEvent(eventFragment);
7785 }
7786 const topics = [];
7787 const dataTypes = [];
7788 const dataValues = [];
7789 if (!eventFragment.anonymous) {
7790 topics.push(this.getEventTopic(eventFragment));
7791 }
7792 if (values.length !== eventFragment.inputs.length) {
7793 logger$c.throwArgumentError("event arguments/values mismatch", "values", values);
7794 }
7795 eventFragment.inputs.forEach((param, index) => {
7796 const value = values[index];
7797 if (param.indexed) {
7798 if (param.type === "string") {
7799 topics.push(id(value));
7800 }
7801 else if (param.type === "bytes") {
7802 topics.push(keccak256(value));
7803 }
7804 else if (param.baseType === "tuple" || param.baseType === "array") {
7805 // @TOOD
7806 throw new Error("not implemented");
7807 }
7808 else {
7809 topics.push(this._abiCoder.encode([param.type], [value]));
7810 }
7811 }
7812 else {
7813 dataTypes.push(param);
7814 dataValues.push(value);
7815 }
7816 });
7817 return {
7818 data: this._abiCoder.encode(dataTypes, dataValues),
7819 topics: topics
7820 };
7821 }
7822 // Decode a filter for the event and the search criteria
7823 decodeEventLog(eventFragment, data, topics) {
7824 if (typeof (eventFragment) === "string") {
7825 eventFragment = this.getEvent(eventFragment);
7826 }
7827 if (topics != null && !eventFragment.anonymous) {
7828 let topicHash = this.getEventTopic(eventFragment);
7829 if (!isHexString(topics[0], 32) || topics[0].toLowerCase() !== topicHash) {
7830 logger$c.throwError("fragment/topic mismatch", Logger.errors.INVALID_ARGUMENT, { argument: "topics[0]", expected: topicHash, value: topics[0] });
7831 }
7832 topics = topics.slice(1);
7833 }
7834 let indexed = [];
7835 let nonIndexed = [];
7836 let dynamic = [];
7837 eventFragment.inputs.forEach((param, index) => {
7838 if (param.indexed) {
7839 if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
7840 indexed.push(ParamType.fromObject({ type: "bytes32", name: param.name }));
7841 dynamic.push(true);
7842 }
7843 else {
7844 indexed.push(param);
7845 dynamic.push(false);
7846 }
7847 }
7848 else {
7849 nonIndexed.push(param);
7850 dynamic.push(false);
7851 }
7852 });
7853 let resultIndexed = (topics != null) ? this._abiCoder.decode(indexed, concat(topics)) : null;
7854 let resultNonIndexed = this._abiCoder.decode(nonIndexed, data);
7855 let result = [];
7856 let nonIndexedIndex = 0, indexedIndex = 0;
7857 eventFragment.inputs.forEach((param, index) => {
7858 if (param.indexed) {
7859 if (resultIndexed == null) {
7860 result[index] = new Indexed({ _isIndexed: true, hash: null });
7861 }
7862 else if (dynamic[index]) {
7863 result[index] = new Indexed({ _isIndexed: true, hash: resultIndexed[indexedIndex++] });
7864 }
7865 else {
7866 try {
7867 result[index] = resultIndexed[indexedIndex++];
7868 }
7869 catch (error) {
7870 result[index] = error;
7871 }
7872 }
7873 }
7874 else {
7875 try {
7876 result[index] = resultNonIndexed[nonIndexedIndex++];
7877 }
7878 catch (error) {
7879 result[index] = error;
7880 }
7881 }
7882 // Add the keyword argument if named and safe
7883 if (param.name && result[param.name] == null) {
7884 const value = result[index];
7885 // Make error named values throw on access
7886 if (value instanceof Error) {
7887 Object.defineProperty(result, param.name, {
7888 get: () => { throw wrapAccessError(`property ${JSON.stringify(param.name)}`, value); }
7889 });
7890 }
7891 else {
7892 result[param.name] = value;
7893 }
7894 }
7895 });
7896 // Make all error indexed values throw on access
7897 for (let i = 0; i < result.length; i++) {
7898 const value = result[i];
7899 if (value instanceof Error) {
7900 Object.defineProperty(result, i, {
7901 get: () => { throw wrapAccessError(`index ${i}`, value); }
7902 });
7903 }
7904 }
7905 return Object.freeze(result);
7906 }
7907 // Given a transaction, find the matching function fragment (if any) and
7908 // determine all its properties and call parameters
7909 parseTransaction(tx) {
7910 let fragment = this.getFunction(tx.data.substring(0, 10).toLowerCase());
7911 if (!fragment) {
7912 return null;
7913 }
7914 return new TransactionDescription({
7915 args: this._abiCoder.decode(fragment.inputs, "0x" + tx.data.substring(10)),
7916 functionFragment: fragment,
7917 name: fragment.name,
7918 signature: fragment.format(),
7919 sighash: this.getSighash(fragment),
7920 value: BigNumber.from(tx.value || "0"),
7921 });
7922 }
7923 // Given an event log, find the matching event fragment (if any) and
7924 // determine all its properties and values
7925 parseLog(log) {
7926 let fragment = this.getEvent(log.topics[0]);
7927 if (!fragment || fragment.anonymous) {
7928 return null;
7929 }
7930 // @TODO: If anonymous, and the only method, and the input count matches, should we parse?
7931 // Probably not, because just because it is the only event in the ABI does
7932 // not mean we have the full ABI; maybe jsut a fragment?
7933 return new LogDescription({
7934 eventFragment: fragment,
7935 name: fragment.name,
7936 signature: fragment.format(),
7937 topic: this.getEventTopic(fragment),
7938 args: this.decodeEventLog(fragment, log.data, log.topics)
7939 });
7940 }
7941 /*
7942 static from(value: Array<Fragment | string | JsonAbi> | string | Interface) {
7943 if (Interface.isInterface(value)) {
7944 return value;
7945 }
7946 if (typeof(value) === "string") {
7947 return new Interface(JSON.parse(value));
7948 }
7949 return new Interface(value);
7950 }
7951 */
7952 static isInterface(value) {
7953 return !!(value && value._isInterface);
7954 }
7955}
7956
7957"use strict";
7958
7959const version$9 = "abstract-provider/5.0.2";
7960
7961"use strict";
7962const logger$d = new Logger(version$9);
7963;
7964;
7965//export type CallTransactionable = {
7966// call(transaction: TransactionRequest): Promise<TransactionResponse>;
7967//};
7968class ForkEvent extends Description {
7969 static isForkEvent(value) {
7970 return !!(value && value._isForkEvent);
7971 }
7972}
7973class BlockForkEvent extends ForkEvent {
7974 constructor(blockHash, expiry) {
7975 if (!isHexString(blockHash, 32)) {
7976 logger$d.throwArgumentError("invalid blockHash", "blockHash", blockHash);
7977 }
7978 super({
7979 _isForkEvent: true,
7980 _isBlockForkEvent: true,
7981 expiry: (expiry || 0),
7982 blockHash: blockHash
7983 });
7984 }
7985}
7986class TransactionForkEvent extends ForkEvent {
7987 constructor(hash, expiry) {
7988 if (!isHexString(hash, 32)) {
7989 logger$d.throwArgumentError("invalid transaction hash", "hash", hash);
7990 }
7991 super({
7992 _isForkEvent: true,
7993 _isTransactionForkEvent: true,
7994 expiry: (expiry || 0),
7995 hash: hash
7996 });
7997 }
7998}
7999class TransactionOrderForkEvent extends ForkEvent {
8000 constructor(beforeHash, afterHash, expiry) {
8001 if (!isHexString(beforeHash, 32)) {
8002 logger$d.throwArgumentError("invalid transaction hash", "beforeHash", beforeHash);
8003 }
8004 if (!isHexString(afterHash, 32)) {
8005 logger$d.throwArgumentError("invalid transaction hash", "afterHash", afterHash);
8006 }
8007 super({
8008 _isForkEvent: true,
8009 _isTransactionOrderForkEvent: true,
8010 expiry: (expiry || 0),
8011 beforeHash: beforeHash,
8012 afterHash: afterHash
8013 });
8014 }
8015}
8016///////////////////////////////
8017// Exported Abstracts
8018class Provider {
8019 constructor() {
8020 logger$d.checkAbstract(new.target, Provider);
8021 defineReadOnly(this, "_isProvider", true);
8022 }
8023 // Alias for "on"
8024 addListener(eventName, listener) {
8025 return this.on(eventName, listener);
8026 }
8027 // Alias for "off"
8028 removeListener(eventName, listener) {
8029 return this.off(eventName, listener);
8030 }
8031 static isProvider(value) {
8032 return !!(value && value._isProvider);
8033 }
8034}
8035
8036const version$a = "abstract-signer/5.0.2";
8037
8038"use strict";
8039var __awaiter$1 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
8040 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8041 return new (P || (P = Promise))(function (resolve, reject) {
8042 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8043 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8044 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8045 step((generator = generator.apply(thisArg, _arguments || [])).next());
8046 });
8047};
8048const logger$e = new Logger(version$a);
8049const allowedTransactionKeys = [
8050 "chainId", "data", "from", "gasLimit", "gasPrice", "nonce", "to", "value"
8051];
8052// Sub-Class Notes:
8053// - A Signer MUST always make sure, that if present, the "from" field
8054// matches the Signer, before sending or signing a transaction
8055// - A Signer SHOULD always wrap private information (such as a private
8056// key or mnemonic) in a function, so that console.log does not leak
8057// the data
8058class Signer {
8059 ///////////////////
8060 // Sub-classes MUST call super
8061 constructor() {
8062 logger$e.checkAbstract(new.target, Signer);
8063 defineReadOnly(this, "_isSigner", true);
8064 }
8065 ///////////////////
8066 // Sub-classes MAY override these
8067 getBalance(blockTag) {
8068 return __awaiter$1(this, void 0, void 0, function* () {
8069 this._checkProvider("getBalance");
8070 return yield this.provider.getBalance(this.getAddress(), blockTag);
8071 });
8072 }
8073 getTransactionCount(blockTag) {
8074 return __awaiter$1(this, void 0, void 0, function* () {
8075 this._checkProvider("getTransactionCount");
8076 return yield this.provider.getTransactionCount(this.getAddress(), blockTag);
8077 });
8078 }
8079 // Populates "from" if unspecified, and estimates the gas for the transation
8080 estimateGas(transaction) {
8081 return __awaiter$1(this, void 0, void 0, function* () {
8082 this._checkProvider("estimateGas");
8083 const tx = yield resolveProperties(this.checkTransaction(transaction));
8084 return yield this.provider.estimateGas(tx);
8085 });
8086 }
8087 // Populates "from" if unspecified, and calls with the transation
8088 call(transaction, blockTag) {
8089 return __awaiter$1(this, void 0, void 0, function* () {
8090 this._checkProvider("call");
8091 const tx = yield resolveProperties(this.checkTransaction(transaction));
8092 return yield this.provider.call(tx, blockTag);
8093 });
8094 }
8095 // Populates all fields in a transaction, signs it and sends it to the network
8096 sendTransaction(transaction) {
8097 this._checkProvider("sendTransaction");
8098 return this.populateTransaction(transaction).then((tx) => {
8099 return this.signTransaction(tx).then((signedTx) => {
8100 return this.provider.sendTransaction(signedTx);
8101 });
8102 });
8103 }
8104 getChainId() {
8105 return __awaiter$1(this, void 0, void 0, function* () {
8106 this._checkProvider("getChainId");
8107 const network = yield this.provider.getNetwork();
8108 return network.chainId;
8109 });
8110 }
8111 getGasPrice() {
8112 return __awaiter$1(this, void 0, void 0, function* () {
8113 this._checkProvider("getGasPrice");
8114 return yield this.provider.getGasPrice();
8115 });
8116 }
8117 resolveName(name) {
8118 return __awaiter$1(this, void 0, void 0, function* () {
8119 this._checkProvider("resolveName");
8120 return yield this.provider.resolveName(name);
8121 });
8122 }
8123 // Checks a transaction does not contain invalid keys and if
8124 // no "from" is provided, populates it.
8125 // - does NOT require a provider
8126 // - adds "from" is not present
8127 // - returns a COPY (safe to mutate the result)
8128 // By default called from: (overriding these prevents it)
8129 // - call
8130 // - estimateGas
8131 // - populateTransaction (and therefor sendTransaction)
8132 checkTransaction(transaction) {
8133 for (const key in transaction) {
8134 if (allowedTransactionKeys.indexOf(key) === -1) {
8135 logger$e.throwArgumentError("invalid transaction key: " + key, "transaction", transaction);
8136 }
8137 }
8138 const tx = shallowCopy(transaction);
8139 if (tx.from == null) {
8140 tx.from = this.getAddress();
8141 }
8142 else {
8143 // Make sure any provided address matches this signer
8144 tx.from = Promise.all([
8145 Promise.resolve(tx.from),
8146 this.getAddress()
8147 ]).then((result) => {
8148 if (result[0] !== result[1]) {
8149 logger$e.throwArgumentError("from address mismatch", "transaction", transaction);
8150 }
8151 return result[0];
8152 });
8153 }
8154 return tx;
8155 }
8156 // Populates ALL keys for a transaction and checks that "from" matches
8157 // this Signer. Should be used by sendTransaction but NOT by signTransaction.
8158 // By default called from: (overriding these prevents it)
8159 // - sendTransaction
8160 populateTransaction(transaction) {
8161 return __awaiter$1(this, void 0, void 0, function* () {
8162 const tx = yield resolveProperties(this.checkTransaction(transaction));
8163 if (tx.to != null) {
8164 tx.to = Promise.resolve(tx.to).then((to) => this.resolveName(to));
8165 }
8166 if (tx.gasPrice == null) {
8167 tx.gasPrice = this.getGasPrice();
8168 }
8169 if (tx.nonce == null) {
8170 tx.nonce = this.getTransactionCount("pending");
8171 }
8172 if (tx.gasLimit == null) {
8173 tx.gasLimit = this.estimateGas(tx).catch((error) => {
8174 return logger$e.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
8175 error: error,
8176 tx: tx
8177 });
8178 });
8179 }
8180 if (tx.chainId == null) {
8181 tx.chainId = this.getChainId();
8182 }
8183 else {
8184 tx.chainId = Promise.all([
8185 Promise.resolve(tx.chainId),
8186 this.getChainId()
8187 ]).then((results) => {
8188 if (results[1] !== 0 && results[0] !== results[1]) {
8189 logger$e.throwArgumentError("chainId address mismatch", "transaction", transaction);
8190 }
8191 return results[0];
8192 });
8193 }
8194 return yield resolveProperties(tx);
8195 });
8196 }
8197 ///////////////////
8198 // Sub-classes SHOULD leave these alone
8199 _checkProvider(operation) {
8200 if (!this.provider) {
8201 logger$e.throwError("missing provider", Logger.errors.UNSUPPORTED_OPERATION, {
8202 operation: (operation || "_checkProvider")
8203 });
8204 }
8205 }
8206 static isSigner(value) {
8207 return !!(value && value._isSigner);
8208 }
8209}
8210class VoidSigner extends Signer {
8211 constructor(address, provider) {
8212 logger$e.checkNew(new.target, VoidSigner);
8213 super();
8214 defineReadOnly(this, "address", address);
8215 defineReadOnly(this, "provider", provider || null);
8216 }
8217 getAddress() {
8218 return Promise.resolve(this.address);
8219 }
8220 _fail(message, operation) {
8221 return Promise.resolve().then(() => {
8222 logger$e.throwError(message, Logger.errors.UNSUPPORTED_OPERATION, { operation: operation });
8223 });
8224 }
8225 signMessage(message) {
8226 return this._fail("VoidSigner cannot sign messages", "signMessage");
8227 }
8228 signTransaction(transaction) {
8229 return this._fail("VoidSigner cannot sign transactions", "signTransaction");
8230 }
8231 connect(provider) {
8232 return new VoidSigner(this.address, provider);
8233 }
8234}
8235
8236const version$b = "contracts/5.0.2";
8237
8238"use strict";
8239var __awaiter$2 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
8240 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8241 return new (P || (P = Promise))(function (resolve, reject) {
8242 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
8243 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8244 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8245 step((generator = generator.apply(thisArg, _arguments || [])).next());
8246 });
8247};
8248const logger$f = new Logger(version$b);
8249;
8250;
8251///////////////////////////////
8252const allowedTransactionKeys$1 = {
8253 chainId: true, data: true, from: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true
8254};
8255function resolveName(resolver, nameOrPromise) {
8256 return __awaiter$2(this, void 0, void 0, function* () {
8257 const name = yield nameOrPromise;
8258 // If it is already an address, just use it (after adding checksum)
8259 try {
8260 return getAddress(name);
8261 }
8262 catch (error) { }
8263 if (!resolver) {
8264 logger$f.throwError("a provider or signer is needed to resolve ENS names", Logger.errors.UNSUPPORTED_OPERATION, {
8265 operation: "resolveName"
8266 });
8267 }
8268 return yield resolver.resolveName(name);
8269 });
8270}
8271// Recursively replaces ENS names with promises to resolve the name and resolves all properties
8272function resolveAddresses(resolver, value, paramType) {
8273 if (Array.isArray(paramType)) {
8274 return Promise.all(paramType.map((paramType, index) => {
8275 return resolveAddresses(resolver, ((Array.isArray(value)) ? value[index] : value[paramType.name]), paramType);
8276 }));
8277 }
8278 if (paramType.type === "address") {
8279 return resolveName(resolver, value);
8280 }
8281 if (paramType.type === "tuple") {
8282 return resolveAddresses(resolver, value, paramType.components);
8283 }
8284 if (paramType.baseType === "array") {
8285 if (!Array.isArray(value)) {
8286 throw new Error("invalid value for array");
8287 }
8288 return Promise.all(value.map((v) => resolveAddresses(resolver, v, paramType.arrayChildren)));
8289 }
8290 return Promise.resolve(value);
8291}
8292function populateTransaction(contract, fragment, args) {
8293 return __awaiter$2(this, void 0, void 0, function* () {
8294 // If an extra argument is given, it is overrides
8295 let overrides = {};
8296 if (args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
8297 overrides = shallowCopy(args.pop());
8298 }
8299 // Make sure the parameter count matches
8300 logger$f.checkArgumentCount(args.length, fragment.inputs.length, "passed to contract");
8301 // Populate "from" override (allow promises)
8302 if (contract.signer) {
8303 if (overrides.from) {
8304 // Contracts with a Signer are from the Signer's frame-of-reference;
8305 // but we allow overriding "from" if it matches the signer
8306 overrides.from = resolveProperties({
8307 override: resolveName(contract.signer, overrides.from),
8308 signer: contract.signer.getAddress()
8309 }).then((check) => __awaiter$2(this, void 0, void 0, function* () {
8310 if (getAddress(check.signer) !== check.override) {
8311 logger$f.throwError("Contract with a Signer cannot override from", Logger.errors.UNSUPPORTED_OPERATION, {
8312 operation: "overrides.from"
8313 });
8314 }
8315 return check.override;
8316 }));
8317 }
8318 else {
8319 overrides.from = contract.signer.getAddress();
8320 }
8321 }
8322 else if (overrides.from) {
8323 overrides.from = resolveName(contract.provider, overrides.from);
8324 //} else {
8325 // Contracts without a signer can override "from", and if
8326 // unspecified the zero address is used
8327 //overrides.from = AddressZero;
8328 }
8329 // Wait for all dependencies to be resolved (prefer the signer over the provider)
8330 const resolved = yield resolveProperties({
8331 args: resolveAddresses(contract.signer || contract.provider, args, fragment.inputs),
8332 address: contract.resolvedAddress,
8333 overrides: (resolveProperties(overrides) || {})
8334 });
8335 // The ABI coded transaction
8336 const tx = {
8337 data: contract.interface.encodeFunctionData(fragment, resolved.args),
8338 to: resolved.address
8339 };
8340 // Resolved Overrides
8341 const ro = resolved.overrides;
8342 // Populate simple overrides
8343 if (ro.nonce != null) {
8344 tx.nonce = BigNumber.from(ro.nonce).toNumber();
8345 }
8346 if (ro.gasLimit != null) {
8347 tx.gasLimit = BigNumber.from(ro.gasLimit);
8348 }
8349 if (ro.gasPrice != null) {
8350 tx.gasPrice = BigNumber.from(ro.gasPrice);
8351 }
8352 if (ro.from != null) {
8353 tx.from = ro.from;
8354 }
8355 // If there was no "gasLimit" override, but the ABI specifies a default, use it
8356 if (tx.gasLimit == null && fragment.gas != null) {
8357 tx.gasLimit = BigNumber.from(fragment.gas).add(21000);
8358 }
8359 // Populate "value" override
8360 if (ro.value) {
8361 const roValue = BigNumber.from(ro.value);
8362 if (!roValue.isZero() && !fragment.payable) {
8363 logger$f.throwError("non-payable method cannot override value", Logger.errors.UNSUPPORTED_OPERATION, {
8364 operation: "overrides.value",
8365 value: overrides.value
8366 });
8367 }
8368 tx.value = roValue;
8369 }
8370 // Remvoe the overrides
8371 delete overrides.nonce;
8372 delete overrides.gasLimit;
8373 delete overrides.gasPrice;
8374 delete overrides.from;
8375 delete overrides.value;
8376 // Make sure there are no stray overrides, which may indicate a
8377 // typo or using an unsupported key.
8378 const leftovers = Object.keys(overrides).filter((key) => (overrides[key] != null));
8379 if (leftovers.length) {
8380 logger$f.throwError(`cannot override ${leftovers.map((l) => JSON.stringify(l)).join(",")}`, Logger.errors.UNSUPPORTED_OPERATION, {
8381 operation: "overrides",
8382 overrides: leftovers
8383 });
8384 }
8385 return tx;
8386 });
8387}
8388function buildPopulate(contract, fragment) {
8389 return function (...args) {
8390 return __awaiter$2(this, void 0, void 0, function* () {
8391 return populateTransaction(contract, fragment, args);
8392 });
8393 };
8394}
8395function buildEstimate(contract, fragment) {
8396 const signerOrProvider = (contract.signer || contract.provider);
8397 return function (...args) {
8398 return __awaiter$2(this, void 0, void 0, function* () {
8399 if (!signerOrProvider) {
8400 logger$f.throwError("estimate require a provider or signer", Logger.errors.UNSUPPORTED_OPERATION, {
8401 operation: "estimateGas"
8402 });
8403 }
8404 const tx = yield populateTransaction(contract, fragment, args);
8405 return yield signerOrProvider.estimateGas(tx);
8406 });
8407 };
8408}
8409function buildCall(contract, fragment, collapseSimple) {
8410 const signerOrProvider = (contract.signer || contract.provider);
8411 return function (...args) {
8412 return __awaiter$2(this, void 0, void 0, function* () {
8413 // Extract the "blockTag" override if present
8414 let blockTag = undefined;
8415 if (args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
8416 const overrides = shallowCopy(args.pop());
8417 if (overrides.blockTag != null) {
8418 blockTag = yield overrides.blockTag;
8419 }
8420 delete overrides.blockTag;
8421 args.push(overrides);
8422 }
8423 // If the contract was just deployed, wait until it is mined
8424 if (contract.deployTransaction != null) {
8425 yield contract._deployed(blockTag);
8426 }
8427 // Call a node and get the result
8428 const tx = yield populateTransaction(contract, fragment, args);
8429 const result = yield signerOrProvider.call(tx, blockTag);
8430 try {
8431 let value = contract.interface.decodeFunctionResult(fragment, result);
8432 if (collapseSimple && fragment.outputs.length === 1) {
8433 value = value[0];
8434 }
8435 return value;
8436 }
8437 catch (error) {
8438 if (error.code === Logger.errors.CALL_EXCEPTION) {
8439 error.address = contract.address;
8440 error.args = args;
8441 error.transaction = tx;
8442 }
8443 throw error;
8444 }
8445 });
8446 };
8447}
8448function buildSend(contract, fragment) {
8449 return function (...args) {
8450 return __awaiter$2(this, void 0, void 0, function* () {
8451 if (!contract.signer) {
8452 logger$f.throwError("sending a transaction requires a signer", Logger.errors.UNSUPPORTED_OPERATION, {
8453 operation: "sendTransaction"
8454 });
8455 }
8456 // If the contract was just deployed, wait until it is minded
8457 if (contract.deployTransaction != null) {
8458 yield contract._deployed();
8459 }
8460 const txRequest = yield populateTransaction(contract, fragment, args);
8461 const tx = yield contract.signer.sendTransaction(txRequest);
8462 // Tweak the tw.wait so the receipt has extra properties
8463 const wait = tx.wait.bind(tx);
8464 tx.wait = (confirmations) => {
8465 return wait(confirmations).then((receipt) => {
8466 receipt.events = receipt.logs.map((log) => {
8467 let event = deepCopy(log);
8468 let parsed = null;
8469 try {
8470 parsed = contract.interface.parseLog(log);
8471 }
8472 catch (e) { }
8473 // Successfully parsed the event log; include it
8474 if (parsed) {
8475 event.args = parsed.args;
8476 event.decode = (data, topics) => {
8477 return contract.interface.decodeEventLog(parsed.eventFragment, data, topics);
8478 };
8479 event.event = parsed.name;
8480 event.eventSignature = parsed.signature;
8481 }
8482 // Useful operations
8483 event.removeListener = () => { return contract.provider; };
8484 event.getBlock = () => {
8485 return contract.provider.getBlock(receipt.blockHash);
8486 };
8487 event.getTransaction = () => {
8488 return contract.provider.getTransaction(receipt.transactionHash);
8489 };
8490 event.getTransactionReceipt = () => {
8491 return Promise.resolve(receipt);
8492 };
8493 return event;
8494 });
8495 return receipt;
8496 });
8497 };
8498 return tx;
8499 });
8500 };
8501}
8502function buildDefault(contract, fragment, collapseSimple) {
8503 if (fragment.constant) {
8504 return buildCall(contract, fragment, collapseSimple);
8505 }
8506 return buildSend(contract, fragment);
8507}
8508function getEventTag(filter) {
8509 if (filter.address && (filter.topics == null || filter.topics.length === 0)) {
8510 return "*";
8511 }
8512 return (filter.address || "*") + "@" + (filter.topics ? filter.topics.map((topic) => {
8513 if (Array.isArray(topic)) {
8514 return topic.join("|");
8515 }
8516 return topic;
8517 }).join(":") : "");
8518}
8519class RunningEvent {
8520 constructor(tag, filter) {
8521 defineReadOnly(this, "tag", tag);
8522 defineReadOnly(this, "filter", filter);
8523 this._listeners = [];
8524 }
8525 addListener(listener, once) {
8526 this._listeners.push({ listener: listener, once: once });
8527 }
8528 removeListener(listener) {
8529 let done = false;
8530 this._listeners = this._listeners.filter((item) => {
8531 if (done || item.listener !== listener) {
8532 return true;
8533 }
8534 done = true;
8535 return false;
8536 });
8537 }
8538 removeAllListeners() {
8539 this._listeners = [];
8540 }
8541 listeners() {
8542 return this._listeners.map((i) => i.listener);
8543 }
8544 listenerCount() {
8545 return this._listeners.length;
8546 }
8547 run(args) {
8548 const listenerCount = this.listenerCount();
8549 this._listeners = this._listeners.filter((item) => {
8550 const argsCopy = args.slice();
8551 // Call the callback in the next event loop
8552 setTimeout(() => {
8553 item.listener.apply(this, argsCopy);
8554 }, 0);
8555 // Reschedule it if it not "once"
8556 return !(item.once);
8557 });
8558 return listenerCount;
8559 }
8560 prepareEvent(event) {
8561 }
8562 // Returns the array that will be applied to an emit
8563 getEmit(event) {
8564 return [event];
8565 }
8566}
8567class ErrorRunningEvent extends RunningEvent {
8568 constructor() {
8569 super("error", null);
8570 }
8571}
8572// @TODO Fragment should inherit Wildcard? and just override getEmit?
8573// or have a common abstract super class, with enough constructor
8574// options to configure both.
8575// A Fragment Event will populate all the properties that Wildcard
8576// will, and additioanlly dereference the arguments when emitting
8577class FragmentRunningEvent extends RunningEvent {
8578 constructor(address, contractInterface, fragment, topics) {
8579 const filter = {
8580 address: address
8581 };
8582 let topic = contractInterface.getEventTopic(fragment);
8583 if (topics) {
8584 if (topic !== topics[0]) {
8585 logger$f.throwArgumentError("topic mismatch", "topics", topics);
8586 }
8587 filter.topics = topics.slice();
8588 }
8589 else {
8590 filter.topics = [topic];
8591 }
8592 super(getEventTag(filter), filter);
8593 defineReadOnly(this, "address", address);
8594 defineReadOnly(this, "interface", contractInterface);
8595 defineReadOnly(this, "fragment", fragment);
8596 }
8597 prepareEvent(event) {
8598 super.prepareEvent(event);
8599 event.event = this.fragment.name;
8600 event.eventSignature = this.fragment.format();
8601 event.decode = (data, topics) => {
8602 return this.interface.decodeEventLog(this.fragment, data, topics);
8603 };
8604 try {
8605 event.args = this.interface.decodeEventLog(this.fragment, event.data, event.topics);
8606 }
8607 catch (error) {
8608 event.args = null;
8609 event.decodeError = error;
8610 }
8611 }
8612 getEmit(event) {
8613 const errors = checkResultErrors(event.args);
8614 if (errors.length) {
8615 throw errors[0].error;
8616 }
8617 const args = (event.args || []).slice();
8618 args.push(event);
8619 return args;
8620 }
8621}
8622// A Wildard Event will attempt to populate:
8623// - event The name of the event name
8624// - eventSignature The full signature of the event
8625// - decode A function to decode data and topics
8626// - args The decoded data and topics
8627class WildcardRunningEvent extends RunningEvent {
8628 constructor(address, contractInterface) {
8629 super("*", { address: address });
8630 defineReadOnly(this, "address", address);
8631 defineReadOnly(this, "interface", contractInterface);
8632 }
8633 prepareEvent(event) {
8634 super.prepareEvent(event);
8635 try {
8636 const parsed = this.interface.parseLog(event);
8637 event.event = parsed.name;
8638 event.eventSignature = parsed.signature;
8639 event.decode = (data, topics) => {
8640 return this.interface.decodeEventLog(parsed.eventFragment, data, topics);
8641 };
8642 event.args = parsed.args;
8643 }
8644 catch (error) {
8645 // No matching event
8646 }
8647 }
8648}
8649class Contract {
8650 constructor(addressOrName, contractInterface, signerOrProvider) {
8651 logger$f.checkNew(new.target, Contract);
8652 // @TODO: Maybe still check the addressOrName looks like a valid address or name?
8653 //address = getAddress(address);
8654 defineReadOnly(this, "interface", getStatic((new.target), "getInterface")(contractInterface));
8655 if (signerOrProvider == null) {
8656 defineReadOnly(this, "provider", null);
8657 defineReadOnly(this, "signer", null);
8658 }
8659 else if (Signer.isSigner(signerOrProvider)) {
8660 defineReadOnly(this, "provider", signerOrProvider.provider || null);
8661 defineReadOnly(this, "signer", signerOrProvider);
8662 }
8663 else if (Provider.isProvider(signerOrProvider)) {
8664 defineReadOnly(this, "provider", signerOrProvider);
8665 defineReadOnly(this, "signer", null);
8666 }
8667 else {
8668 logger$f.throwArgumentError("invalid signer or provider", "signerOrProvider", signerOrProvider);
8669 }
8670 defineReadOnly(this, "callStatic", {});
8671 defineReadOnly(this, "estimateGas", {});
8672 defineReadOnly(this, "functions", {});
8673 defineReadOnly(this, "populateTransaction", {});
8674 defineReadOnly(this, "filters", {});
8675 {
8676 const uniqueFilters = {};
8677 Object.keys(this.interface.events).forEach((eventSignature) => {
8678 const event = this.interface.events[eventSignature];
8679 defineReadOnly(this.filters, eventSignature, (...args) => {
8680 return {
8681 address: this.address,
8682 topics: this.interface.encodeFilterTopics(event, args)
8683 };
8684 });
8685 if (!uniqueFilters[event.name]) {
8686 uniqueFilters[event.name] = [];
8687 }
8688 uniqueFilters[event.name].push(eventSignature);
8689 });
8690 Object.keys(uniqueFilters).forEach((name) => {
8691 const filters = uniqueFilters[name];
8692 if (filters.length === 1) {
8693 defineReadOnly(this.filters, name, this.filters[filters[0]]);
8694 }
8695 else {
8696 logger$f.warn(`Duplicate definition of ${name} (${filters.join(", ")})`);
8697 }
8698 });
8699 }
8700 defineReadOnly(this, "_runningEvents", {});
8701 defineReadOnly(this, "_wrappedEmits", {});
8702 defineReadOnly(this, "address", addressOrName);
8703 if (this.provider) {
8704 defineReadOnly(this, "resolvedAddress", this.provider.resolveName(addressOrName).then((address) => {
8705 if (address == null) {
8706 throw new Error("name not found");
8707 }
8708 return address;
8709 }).catch((error) => {
8710 console.log("ERROR: Cannot find Contract - " + addressOrName);
8711 throw error;
8712 }));
8713 }
8714 else {
8715 try {
8716 defineReadOnly(this, "resolvedAddress", Promise.resolve(getAddress(addressOrName)));
8717 }
8718 catch (error) {
8719 // Without a provider, we cannot use ENS names
8720 logger$f.throwError("provider is required to use ENS name as contract address", Logger.errors.UNSUPPORTED_OPERATION, {
8721 operation: "new Contract"
8722 });
8723 }
8724 }
8725 const uniqueNames = {};
8726 const uniqueSignatures = {};
8727 Object.keys(this.interface.functions).forEach((signature) => {
8728 const fragment = this.interface.functions[signature];
8729 // Check that the signature is unique; if not the ABI generation has
8730 // not been cleaned or may be incorrectly generated
8731 if (uniqueSignatures[signature]) {
8732 logger$f.warn(`Duplicate ABI entry for ${JSON.stringify(name)}`);
8733 return;
8734 }
8735 uniqueSignatures[signature] = true;
8736 // Track unique names; we only expose bare named functions if they
8737 // are ambiguous
8738 {
8739 const name = fragment.name;
8740 if (!uniqueNames[name]) {
8741 uniqueNames[name] = [];
8742 }
8743 uniqueNames[name].push(signature);
8744 }
8745 if (this[signature] == null) {
8746 defineReadOnly(this, signature, buildDefault(this, fragment, true));
8747 }
8748 // We do not collapse simple calls on this bucket, which allows
8749 // frameworks to safely use this without introspection as well as
8750 // allows decoding error recovery.
8751 if (this.functions[signature] == null) {
8752 defineReadOnly(this.functions, signature, buildDefault(this, fragment, false));
8753 }
8754 if (this.callStatic[signature] == null) {
8755 defineReadOnly(this.callStatic, signature, buildCall(this, fragment, true));
8756 }
8757 if (this.populateTransaction[signature] == null) {
8758 defineReadOnly(this.populateTransaction, signature, buildPopulate(this, fragment));
8759 }
8760 if (this.estimateGas[signature] == null) {
8761 defineReadOnly(this.estimateGas, signature, buildEstimate(this, fragment));
8762 }
8763 });
8764 Object.keys(uniqueNames).forEach((name) => {
8765 // Ambiguous names to not get attached as bare names
8766 const signatures = uniqueNames[name];
8767 if (signatures.length > 1) {
8768 return;
8769 }
8770 const signature = signatures[0];
8771 if (this[name] == null) {
8772 defineReadOnly(this, name, this[signature]);
8773 }
8774 if (this.functions[name] == null) {
8775 defineReadOnly(this.functions, name, this.functions[signature]);
8776 }
8777 if (this.callStatic[name] == null) {
8778 defineReadOnly(this.callStatic, name, this.callStatic[signature]);
8779 }
8780 if (this.populateTransaction[name] == null) {
8781 defineReadOnly(this.populateTransaction, name, this.populateTransaction[signature]);
8782 }
8783 if (this.estimateGas[name] == null) {
8784 defineReadOnly(this.estimateGas, name, this.estimateGas[signature]);
8785 }
8786 });
8787 }
8788 static getContractAddress(transaction) {
8789 return getContractAddress(transaction);
8790 }
8791 static getInterface(contractInterface) {
8792 if (Interface.isInterface(contractInterface)) {
8793 return contractInterface;
8794 }
8795 return new Interface(contractInterface);
8796 }
8797 // @TODO: Allow timeout?
8798 deployed() {
8799 return this._deployed();
8800 }
8801 _deployed(blockTag) {
8802 if (!this._deployedPromise) {
8803 // If we were just deployed, we know the transaction we should occur in
8804 if (this.deployTransaction) {
8805 this._deployedPromise = this.deployTransaction.wait().then(() => {
8806 return this;
8807 });
8808 }
8809 else {
8810 // @TODO: Once we allow a timeout to be passed in, we will wait
8811 // up to that many blocks for getCode
8812 // Otherwise, poll for our code to be deployed
8813 this._deployedPromise = this.provider.getCode(this.address, blockTag).then((code) => {
8814 if (code === "0x") {
8815 logger$f.throwError("contract not deployed", Logger.errors.UNSUPPORTED_OPERATION, {
8816 contractAddress: this.address,
8817 operation: "getDeployed"
8818 });
8819 }
8820 return this;
8821 });
8822 }
8823 }
8824 return this._deployedPromise;
8825 }
8826 // @TODO:
8827 // estimateFallback(overrides?: TransactionRequest): Promise<BigNumber>
8828 // @TODO:
8829 // estimateDeploy(bytecode: string, ...args): Promise<BigNumber>
8830 fallback(overrides) {
8831 if (!this.signer) {
8832 logger$f.throwError("sending a transactions require a signer", Logger.errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction(fallback)" });
8833 }
8834 const tx = shallowCopy(overrides || {});
8835 ["from", "to"].forEach(function (key) {
8836 if (tx[key] == null) {
8837 return;
8838 }
8839 logger$f.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { operation: key });
8840 });
8841 tx.to = this.resolvedAddress;
8842 return this.deployed().then(() => {
8843 return this.signer.sendTransaction(tx);
8844 });
8845 }
8846 // Reconnect to a different signer or provider
8847 connect(signerOrProvider) {
8848 if (typeof (signerOrProvider) === "string") {
8849 signerOrProvider = new VoidSigner(signerOrProvider, this.provider);
8850 }
8851 const contract = new (this.constructor)(this.address, this.interface, signerOrProvider);
8852 if (this.deployTransaction) {
8853 defineReadOnly(contract, "deployTransaction", this.deployTransaction);
8854 }
8855 return contract;
8856 }
8857 // Re-attach to a different on-chain instance of this contract
8858 attach(addressOrName) {
8859 return new (this.constructor)(addressOrName, this.interface, this.signer || this.provider);
8860 }
8861 static isIndexed(value) {
8862 return Indexed.isIndexed(value);
8863 }
8864 _normalizeRunningEvent(runningEvent) {
8865 // Already have an instance of this event running; we can re-use it
8866 if (this._runningEvents[runningEvent.tag]) {
8867 return this._runningEvents[runningEvent.tag];
8868 }
8869 return runningEvent;
8870 }
8871 _getRunningEvent(eventName) {
8872 if (typeof (eventName) === "string") {
8873 // Listen for "error" events (if your contract has an error event, include
8874 // the full signature to bypass this special event keyword)
8875 if (eventName === "error") {
8876 return this._normalizeRunningEvent(new ErrorRunningEvent());
8877 }
8878 // Listen for any event that is registered
8879 if (eventName === "event") {
8880 return this._normalizeRunningEvent(new RunningEvent("event", null));
8881 }
8882 // Listen for any event
8883 if (eventName === "*") {
8884 return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface));
8885 }
8886 // Get the event Fragment (throws if ambiguous/unknown event)
8887 const fragment = this.interface.getEvent(eventName);
8888 return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment));
8889 }
8890 // We have topics to filter by...
8891 if (eventName.topics && eventName.topics.length > 0) {
8892 // Is it a known topichash? (throws if no matching topichash)
8893 try {
8894 const topic = eventName.topics[0];
8895 if (typeof (topic) !== "string") {
8896 throw new Error("invalid topic"); // @TODO: May happen for anonymous events
8897 }
8898 const fragment = this.interface.getEvent(topic);
8899 return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment, eventName.topics));
8900 }
8901 catch (error) { }
8902 // Filter by the unknown topichash
8903 const filter = {
8904 address: this.address,
8905 topics: eventName.topics
8906 };
8907 return this._normalizeRunningEvent(new RunningEvent(getEventTag(filter), filter));
8908 }
8909 return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface));
8910 }
8911 _checkRunningEvents(runningEvent) {
8912 if (runningEvent.listenerCount() === 0) {
8913 delete this._runningEvents[runningEvent.tag];
8914 // If we have a poller for this, remove it
8915 const emit = this._wrappedEmits[runningEvent.tag];
8916 if (emit) {
8917 this.provider.off(runningEvent.filter, emit);
8918 delete this._wrappedEmits[runningEvent.tag];
8919 }
8920 }
8921 }
8922 // Subclasses can override this to gracefully recover
8923 // from parse errors if they wish
8924 _wrapEvent(runningEvent, log, listener) {
8925 const event = deepCopy(log);
8926 event.removeListener = () => {
8927 if (!listener) {
8928 return;
8929 }
8930 runningEvent.removeListener(listener);
8931 this._checkRunningEvents(runningEvent);
8932 };
8933 event.getBlock = () => { return this.provider.getBlock(log.blockHash); };
8934 event.getTransaction = () => { return this.provider.getTransaction(log.transactionHash); };
8935 event.getTransactionReceipt = () => { return this.provider.getTransactionReceipt(log.transactionHash); };
8936 // This may throw if the topics and data mismatch the signature
8937 runningEvent.prepareEvent(event);
8938 return event;
8939 }
8940 _addEventListener(runningEvent, listener, once) {
8941 if (!this.provider) {
8942 logger$f.throwError("events require a provider or a signer with a provider", Logger.errors.UNSUPPORTED_OPERATION, { operation: "once" });
8943 }
8944 runningEvent.addListener(listener, once);
8945 // Track this running event and its listeners (may already be there; but no hard in updating)
8946 this._runningEvents[runningEvent.tag] = runningEvent;
8947 // If we are not polling the provider, start polling
8948 if (!this._wrappedEmits[runningEvent.tag]) {
8949 const wrappedEmit = (log) => {
8950 let event = this._wrapEvent(runningEvent, log, listener);
8951 // Try to emit the result for the parameterized event...
8952 if (event.decodeError == null) {
8953 try {
8954 const args = runningEvent.getEmit(event);
8955 this.emit(runningEvent.filter, ...args);
8956 }
8957 catch (error) {
8958 event.decodeError = error.error;
8959 }
8960 }
8961 // Always emit "event" for fragment-base events
8962 if (runningEvent.filter != null) {
8963 this.emit("event", event);
8964 }
8965 // Emit "error" if there was an error
8966 if (event.decodeError != null) {
8967 this.emit("error", event.decodeError, event);
8968 }
8969 };
8970 this._wrappedEmits[runningEvent.tag] = wrappedEmit;
8971 // Special events, like "error" do not have a filter
8972 if (runningEvent.filter != null) {
8973 this.provider.on(runningEvent.filter, wrappedEmit);
8974 }
8975 }
8976 }
8977 queryFilter(event, fromBlockOrBlockhash, toBlock) {
8978 const runningEvent = this._getRunningEvent(event);
8979 const filter = shallowCopy(runningEvent.filter);
8980 if (typeof (fromBlockOrBlockhash) === "string" && isHexString(fromBlockOrBlockhash, 32)) {
8981 if (toBlock != null) {
8982 logger$f.throwArgumentError("cannot specify toBlock with blockhash", "toBlock", toBlock);
8983 }
8984 filter.blockHash = fromBlockOrBlockhash;
8985 }
8986 else {
8987 filter.fromBlock = ((fromBlockOrBlockhash != null) ? fromBlockOrBlockhash : 0);
8988 filter.toBlock = ((toBlock != null) ? toBlock : "latest");
8989 }
8990 return this.provider.getLogs(filter).then((logs) => {
8991 return logs.map((log) => this._wrapEvent(runningEvent, log, null));
8992 });
8993 }
8994 on(event, listener) {
8995 this._addEventListener(this._getRunningEvent(event), listener, false);
8996 return this;
8997 }
8998 once(event, listener) {
8999 this._addEventListener(this._getRunningEvent(event), listener, true);
9000 return this;
9001 }
9002 emit(eventName, ...args) {
9003 if (!this.provider) {
9004 return false;
9005 }
9006 const runningEvent = this._getRunningEvent(eventName);
9007 const result = (runningEvent.run(args) > 0);
9008 // May have drained all the "once" events; check for living events
9009 this._checkRunningEvents(runningEvent);
9010 return result;
9011 }
9012 listenerCount(eventName) {
9013 if (!this.provider) {
9014 return 0;
9015 }
9016 return this._getRunningEvent(eventName).listenerCount();
9017 }
9018 listeners(eventName) {
9019 if (!this.provider) {
9020 return [];
9021 }
9022 if (eventName == null) {
9023 const result = [];
9024 for (let tag in this._runningEvents) {
9025 this._runningEvents[tag].listeners().forEach((listener) => {
9026 result.push(listener);
9027 });
9028 }
9029 return result;
9030 }
9031 return this._getRunningEvent(eventName).listeners();
9032 }
9033 removeAllListeners(eventName) {
9034 if (!this.provider) {
9035 return this;
9036 }
9037 if (eventName == null) {
9038 for (const tag in this._runningEvents) {
9039 const runningEvent = this._runningEvents[tag];
9040 runningEvent.removeAllListeners();
9041 this._checkRunningEvents(runningEvent);
9042 }
9043 return this;
9044 }
9045 // Delete any listeners
9046 const runningEvent = this._getRunningEvent(eventName);
9047 runningEvent.removeAllListeners();
9048 this._checkRunningEvents(runningEvent);
9049 return this;
9050 }
9051 off(eventName, listener) {
9052 if (!this.provider) {
9053 return this;
9054 }
9055 const runningEvent = this._getRunningEvent(eventName);
9056 runningEvent.removeListener(listener);
9057 this._checkRunningEvents(runningEvent);
9058 return this;
9059 }
9060 removeListener(eventName, listener) {
9061 return this.off(eventName, listener);
9062 }
9063}
9064class ContractFactory {
9065 constructor(contractInterface, bytecode, signer) {
9066 let bytecodeHex = null;
9067 if (typeof (bytecode) === "string") {
9068 bytecodeHex = bytecode;
9069 }
9070 else if (isBytes(bytecode)) {
9071 bytecodeHex = hexlify(bytecode);
9072 }
9073 else if (bytecode && typeof (bytecode.object) === "string") {
9074 // Allow the bytecode object from the Solidity compiler
9075 bytecodeHex = bytecode.object;
9076 }
9077 else {
9078 // Crash in the next verification step
9079 bytecodeHex = "!";
9080 }
9081 // Make sure it is 0x prefixed
9082 if (bytecodeHex.substring(0, 2) !== "0x") {
9083 bytecodeHex = "0x" + bytecodeHex;
9084 }
9085 // Make sure the final result is valid bytecode
9086 if (!isHexString(bytecodeHex) || (bytecodeHex.length % 2)) {
9087 logger$f.throwArgumentError("invalid bytecode", "bytecode", bytecode);
9088 }
9089 // If we have a signer, make sure it is valid
9090 if (signer && !Signer.isSigner(signer)) {
9091 logger$f.throwArgumentError("invalid signer", "signer", signer);
9092 }
9093 defineReadOnly(this, "bytecode", bytecodeHex);
9094 defineReadOnly(this, "interface", getStatic((new.target), "getInterface")(contractInterface));
9095 defineReadOnly(this, "signer", signer || null);
9096 }
9097 // @TODO: Future; rename to populteTransaction?
9098 getDeployTransaction(...args) {
9099 let tx = {};
9100 // If we have 1 additional argument, we allow transaction overrides
9101 if (args.length === this.interface.deploy.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
9102 tx = shallowCopy(args.pop());
9103 for (const key in tx) {
9104 if (!allowedTransactionKeys$1[key]) {
9105 throw new Error("unknown transaction override " + key);
9106 }
9107 }
9108 }
9109 // Do not allow these to be overridden in a deployment transaction
9110 ["data", "from", "to"].forEach((key) => {
9111 if (tx[key] == null) {
9112 return;
9113 }
9114 logger$f.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { operation: key });
9115 });
9116 // Make sure the call matches the constructor signature
9117 logger$f.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
9118 // Set the data to the bytecode + the encoded constructor arguments
9119 tx.data = hexlify(concat([
9120 this.bytecode,
9121 this.interface.encodeDeploy(args)
9122 ]));
9123 return tx;
9124 }
9125 deploy(...args) {
9126 return __awaiter$2(this, void 0, void 0, function* () {
9127 let overrides = {};
9128 // If 1 extra parameter was passed in, it contains overrides
9129 if (args.length === this.interface.deploy.inputs.length + 1) {
9130 overrides = args.pop();
9131 }
9132 // Make sure the call matches the constructor signature
9133 logger$f.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
9134 // Resolve ENS names and promises in the arguments
9135 const params = yield resolveAddresses(this.signer, args, this.interface.deploy.inputs);
9136 params.push(overrides);
9137 // Get the deployment transaction (with optional overrides)
9138 const unsignedTx = this.getDeployTransaction(...params);
9139 // Send the deployment transaction
9140 const tx = yield this.signer.sendTransaction(unsignedTx);
9141 const address = getStatic(this.constructor, "getContractAddress")(tx);
9142 const contract = getStatic(this.constructor, "getContract")(address, this.interface, this.signer);
9143 defineReadOnly(contract, "deployTransaction", tx);
9144 return contract;
9145 });
9146 }
9147 attach(address) {
9148 return (this.constructor).getContract(address, this.interface, this.signer);
9149 }
9150 connect(signer) {
9151 return new (this.constructor)(this.interface, this.bytecode, signer);
9152 }
9153 static fromSolidity(compilerOutput, signer) {
9154 if (compilerOutput == null) {
9155 logger$f.throwError("missing compiler output", Logger.errors.MISSING_ARGUMENT, { argument: "compilerOutput" });
9156 }
9157 if (typeof (compilerOutput) === "string") {
9158 compilerOutput = JSON.parse(compilerOutput);
9159 }
9160 const abi = compilerOutput.abi;
9161 let bytecode = null;
9162 if (compilerOutput.bytecode) {
9163 bytecode = compilerOutput.bytecode;
9164 }
9165 else if (compilerOutput.evm && compilerOutput.evm.bytecode) {
9166 bytecode = compilerOutput.evm.bytecode;
9167 }
9168 return new this(abi, bytecode, signer);
9169 }
9170 static getInterface(contractInterface) {
9171 return Contract.getInterface(contractInterface);
9172 }
9173 static getContractAddress(tx) {
9174 return getContractAddress(tx);
9175 }
9176 static getContract(address, contractInterface, signer) {
9177 return new Contract(address, contractInterface, signer);
9178 }
9179}
9180
9181/**
9182 * var basex = require("base-x");
9183 *
9184 * This implementation is heavily based on base-x. The main reason to
9185 * deviate was to prevent the dependency of Buffer.
9186 *
9187 * Contributors:
9188 *
9189 * base-x encoding
9190 * Forked from https://github.com/cryptocoinjs/bs58
9191 * Originally written by Mike Hearn for BitcoinJ
9192 * Copyright (c) 2011 Google Inc
9193 * Ported to JavaScript by Stefan Thomas
9194 * Merged Buffer refactorings from base58-native by Stephen Pair
9195 * Copyright (c) 2013 BitPay Inc
9196 *
9197 * The MIT License (MIT)
9198 *
9199 * Copyright base-x contributors (c) 2016
9200 *
9201 * Permission is hereby granted, free of charge, to any person obtaining a
9202 * copy of this software and associated documentation files (the "Software"),
9203 * to deal in the Software without restriction, including without limitation
9204 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9205 * and/or sell copies of the Software, and to permit persons to whom the
9206 * Software is furnished to do so, subject to the following conditions:
9207 *
9208 * The above copyright notice and this permission notice shall be included in
9209 * all copies or substantial portions of the Software.
9210
9211 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9212 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9213 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9214 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9215 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
9216 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
9217 * IN THE SOFTWARE.
9218 *
9219 */
9220class BaseX {
9221 constructor(alphabet) {
9222 defineReadOnly(this, "alphabet", alphabet);
9223 defineReadOnly(this, "base", alphabet.length);
9224 defineReadOnly(this, "_alphabetMap", {});
9225 defineReadOnly(this, "_leader", alphabet.charAt(0));
9226 // pre-compute lookup table
9227 for (let i = 0; i < alphabet.length; i++) {
9228 this._alphabetMap[alphabet.charAt(i)] = i;
9229 }
9230 }
9231 encode(value) {
9232 let source = arrayify(value);
9233 if (source.length === 0) {
9234 return "";
9235 }
9236 let digits = [0];
9237 for (let i = 0; i < source.length; ++i) {
9238 let carry = source[i];
9239 for (let j = 0; j < digits.length; ++j) {
9240 carry += digits[j] << 8;
9241 digits[j] = carry % this.base;
9242 carry = (carry / this.base) | 0;
9243 }
9244 while (carry > 0) {
9245 digits.push(carry % this.base);
9246 carry = (carry / this.base) | 0;
9247 }
9248 }
9249 let string = "";
9250 // deal with leading zeros
9251 for (let k = 0; source[k] === 0 && k < source.length - 1; ++k) {
9252 string += this._leader;
9253 }
9254 // convert digits to a string
9255 for (let q = digits.length - 1; q >= 0; --q) {
9256 string += this.alphabet[digits[q]];
9257 }
9258 return string;
9259 }
9260 decode(value) {
9261 if (typeof (value) !== "string") {
9262 throw new TypeError("Expected String");
9263 }
9264 let bytes = [];
9265 if (value.length === 0) {
9266 return new Uint8Array(bytes);
9267 }
9268 bytes.push(0);
9269 for (let i = 0; i < value.length; i++) {
9270 let byte = this._alphabetMap[value[i]];
9271 if (byte === undefined) {
9272 throw new Error("Non-base" + this.base + " character");
9273 }
9274 let carry = byte;
9275 for (let j = 0; j < bytes.length; ++j) {
9276 carry += bytes[j] * this.base;
9277 bytes[j] = carry & 0xff;
9278 carry >>= 8;
9279 }
9280 while (carry > 0) {
9281 bytes.push(carry & 0xff);
9282 carry >>= 8;
9283 }
9284 }
9285 // deal with leading zeros
9286 for (let k = 0; value[k] === this._leader && k < value.length - 1; ++k) {
9287 bytes.push(0);
9288 }
9289 return arrayify(new Uint8Array(bytes.reverse()));
9290 }
9291}
9292const Base32 = new BaseX("abcdefghijklmnopqrstuvwxyz234567");
9293const Base58 = new BaseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
9294//console.log(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj"))
9295//console.log(Base58.encode(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj")))
9296
9297var minimalisticAssert = assert;
9298
9299function assert(val, msg) {
9300 if (!val)
9301 throw new Error(msg || 'Assertion failed');
9302}
9303
9304assert.equal = function assertEqual(l, r, msg) {
9305 if (l != r)
9306 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
9307};
9308
9309var inherits_browser = createCommonjsModule(function (module) {
9310if (typeof Object.create === 'function') {
9311 // implementation from standard node.js 'util' module
9312 module.exports = function inherits(ctor, superCtor) {
9313 if (superCtor) {
9314 ctor.super_ = superCtor;
9315 ctor.prototype = Object.create(superCtor.prototype, {
9316 constructor: {
9317 value: ctor,
9318 enumerable: false,
9319 writable: true,
9320 configurable: true
9321 }
9322 });
9323 }
9324 };
9325} else {
9326 // old school shim for old browsers
9327 module.exports = function inherits(ctor, superCtor) {
9328 if (superCtor) {
9329 ctor.super_ = superCtor;
9330 var TempCtor = function () {};
9331 TempCtor.prototype = superCtor.prototype;
9332 ctor.prototype = new TempCtor();
9333 ctor.prototype.constructor = ctor;
9334 }
9335 };
9336}
9337});
9338
9339'use strict';
9340
9341
9342
9343
9344var inherits_1 = inherits_browser;
9345
9346function toArray(msg, enc) {
9347 if (Array.isArray(msg))
9348 return msg.slice();
9349 if (!msg)
9350 return [];
9351 var res = [];
9352 if (typeof msg === 'string') {
9353 if (!enc) {
9354 for (var i = 0; i < msg.length; i++) {
9355 var c = msg.charCodeAt(i);
9356 var hi = c >> 8;
9357 var lo = c & 0xff;
9358 if (hi)
9359 res.push(hi, lo);
9360 else
9361 res.push(lo);
9362 }
9363 } else if (enc === 'hex') {
9364 msg = msg.replace(/[^a-z0-9]+/ig, '');
9365 if (msg.length % 2 !== 0)
9366 msg = '0' + msg;
9367 for (i = 0; i < msg.length; i += 2)
9368 res.push(parseInt(msg[i] + msg[i + 1], 16));
9369 }
9370 } else {
9371 for (i = 0; i < msg.length; i++)
9372 res[i] = msg[i] | 0;
9373 }
9374 return res;
9375}
9376var toArray_1 = toArray;
9377
9378function toHex$1(msg) {
9379 var res = '';
9380 for (var i = 0; i < msg.length; i++)
9381 res += zero2(msg[i].toString(16));
9382 return res;
9383}
9384var toHex_1 = toHex$1;
9385
9386function htonl(w) {
9387 var res = (w >>> 24) |
9388 ((w >>> 8) & 0xff00) |
9389 ((w << 8) & 0xff0000) |
9390 ((w & 0xff) << 24);
9391 return res >>> 0;
9392}
9393var htonl_1 = htonl;
9394
9395function toHex32(msg, endian) {
9396 var res = '';
9397 for (var i = 0; i < msg.length; i++) {
9398 var w = msg[i];
9399 if (endian === 'little')
9400 w = htonl(w);
9401 res += zero8(w.toString(16));
9402 }
9403 return res;
9404}
9405var toHex32_1 = toHex32;
9406
9407function zero2(word) {
9408 if (word.length === 1)
9409 return '0' + word;
9410 else
9411 return word;
9412}
9413var zero2_1 = zero2;
9414
9415function zero8(word) {
9416 if (word.length === 7)
9417 return '0' + word;
9418 else if (word.length === 6)
9419 return '00' + word;
9420 else if (word.length === 5)
9421 return '000' + word;
9422 else if (word.length === 4)
9423 return '0000' + word;
9424 else if (word.length === 3)
9425 return '00000' + word;
9426 else if (word.length === 2)
9427 return '000000' + word;
9428 else if (word.length === 1)
9429 return '0000000' + word;
9430 else
9431 return word;
9432}
9433var zero8_1 = zero8;
9434
9435function join32(msg, start, end, endian) {
9436 var len = end - start;
9437 minimalisticAssert(len % 4 === 0);
9438 var res = new Array(len / 4);
9439 for (var i = 0, k = start; i < res.length; i++, k += 4) {
9440 var w;
9441 if (endian === 'big')
9442 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
9443 else
9444 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
9445 res[i] = w >>> 0;
9446 }
9447 return res;
9448}
9449var join32_1 = join32;
9450
9451function split32(msg, endian) {
9452 var res = new Array(msg.length * 4);
9453 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
9454 var m = msg[i];
9455 if (endian === 'big') {
9456 res[k] = m >>> 24;
9457 res[k + 1] = (m >>> 16) & 0xff;
9458 res[k + 2] = (m >>> 8) & 0xff;
9459 res[k + 3] = m & 0xff;
9460 } else {
9461 res[k + 3] = m >>> 24;
9462 res[k + 2] = (m >>> 16) & 0xff;
9463 res[k + 1] = (m >>> 8) & 0xff;
9464 res[k] = m & 0xff;
9465 }
9466 }
9467 return res;
9468}
9469var split32_1 = split32;
9470
9471function rotr32(w, b) {
9472 return (w >>> b) | (w << (32 - b));
9473}
9474var rotr32_1 = rotr32;
9475
9476function rotl32(w, b) {
9477 return (w << b) | (w >>> (32 - b));
9478}
9479var rotl32_1 = rotl32;
9480
9481function sum32(a, b) {
9482 return (a + b) >>> 0;
9483}
9484var sum32_1 = sum32;
9485
9486function sum32_3(a, b, c) {
9487 return (a + b + c) >>> 0;
9488}
9489var sum32_3_1 = sum32_3;
9490
9491function sum32_4(a, b, c, d) {
9492 return (a + b + c + d) >>> 0;
9493}
9494var sum32_4_1 = sum32_4;
9495
9496function sum32_5(a, b, c, d, e) {
9497 return (a + b + c + d + e) >>> 0;
9498}
9499var sum32_5_1 = sum32_5;
9500
9501function sum64(buf, pos, ah, al) {
9502 var bh = buf[pos];
9503 var bl = buf[pos + 1];
9504
9505 var lo = (al + bl) >>> 0;
9506 var hi = (lo < al ? 1 : 0) + ah + bh;
9507 buf[pos] = hi >>> 0;
9508 buf[pos + 1] = lo;
9509}
9510var sum64_1 = sum64;
9511
9512function sum64_hi(ah, al, bh, bl) {
9513 var lo = (al + bl) >>> 0;
9514 var hi = (lo < al ? 1 : 0) + ah + bh;
9515 return hi >>> 0;
9516}
9517var sum64_hi_1 = sum64_hi;
9518
9519function sum64_lo(ah, al, bh, bl) {
9520 var lo = al + bl;
9521 return lo >>> 0;
9522}
9523var sum64_lo_1 = sum64_lo;
9524
9525function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
9526 var carry = 0;
9527 var lo = al;
9528 lo = (lo + bl) >>> 0;
9529 carry += lo < al ? 1 : 0;
9530 lo = (lo + cl) >>> 0;
9531 carry += lo < cl ? 1 : 0;
9532 lo = (lo + dl) >>> 0;
9533 carry += lo < dl ? 1 : 0;
9534
9535 var hi = ah + bh + ch + dh + carry;
9536 return hi >>> 0;
9537}
9538var sum64_4_hi_1 = sum64_4_hi;
9539
9540function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
9541 var lo = al + bl + cl + dl;
9542 return lo >>> 0;
9543}
9544var sum64_4_lo_1 = sum64_4_lo;
9545
9546function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
9547 var carry = 0;
9548 var lo = al;
9549 lo = (lo + bl) >>> 0;
9550 carry += lo < al ? 1 : 0;
9551 lo = (lo + cl) >>> 0;
9552 carry += lo < cl ? 1 : 0;
9553 lo = (lo + dl) >>> 0;
9554 carry += lo < dl ? 1 : 0;
9555 lo = (lo + el) >>> 0;
9556 carry += lo < el ? 1 : 0;
9557
9558 var hi = ah + bh + ch + dh + eh + carry;
9559 return hi >>> 0;
9560}
9561var sum64_5_hi_1 = sum64_5_hi;
9562
9563function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
9564 var lo = al + bl + cl + dl + el;
9565
9566 return lo >>> 0;
9567}
9568var sum64_5_lo_1 = sum64_5_lo;
9569
9570function rotr64_hi(ah, al, num) {
9571 var r = (al << (32 - num)) | (ah >>> num);
9572 return r >>> 0;
9573}
9574var rotr64_hi_1 = rotr64_hi;
9575
9576function rotr64_lo(ah, al, num) {
9577 var r = (ah << (32 - num)) | (al >>> num);
9578 return r >>> 0;
9579}
9580var rotr64_lo_1 = rotr64_lo;
9581
9582function shr64_hi(ah, al, num) {
9583 return ah >>> num;
9584}
9585var shr64_hi_1 = shr64_hi;
9586
9587function shr64_lo(ah, al, num) {
9588 var r = (ah << (32 - num)) | (al >>> num);
9589 return r >>> 0;
9590}
9591var shr64_lo_1 = shr64_lo;
9592
9593var utils = {
9594 inherits: inherits_1,
9595 toArray: toArray_1,
9596 toHex: toHex_1,
9597 htonl: htonl_1,
9598 toHex32: toHex32_1,
9599 zero2: zero2_1,
9600 zero8: zero8_1,
9601 join32: join32_1,
9602 split32: split32_1,
9603 rotr32: rotr32_1,
9604 rotl32: rotl32_1,
9605 sum32: sum32_1,
9606 sum32_3: sum32_3_1,
9607 sum32_4: sum32_4_1,
9608 sum32_5: sum32_5_1,
9609 sum64: sum64_1,
9610 sum64_hi: sum64_hi_1,
9611 sum64_lo: sum64_lo_1,
9612 sum64_4_hi: sum64_4_hi_1,
9613 sum64_4_lo: sum64_4_lo_1,
9614 sum64_5_hi: sum64_5_hi_1,
9615 sum64_5_lo: sum64_5_lo_1,
9616 rotr64_hi: rotr64_hi_1,
9617 rotr64_lo: rotr64_lo_1,
9618 shr64_hi: shr64_hi_1,
9619 shr64_lo: shr64_lo_1
9620};
9621
9622'use strict';
9623
9624
9625
9626
9627function BlockHash() {
9628 this.pending = null;
9629 this.pendingTotal = 0;
9630 this.blockSize = this.constructor.blockSize;
9631 this.outSize = this.constructor.outSize;
9632 this.hmacStrength = this.constructor.hmacStrength;
9633 this.padLength = this.constructor.padLength / 8;
9634 this.endian = 'big';
9635
9636 this._delta8 = this.blockSize / 8;
9637 this._delta32 = this.blockSize / 32;
9638}
9639var BlockHash_1 = BlockHash;
9640
9641BlockHash.prototype.update = function update(msg, enc) {
9642 // Convert message to array, pad it, and join into 32bit blocks
9643 msg = utils.toArray(msg, enc);
9644 if (!this.pending)
9645 this.pending = msg;
9646 else
9647 this.pending = this.pending.concat(msg);
9648 this.pendingTotal += msg.length;
9649
9650 // Enough data, try updating
9651 if (this.pending.length >= this._delta8) {
9652 msg = this.pending;
9653
9654 // Process pending data in blocks
9655 var r = msg.length % this._delta8;
9656 this.pending = msg.slice(msg.length - r, msg.length);
9657 if (this.pending.length === 0)
9658 this.pending = null;
9659
9660 msg = utils.join32(msg, 0, msg.length - r, this.endian);
9661 for (var i = 0; i < msg.length; i += this._delta32)
9662 this._update(msg, i, i + this._delta32);
9663 }
9664
9665 return this;
9666};
9667
9668BlockHash.prototype.digest = function digest(enc) {
9669 this.update(this._pad());
9670 minimalisticAssert(this.pending === null);
9671
9672 return this._digest(enc);
9673};
9674
9675BlockHash.prototype._pad = function pad() {
9676 var len = this.pendingTotal;
9677 var bytes = this._delta8;
9678 var k = bytes - ((len + this.padLength) % bytes);
9679 var res = new Array(k + this.padLength);
9680 res[0] = 0x80;
9681 for (var i = 1; i < k; i++)
9682 res[i] = 0;
9683
9684 // Append length
9685 len <<= 3;
9686 if (this.endian === 'big') {
9687 for (var t = 8; t < this.padLength; t++)
9688 res[i++] = 0;
9689
9690 res[i++] = 0;
9691 res[i++] = 0;
9692 res[i++] = 0;
9693 res[i++] = 0;
9694 res[i++] = (len >>> 24) & 0xff;
9695 res[i++] = (len >>> 16) & 0xff;
9696 res[i++] = (len >>> 8) & 0xff;
9697 res[i++] = len & 0xff;
9698 } else {
9699 res[i++] = len & 0xff;
9700 res[i++] = (len >>> 8) & 0xff;
9701 res[i++] = (len >>> 16) & 0xff;
9702 res[i++] = (len >>> 24) & 0xff;
9703 res[i++] = 0;
9704 res[i++] = 0;
9705 res[i++] = 0;
9706 res[i++] = 0;
9707
9708 for (t = 8; t < this.padLength; t++)
9709 res[i++] = 0;
9710 }
9711
9712 return res;
9713};
9714
9715var common = {
9716 BlockHash: BlockHash_1
9717};
9718
9719var _1 = {};
9720
9721var _224 = {};
9722
9723'use strict';
9724
9725
9726var rotr32$1 = utils.rotr32;
9727
9728function ft_1(s, x, y, z) {
9729 if (s === 0)
9730 return ch32(x, y, z);
9731 if (s === 1 || s === 3)
9732 return p32(x, y, z);
9733 if (s === 2)
9734 return maj32(x, y, z);
9735}
9736var ft_1_1 = ft_1;
9737
9738function ch32(x, y, z) {
9739 return (x & y) ^ ((~x) & z);
9740}
9741var ch32_1 = ch32;
9742
9743function maj32(x, y, z) {
9744 return (x & y) ^ (x & z) ^ (y & z);
9745}
9746var maj32_1 = maj32;
9747
9748function p32(x, y, z) {
9749 return x ^ y ^ z;
9750}
9751var p32_1 = p32;
9752
9753function s0_256(x) {
9754 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
9755}
9756var s0_256_1 = s0_256;
9757
9758function s1_256(x) {
9759 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
9760}
9761var s1_256_1 = s1_256;
9762
9763function g0_256(x) {
9764 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
9765}
9766var g0_256_1 = g0_256;
9767
9768function g1_256(x) {
9769 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
9770}
9771var g1_256_1 = g1_256;
9772
9773var common$1 = {
9774 ft_1: ft_1_1,
9775 ch32: ch32_1,
9776 maj32: maj32_1,
9777 p32: p32_1,
9778 s0_256: s0_256_1,
9779 s1_256: s1_256_1,
9780 g0_256: g0_256_1,
9781 g1_256: g1_256_1
9782};
9783
9784'use strict';
9785
9786
9787
9788
9789
9790
9791var sum32$1 = utils.sum32;
9792var sum32_4$1 = utils.sum32_4;
9793var sum32_5$1 = utils.sum32_5;
9794var ch32$1 = common$1.ch32;
9795var maj32$1 = common$1.maj32;
9796var s0_256$1 = common$1.s0_256;
9797var s1_256$1 = common$1.s1_256;
9798var g0_256$1 = common$1.g0_256;
9799var g1_256$1 = common$1.g1_256;
9800
9801var BlockHash$1 = common.BlockHash;
9802
9803var sha256_K = [
9804 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
9805 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
9806 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
9807 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
9808 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
9809 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
9810 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
9811 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
9812 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
9813 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
9814 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
9815 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
9816 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
9817 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
9818 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
9819 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
9820];
9821
9822function SHA256() {
9823 if (!(this instanceof SHA256))
9824 return new SHA256();
9825
9826 BlockHash$1.call(this);
9827 this.h = [
9828 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
9829 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
9830 ];
9831 this.k = sha256_K;
9832 this.W = new Array(64);
9833}
9834utils.inherits(SHA256, BlockHash$1);
9835var _256 = SHA256;
9836
9837SHA256.blockSize = 512;
9838SHA256.outSize = 256;
9839SHA256.hmacStrength = 192;
9840SHA256.padLength = 64;
9841
9842SHA256.prototype._update = function _update(msg, start) {
9843 var W = this.W;
9844
9845 for (var i = 0; i < 16; i++)
9846 W[i] = msg[start + i];
9847 for (; i < W.length; i++)
9848 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
9849
9850 var a = this.h[0];
9851 var b = this.h[1];
9852 var c = this.h[2];
9853 var d = this.h[3];
9854 var e = this.h[4];
9855 var f = this.h[5];
9856 var g = this.h[6];
9857 var h = this.h[7];
9858
9859 minimalisticAssert(this.k.length === W.length);
9860 for (i = 0; i < W.length; i++) {
9861 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
9862 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
9863 h = g;
9864 g = f;
9865 f = e;
9866 e = sum32$1(d, T1);
9867 d = c;
9868 c = b;
9869 b = a;
9870 a = sum32$1(T1, T2);
9871 }
9872
9873 this.h[0] = sum32$1(this.h[0], a);
9874 this.h[1] = sum32$1(this.h[1], b);
9875 this.h[2] = sum32$1(this.h[2], c);
9876 this.h[3] = sum32$1(this.h[3], d);
9877 this.h[4] = sum32$1(this.h[4], e);
9878 this.h[5] = sum32$1(this.h[5], f);
9879 this.h[6] = sum32$1(this.h[6], g);
9880 this.h[7] = sum32$1(this.h[7], h);
9881};
9882
9883SHA256.prototype._digest = function digest(enc) {
9884 if (enc === 'hex')
9885 return utils.toHex32(this.h, 'big');
9886 else
9887 return utils.split32(this.h, 'big');
9888};
9889
9890var _384 = {};
9891
9892'use strict';
9893
9894
9895
9896
9897
9898var rotr64_hi$1 = utils.rotr64_hi;
9899var rotr64_lo$1 = utils.rotr64_lo;
9900var shr64_hi$1 = utils.shr64_hi;
9901var shr64_lo$1 = utils.shr64_lo;
9902var sum64$1 = utils.sum64;
9903var sum64_hi$1 = utils.sum64_hi;
9904var sum64_lo$1 = utils.sum64_lo;
9905var sum64_4_hi$1 = utils.sum64_4_hi;
9906var sum64_4_lo$1 = utils.sum64_4_lo;
9907var sum64_5_hi$1 = utils.sum64_5_hi;
9908var sum64_5_lo$1 = utils.sum64_5_lo;
9909
9910var BlockHash$2 = common.BlockHash;
9911
9912var sha512_K = [
9913 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
9914 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
9915 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
9916 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
9917 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
9918 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
9919 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
9920 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
9921 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
9922 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
9923 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
9924 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
9925 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
9926 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
9927 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
9928 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
9929 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
9930 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
9931 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
9932 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
9933 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
9934 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
9935 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
9936 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
9937 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
9938 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
9939 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
9940 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
9941 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
9942 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
9943 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
9944 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
9945 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
9946 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
9947 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
9948 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
9949 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
9950 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
9951 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
9952 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
9953];
9954
9955function SHA512() {
9956 if (!(this instanceof SHA512))
9957 return new SHA512();
9958
9959 BlockHash$2.call(this);
9960 this.h = [
9961 0x6a09e667, 0xf3bcc908,
9962 0xbb67ae85, 0x84caa73b,
9963 0x3c6ef372, 0xfe94f82b,
9964 0xa54ff53a, 0x5f1d36f1,
9965 0x510e527f, 0xade682d1,
9966 0x9b05688c, 0x2b3e6c1f,
9967 0x1f83d9ab, 0xfb41bd6b,
9968 0x5be0cd19, 0x137e2179 ];
9969 this.k = sha512_K;
9970 this.W = new Array(160);
9971}
9972utils.inherits(SHA512, BlockHash$2);
9973var _512 = SHA512;
9974
9975SHA512.blockSize = 1024;
9976SHA512.outSize = 512;
9977SHA512.hmacStrength = 192;
9978SHA512.padLength = 128;
9979
9980SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
9981 var W = this.W;
9982
9983 // 32 x 32bit words
9984 for (var i = 0; i < 32; i++)
9985 W[i] = msg[start + i];
9986 for (; i < W.length; i += 2) {
9987 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
9988 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
9989 var c1_hi = W[i - 14]; // i - 7
9990 var c1_lo = W[i - 13];
9991 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
9992 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
9993 var c3_hi = W[i - 32]; // i - 16
9994 var c3_lo = W[i - 31];
9995
9996 W[i] = sum64_4_hi$1(
9997 c0_hi, c0_lo,
9998 c1_hi, c1_lo,
9999 c2_hi, c2_lo,
10000 c3_hi, c3_lo);
10001 W[i + 1] = sum64_4_lo$1(
10002 c0_hi, c0_lo,
10003 c1_hi, c1_lo,
10004 c2_hi, c2_lo,
10005 c3_hi, c3_lo);
10006 }
10007};
10008
10009SHA512.prototype._update = function _update(msg, start) {
10010 this._prepareBlock(msg, start);
10011
10012 var W = this.W;
10013
10014 var ah = this.h[0];
10015 var al = this.h[1];
10016 var bh = this.h[2];
10017 var bl = this.h[3];
10018 var ch = this.h[4];
10019 var cl = this.h[5];
10020 var dh = this.h[6];
10021 var dl = this.h[7];
10022 var eh = this.h[8];
10023 var el = this.h[9];
10024 var fh = this.h[10];
10025 var fl = this.h[11];
10026 var gh = this.h[12];
10027 var gl = this.h[13];
10028 var hh = this.h[14];
10029 var hl = this.h[15];
10030
10031 minimalisticAssert(this.k.length === W.length);
10032 for (var i = 0; i < W.length; i += 2) {
10033 var c0_hi = hh;
10034 var c0_lo = hl;
10035 var c1_hi = s1_512_hi(eh, el);
10036 var c1_lo = s1_512_lo(eh, el);
10037 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
10038 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
10039 var c3_hi = this.k[i];
10040 var c3_lo = this.k[i + 1];
10041 var c4_hi = W[i];
10042 var c4_lo = W[i + 1];
10043
10044 var T1_hi = sum64_5_hi$1(
10045 c0_hi, c0_lo,
10046 c1_hi, c1_lo,
10047 c2_hi, c2_lo,
10048 c3_hi, c3_lo,
10049 c4_hi, c4_lo);
10050 var T1_lo = sum64_5_lo$1(
10051 c0_hi, c0_lo,
10052 c1_hi, c1_lo,
10053 c2_hi, c2_lo,
10054 c3_hi, c3_lo,
10055 c4_hi, c4_lo);
10056
10057 c0_hi = s0_512_hi(ah, al);
10058 c0_lo = s0_512_lo(ah, al);
10059 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
10060 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
10061
10062 var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo);
10063 var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo);
10064
10065 hh = gh;
10066 hl = gl;
10067
10068 gh = fh;
10069 gl = fl;
10070
10071 fh = eh;
10072 fl = el;
10073
10074 eh = sum64_hi$1(dh, dl, T1_hi, T1_lo);
10075 el = sum64_lo$1(dl, dl, T1_hi, T1_lo);
10076
10077 dh = ch;
10078 dl = cl;
10079
10080 ch = bh;
10081 cl = bl;
10082
10083 bh = ah;
10084 bl = al;
10085
10086 ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo);
10087 al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo);
10088 }
10089
10090 sum64$1(this.h, 0, ah, al);
10091 sum64$1(this.h, 2, bh, bl);
10092 sum64$1(this.h, 4, ch, cl);
10093 sum64$1(this.h, 6, dh, dl);
10094 sum64$1(this.h, 8, eh, el);
10095 sum64$1(this.h, 10, fh, fl);
10096 sum64$1(this.h, 12, gh, gl);
10097 sum64$1(this.h, 14, hh, hl);
10098};
10099
10100SHA512.prototype._digest = function digest(enc) {
10101 if (enc === 'hex')
10102 return utils.toHex32(this.h, 'big');
10103 else
10104 return utils.split32(this.h, 'big');
10105};
10106
10107function ch64_hi(xh, xl, yh, yl, zh) {
10108 var r = (xh & yh) ^ ((~xh) & zh);
10109 if (r < 0)
10110 r += 0x100000000;
10111 return r;
10112}
10113
10114function ch64_lo(xh, xl, yh, yl, zh, zl) {
10115 var r = (xl & yl) ^ ((~xl) & zl);
10116 if (r < 0)
10117 r += 0x100000000;
10118 return r;
10119}
10120
10121function maj64_hi(xh, xl, yh, yl, zh) {
10122 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
10123 if (r < 0)
10124 r += 0x100000000;
10125 return r;
10126}
10127
10128function maj64_lo(xh, xl, yh, yl, zh, zl) {
10129 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
10130 if (r < 0)
10131 r += 0x100000000;
10132 return r;
10133}
10134
10135function s0_512_hi(xh, xl) {
10136 var c0_hi = rotr64_hi$1(xh, xl, 28);
10137 var c1_hi = rotr64_hi$1(xl, xh, 2); // 34
10138 var c2_hi = rotr64_hi$1(xl, xh, 7); // 39
10139
10140 var r = c0_hi ^ c1_hi ^ c2_hi;
10141 if (r < 0)
10142 r += 0x100000000;
10143 return r;
10144}
10145
10146function s0_512_lo(xh, xl) {
10147 var c0_lo = rotr64_lo$1(xh, xl, 28);
10148 var c1_lo = rotr64_lo$1(xl, xh, 2); // 34
10149 var c2_lo = rotr64_lo$1(xl, xh, 7); // 39
10150
10151 var r = c0_lo ^ c1_lo ^ c2_lo;
10152 if (r < 0)
10153 r += 0x100000000;
10154 return r;
10155}
10156
10157function s1_512_hi(xh, xl) {
10158 var c0_hi = rotr64_hi$1(xh, xl, 14);
10159 var c1_hi = rotr64_hi$1(xh, xl, 18);
10160 var c2_hi = rotr64_hi$1(xl, xh, 9); // 41
10161
10162 var r = c0_hi ^ c1_hi ^ c2_hi;
10163 if (r < 0)
10164 r += 0x100000000;
10165 return r;
10166}
10167
10168function s1_512_lo(xh, xl) {
10169 var c0_lo = rotr64_lo$1(xh, xl, 14);
10170 var c1_lo = rotr64_lo$1(xh, xl, 18);
10171 var c2_lo = rotr64_lo$1(xl, xh, 9); // 41
10172
10173 var r = c0_lo ^ c1_lo ^ c2_lo;
10174 if (r < 0)
10175 r += 0x100000000;
10176 return r;
10177}
10178
10179function g0_512_hi(xh, xl) {
10180 var c0_hi = rotr64_hi$1(xh, xl, 1);
10181 var c1_hi = rotr64_hi$1(xh, xl, 8);
10182 var c2_hi = shr64_hi$1(xh, xl, 7);
10183
10184 var r = c0_hi ^ c1_hi ^ c2_hi;
10185 if (r < 0)
10186 r += 0x100000000;
10187 return r;
10188}
10189
10190function g0_512_lo(xh, xl) {
10191 var c0_lo = rotr64_lo$1(xh, xl, 1);
10192 var c1_lo = rotr64_lo$1(xh, xl, 8);
10193 var c2_lo = shr64_lo$1(xh, xl, 7);
10194
10195 var r = c0_lo ^ c1_lo ^ c2_lo;
10196 if (r < 0)
10197 r += 0x100000000;
10198 return r;
10199}
10200
10201function g1_512_hi(xh, xl) {
10202 var c0_hi = rotr64_hi$1(xh, xl, 19);
10203 var c1_hi = rotr64_hi$1(xl, xh, 29); // 61
10204 var c2_hi = shr64_hi$1(xh, xl, 6);
10205
10206 var r = c0_hi ^ c1_hi ^ c2_hi;
10207 if (r < 0)
10208 r += 0x100000000;
10209 return r;
10210}
10211
10212function g1_512_lo(xh, xl) {
10213 var c0_lo = rotr64_lo$1(xh, xl, 19);
10214 var c1_lo = rotr64_lo$1(xl, xh, 29); // 61
10215 var c2_lo = shr64_lo$1(xh, xl, 6);
10216
10217 var r = c0_lo ^ c1_lo ^ c2_lo;
10218 if (r < 0)
10219 r += 0x100000000;
10220 return r;
10221}
10222
10223'use strict';
10224
10225var sha1 = _1;
10226var sha224 = _224;
10227var sha256 = _256;
10228var sha384 = _384;
10229var sha512 = _512;
10230
10231var sha = {
10232 sha1: sha1,
10233 sha224: sha224,
10234 sha256: sha256,
10235 sha384: sha384,
10236 sha512: sha512
10237};
10238
10239'use strict';
10240
10241
10242
10243
10244var rotl32$1 = utils.rotl32;
10245var sum32$2 = utils.sum32;
10246var sum32_3$1 = utils.sum32_3;
10247var sum32_4$2 = utils.sum32_4;
10248var BlockHash$3 = common.BlockHash;
10249
10250function RIPEMD160() {
10251 if (!(this instanceof RIPEMD160))
10252 return new RIPEMD160();
10253
10254 BlockHash$3.call(this);
10255
10256 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
10257 this.endian = 'little';
10258}
10259utils.inherits(RIPEMD160, BlockHash$3);
10260var ripemd160 = RIPEMD160;
10261
10262RIPEMD160.blockSize = 512;
10263RIPEMD160.outSize = 160;
10264RIPEMD160.hmacStrength = 192;
10265RIPEMD160.padLength = 64;
10266
10267RIPEMD160.prototype._update = function update(msg, start) {
10268 var A = this.h[0];
10269 var B = this.h[1];
10270 var C = this.h[2];
10271 var D = this.h[3];
10272 var E = this.h[4];
10273 var Ah = A;
10274 var Bh = B;
10275 var Ch = C;
10276 var Dh = D;
10277 var Eh = E;
10278 for (var j = 0; j < 80; j++) {
10279 var T = sum32$2(
10280 rotl32$1(
10281 sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)),
10282 s[j]),
10283 E);
10284 A = E;
10285 E = D;
10286 D = rotl32$1(C, 10);
10287 C = B;
10288 B = T;
10289 T = sum32$2(
10290 rotl32$1(
10291 sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
10292 sh[j]),
10293 Eh);
10294 Ah = Eh;
10295 Eh = Dh;
10296 Dh = rotl32$1(Ch, 10);
10297 Ch = Bh;
10298 Bh = T;
10299 }
10300 T = sum32_3$1(this.h[1], C, Dh);
10301 this.h[1] = sum32_3$1(this.h[2], D, Eh);
10302 this.h[2] = sum32_3$1(this.h[3], E, Ah);
10303 this.h[3] = sum32_3$1(this.h[4], A, Bh);
10304 this.h[4] = sum32_3$1(this.h[0], B, Ch);
10305 this.h[0] = T;
10306};
10307
10308RIPEMD160.prototype._digest = function digest(enc) {
10309 if (enc === 'hex')
10310 return utils.toHex32(this.h, 'little');
10311 else
10312 return utils.split32(this.h, 'little');
10313};
10314
10315function f(j, x, y, z) {
10316 if (j <= 15)
10317 return x ^ y ^ z;
10318 else if (j <= 31)
10319 return (x & y) | ((~x) & z);
10320 else if (j <= 47)
10321 return (x | (~y)) ^ z;
10322 else if (j <= 63)
10323 return (x & z) | (y & (~z));
10324 else
10325 return x ^ (y | (~z));
10326}
10327
10328function K(j) {
10329 if (j <= 15)
10330 return 0x00000000;
10331 else if (j <= 31)
10332 return 0x5a827999;
10333 else if (j <= 47)
10334 return 0x6ed9eba1;
10335 else if (j <= 63)
10336 return 0x8f1bbcdc;
10337 else
10338 return 0xa953fd4e;
10339}
10340
10341function Kh(j) {
10342 if (j <= 15)
10343 return 0x50a28be6;
10344 else if (j <= 31)
10345 return 0x5c4dd124;
10346 else if (j <= 47)
10347 return 0x6d703ef3;
10348 else if (j <= 63)
10349 return 0x7a6d76e9;
10350 else
10351 return 0x00000000;
10352}
10353
10354var r = [
10355 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
10356 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
10357 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
10358 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
10359 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
10360];
10361
10362var rh = [
10363 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
10364 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
10365 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
10366 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
10367 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
10368];
10369
10370var s = [
10371 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
10372 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
10373 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
10374 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
10375 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
10376];
10377
10378var sh = [
10379 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
10380 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
10381 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
10382 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
10383 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
10384];
10385
10386var ripemd = {
10387 ripemd160: ripemd160
10388};
10389
10390'use strict';
10391
10392
10393
10394
10395function Hmac(hash, key, enc) {
10396 if (!(this instanceof Hmac))
10397 return new Hmac(hash, key, enc);
10398 this.Hash = hash;
10399 this.blockSize = hash.blockSize / 8;
10400 this.outSize = hash.outSize / 8;
10401 this.inner = null;
10402 this.outer = null;
10403
10404 this._init(utils.toArray(key, enc));
10405}
10406var hmac = Hmac;
10407
10408Hmac.prototype._init = function init(key) {
10409 // Shorten key, if needed
10410 if (key.length > this.blockSize)
10411 key = new this.Hash().update(key).digest();
10412 minimalisticAssert(key.length <= this.blockSize);
10413
10414 // Add padding to key
10415 for (var i = key.length; i < this.blockSize; i++)
10416 key.push(0);
10417
10418 for (i = 0; i < key.length; i++)
10419 key[i] ^= 0x36;
10420 this.inner = new this.Hash().update(key);
10421
10422 // 0x36 ^ 0x5c = 0x6a
10423 for (i = 0; i < key.length; i++)
10424 key[i] ^= 0x6a;
10425 this.outer = new this.Hash().update(key);
10426};
10427
10428Hmac.prototype.update = function update(msg, enc) {
10429 this.inner.update(msg, enc);
10430 return this;
10431};
10432
10433Hmac.prototype.digest = function digest(enc) {
10434 this.outer.update(this.inner.digest());
10435 return this.outer.digest(enc);
10436};
10437
10438var hash_1 = createCommonjsModule(function (module, exports) {
10439var hash = exports;
10440
10441hash.utils = utils;
10442hash.common = common;
10443hash.sha = sha;
10444hash.ripemd = ripemd;
10445hash.hmac = hmac;
10446
10447// Proxy hash functions to the main object
10448hash.sha1 = hash.sha.sha1;
10449hash.sha256 = hash.sha.sha256;
10450hash.sha224 = hash.sha.sha224;
10451hash.sha384 = hash.sha.sha384;
10452hash.sha512 = hash.sha.sha512;
10453hash.ripemd160 = hash.ripemd.ripemd160;
10454});
10455var hash_2 = hash_1.hmac;
10456var hash_3 = hash_1.ripemd160;
10457var hash_4 = hash_1.sha256;
10458var hash_5 = hash_1.sha512;
10459
10460var _version = createCommonjsModule(function (module, exports) {
10461"use strict";
10462Object.defineProperty(exports, "__esModule", { value: true });
10463exports.version = "sha2/5.0.2";
10464
10465});
10466
10467var _version$1 = unwrapExports(_version);
10468var _version_1 = _version.version;
10469
10470var browser = createCommonjsModule(function (module, exports) {
10471"use strict";
10472var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
10473 if (mod && mod.__esModule) return mod;
10474 var result = {};
10475 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
10476 result["default"] = mod;
10477 return result;
10478};
10479Object.defineProperty(exports, "__esModule", { value: true });
10480var hash = __importStar(hash_1);
10481
10482
10483
10484var logger = new lib_esm.Logger(_version.version);
10485var SupportedAlgorithm;
10486(function (SupportedAlgorithm) {
10487 SupportedAlgorithm["sha256"] = "sha256";
10488 SupportedAlgorithm["sha512"] = "sha512";
10489})(SupportedAlgorithm = exports.SupportedAlgorithm || (exports.SupportedAlgorithm = {}));
10490;
10491function ripemd160(data) {
10492 return "0x" + (hash.ripemd160().update(lib_esm$1.arrayify(data)).digest("hex"));
10493}
10494exports.ripemd160 = ripemd160;
10495function sha256(data) {
10496 return "0x" + (hash.sha256().update(lib_esm$1.arrayify(data)).digest("hex"));
10497}
10498exports.sha256 = sha256;
10499function sha512(data) {
10500 return "0x" + (hash.sha512().update(lib_esm$1.arrayify(data)).digest("hex"));
10501}
10502exports.sha512 = sha512;
10503function computeHmac(algorithm, key, data) {
10504 if (!SupportedAlgorithm[algorithm]) {
10505 logger.throwError("unsupported algorithm " + algorithm, lib_esm.Logger.errors.UNSUPPORTED_OPERATION, {
10506 operation: "hmac",
10507 algorithm: algorithm
10508 });
10509 }
10510 return "0x" + hash.hmac(hash[algorithm], lib_esm$1.arrayify(key)).update(lib_esm$1.arrayify(data)).digest("hex");
10511}
10512exports.computeHmac = computeHmac;
10513
10514});
10515
10516var browser$1 = unwrapExports(browser);
10517var browser_1 = browser.SupportedAlgorithm;
10518var browser_2 = browser.ripemd160;
10519var browser_3 = browser.sha256;
10520var browser_4 = browser.sha512;
10521var browser_5 = browser.computeHmac;
10522
10523"use strict";
10524function pbkdf2(password, salt, iterations, keylen, hashAlgorithm) {
10525 password = arrayify(password);
10526 salt = arrayify(salt);
10527 let hLen;
10528 let l = 1;
10529 const DK = new Uint8Array(keylen);
10530 const block1 = new Uint8Array(salt.length + 4);
10531 block1.set(salt);
10532 //salt.copy(block1, 0, 0, salt.length)
10533 let r;
10534 let T;
10535 for (let i = 1; i <= l; i++) {
10536 //block1.writeUInt32BE(i, salt.length)
10537 block1[salt.length] = (i >> 24) & 0xff;
10538 block1[salt.length + 1] = (i >> 16) & 0xff;
10539 block1[salt.length + 2] = (i >> 8) & 0xff;
10540 block1[salt.length + 3] = i & 0xff;
10541 //let U = createHmac(password).update(block1).digest();
10542 let U = arrayify(browser_5(hashAlgorithm, password, block1));
10543 if (!hLen) {
10544 hLen = U.length;
10545 T = new Uint8Array(hLen);
10546 l = Math.ceil(keylen / hLen);
10547 r = keylen - (l - 1) * hLen;
10548 }
10549 //U.copy(T, 0, 0, hLen)
10550 T.set(U);
10551 for (let j = 1; j < iterations; j++) {
10552 //U = createHmac(password).update(U).digest();
10553 U = arrayify(browser_5(hashAlgorithm, password, U));
10554 for (let k = 0; k < hLen; k++)
10555 T[k] ^= U[k];
10556 }
10557 const destPos = (i - 1) * hLen;
10558 const len = (i === l ? r : hLen);
10559 //T.copy(DK, destPos, 0, len)
10560 DK.set(arrayify(T).slice(0, len), destPos);
10561 }
10562 return hexlify(DK);
10563}
10564
10565var version$c = "6.5.3";
10566var _package = {
10567 version: version$c
10568};
10569
10570var _package$1 = /*#__PURE__*/Object.freeze({
10571 version: version$c,
10572 'default': _package
10573});
10574
10575var bn$1 = createCommonjsModule(function (module) {
10576(function (module, exports) {
10577 'use strict';
10578
10579 // Utils
10580 function assert (val, msg) {
10581 if (!val) throw new Error(msg || 'Assertion failed');
10582 }
10583
10584 // Could use `inherits` module, but don't want to move from single file
10585 // architecture yet.
10586 function inherits (ctor, superCtor) {
10587 ctor.super_ = superCtor;
10588 var TempCtor = function () {};
10589 TempCtor.prototype = superCtor.prototype;
10590 ctor.prototype = new TempCtor();
10591 ctor.prototype.constructor = ctor;
10592 }
10593
10594 // BN
10595
10596 function BN (number, base, endian) {
10597 if (BN.isBN(number)) {
10598 return number;
10599 }
10600
10601 this.negative = 0;
10602 this.words = null;
10603 this.length = 0;
10604
10605 // Reduction context
10606 this.red = null;
10607
10608 if (number !== null) {
10609 if (base === 'le' || base === 'be') {
10610 endian = base;
10611 base = 10;
10612 }
10613
10614 this._init(number || 0, base || 10, endian || 'be');
10615 }
10616 }
10617 if (typeof module === 'object') {
10618 module.exports = BN;
10619 } else {
10620 exports.BN = BN;
10621 }
10622
10623 BN.BN = BN;
10624 BN.wordSize = 26;
10625
10626 var Buffer;
10627 try {
10628 Buffer = require$$0.Buffer;
10629 } catch (e) {
10630 }
10631
10632 BN.isBN = function isBN (num) {
10633 if (num instanceof BN) {
10634 return true;
10635 }
10636
10637 return num !== null && typeof num === 'object' &&
10638 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
10639 };
10640
10641 BN.max = function max (left, right) {
10642 if (left.cmp(right) > 0) return left;
10643 return right;
10644 };
10645
10646 BN.min = function min (left, right) {
10647 if (left.cmp(right) < 0) return left;
10648 return right;
10649 };
10650
10651 BN.prototype._init = function init (number, base, endian) {
10652 if (typeof number === 'number') {
10653 return this._initNumber(number, base, endian);
10654 }
10655
10656 if (typeof number === 'object') {
10657 return this._initArray(number, base, endian);
10658 }
10659
10660 if (base === 'hex') {
10661 base = 16;
10662 }
10663 assert(base === (base | 0) && base >= 2 && base <= 36);
10664
10665 number = number.toString().replace(/\s+/g, '');
10666 var start = 0;
10667 if (number[0] === '-') {
10668 start++;
10669 }
10670
10671 if (base === 16) {
10672 this._parseHex(number, start);
10673 } else {
10674 this._parseBase(number, base, start);
10675 }
10676
10677 if (number[0] === '-') {
10678 this.negative = 1;
10679 }
10680
10681 this.strip();
10682
10683 if (endian !== 'le') return;
10684
10685 this._initArray(this.toArray(), base, endian);
10686 };
10687
10688 BN.prototype._initNumber = function _initNumber (number, base, endian) {
10689 if (number < 0) {
10690 this.negative = 1;
10691 number = -number;
10692 }
10693 if (number < 0x4000000) {
10694 this.words = [ number & 0x3ffffff ];
10695 this.length = 1;
10696 } else if (number < 0x10000000000000) {
10697 this.words = [
10698 number & 0x3ffffff,
10699 (number / 0x4000000) & 0x3ffffff
10700 ];
10701 this.length = 2;
10702 } else {
10703 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
10704 this.words = [
10705 number & 0x3ffffff,
10706 (number / 0x4000000) & 0x3ffffff,
10707 1
10708 ];
10709 this.length = 3;
10710 }
10711
10712 if (endian !== 'le') return;
10713
10714 // Reverse the bytes
10715 this._initArray(this.toArray(), base, endian);
10716 };
10717
10718 BN.prototype._initArray = function _initArray (number, base, endian) {
10719 // Perhaps a Uint8Array
10720 assert(typeof number.length === 'number');
10721 if (number.length <= 0) {
10722 this.words = [ 0 ];
10723 this.length = 1;
10724 return this;
10725 }
10726
10727 this.length = Math.ceil(number.length / 3);
10728 this.words = new Array(this.length);
10729 for (var i = 0; i < this.length; i++) {
10730 this.words[i] = 0;
10731 }
10732
10733 var j, w;
10734 var off = 0;
10735 if (endian === 'be') {
10736 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
10737 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
10738 this.words[j] |= (w << off) & 0x3ffffff;
10739 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
10740 off += 24;
10741 if (off >= 26) {
10742 off -= 26;
10743 j++;
10744 }
10745 }
10746 } else if (endian === 'le') {
10747 for (i = 0, j = 0; i < number.length; i += 3) {
10748 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
10749 this.words[j] |= (w << off) & 0x3ffffff;
10750 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
10751 off += 24;
10752 if (off >= 26) {
10753 off -= 26;
10754 j++;
10755 }
10756 }
10757 }
10758 return this.strip();
10759 };
10760
10761 function parseHex (str, start, end) {
10762 var r = 0;
10763 var len = Math.min(str.length, end);
10764 for (var i = start; i < len; i++) {
10765 var c = str.charCodeAt(i) - 48;
10766
10767 r <<= 4;
10768
10769 // 'a' - 'f'
10770 if (c >= 49 && c <= 54) {
10771 r |= c - 49 + 0xa;
10772
10773 // 'A' - 'F'
10774 } else if (c >= 17 && c <= 22) {
10775 r |= c - 17 + 0xa;
10776
10777 // '0' - '9'
10778 } else {
10779 r |= c & 0xf;
10780 }
10781 }
10782 return r;
10783 }
10784
10785 BN.prototype._parseHex = function _parseHex (number, start) {
10786 // Create possibly bigger array to ensure that it fits the number
10787 this.length = Math.ceil((number.length - start) / 6);
10788 this.words = new Array(this.length);
10789 for (var i = 0; i < this.length; i++) {
10790 this.words[i] = 0;
10791 }
10792
10793 var j, w;
10794 // Scan 24-bit chunks and add them to the number
10795 var off = 0;
10796 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
10797 w = parseHex(number, i, i + 6);
10798 this.words[j] |= (w << off) & 0x3ffffff;
10799 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
10800 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
10801 off += 24;
10802 if (off >= 26) {
10803 off -= 26;
10804 j++;
10805 }
10806 }
10807 if (i + 6 !== start) {
10808 w = parseHex(number, start, i + 6);
10809 this.words[j] |= (w << off) & 0x3ffffff;
10810 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
10811 }
10812 this.strip();
10813 };
10814
10815 function parseBase (str, start, end, mul) {
10816 var r = 0;
10817 var len = Math.min(str.length, end);
10818 for (var i = start; i < len; i++) {
10819 var c = str.charCodeAt(i) - 48;
10820
10821 r *= mul;
10822
10823 // 'a'
10824 if (c >= 49) {
10825 r += c - 49 + 0xa;
10826
10827 // 'A'
10828 } else if (c >= 17) {
10829 r += c - 17 + 0xa;
10830
10831 // '0' - '9'
10832 } else {
10833 r += c;
10834 }
10835 }
10836 return r;
10837 }
10838
10839 BN.prototype._parseBase = function _parseBase (number, base, start) {
10840 // Initialize as zero
10841 this.words = [ 0 ];
10842 this.length = 1;
10843
10844 // Find length of limb in base
10845 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
10846 limbLen++;
10847 }
10848 limbLen--;
10849 limbPow = (limbPow / base) | 0;
10850
10851 var total = number.length - start;
10852 var mod = total % limbLen;
10853 var end = Math.min(total, total - mod) + start;
10854
10855 var word = 0;
10856 for (var i = start; i < end; i += limbLen) {
10857 word = parseBase(number, i, i + limbLen, base);
10858
10859 this.imuln(limbPow);
10860 if (this.words[0] + word < 0x4000000) {
10861 this.words[0] += word;
10862 } else {
10863 this._iaddn(word);
10864 }
10865 }
10866
10867 if (mod !== 0) {
10868 var pow = 1;
10869 word = parseBase(number, i, number.length, base);
10870
10871 for (i = 0; i < mod; i++) {
10872 pow *= base;
10873 }
10874
10875 this.imuln(pow);
10876 if (this.words[0] + word < 0x4000000) {
10877 this.words[0] += word;
10878 } else {
10879 this._iaddn(word);
10880 }
10881 }
10882 };
10883
10884 BN.prototype.copy = function copy (dest) {
10885 dest.words = new Array(this.length);
10886 for (var i = 0; i < this.length; i++) {
10887 dest.words[i] = this.words[i];
10888 }
10889 dest.length = this.length;
10890 dest.negative = this.negative;
10891 dest.red = this.red;
10892 };
10893
10894 BN.prototype.clone = function clone () {
10895 var r = new BN(null);
10896 this.copy(r);
10897 return r;
10898 };
10899
10900 BN.prototype._expand = function _expand (size) {
10901 while (this.length < size) {
10902 this.words[this.length++] = 0;
10903 }
10904 return this;
10905 };
10906
10907 // Remove leading `0` from `this`
10908 BN.prototype.strip = function strip () {
10909 while (this.length > 1 && this.words[this.length - 1] === 0) {
10910 this.length--;
10911 }
10912 return this._normSign();
10913 };
10914
10915 BN.prototype._normSign = function _normSign () {
10916 // -0 = 0
10917 if (this.length === 1 && this.words[0] === 0) {
10918 this.negative = 0;
10919 }
10920 return this;
10921 };
10922
10923 BN.prototype.inspect = function inspect () {
10924 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
10925 };
10926
10927 /*
10928
10929 var zeros = [];
10930 var groupSizes = [];
10931 var groupBases = [];
10932
10933 var s = '';
10934 var i = -1;
10935 while (++i < BN.wordSize) {
10936 zeros[i] = s;
10937 s += '0';
10938 }
10939 groupSizes[0] = 0;
10940 groupSizes[1] = 0;
10941 groupBases[0] = 0;
10942 groupBases[1] = 0;
10943 var base = 2 - 1;
10944 while (++base < 36 + 1) {
10945 var groupSize = 0;
10946 var groupBase = 1;
10947 while (groupBase < (1 << BN.wordSize) / base) {
10948 groupBase *= base;
10949 groupSize += 1;
10950 }
10951 groupSizes[base] = groupSize;
10952 groupBases[base] = groupBase;
10953 }
10954
10955 */
10956
10957 var zeros = [
10958 '',
10959 '0',
10960 '00',
10961 '000',
10962 '0000',
10963 '00000',
10964 '000000',
10965 '0000000',
10966 '00000000',
10967 '000000000',
10968 '0000000000',
10969 '00000000000',
10970 '000000000000',
10971 '0000000000000',
10972 '00000000000000',
10973 '000000000000000',
10974 '0000000000000000',
10975 '00000000000000000',
10976 '000000000000000000',
10977 '0000000000000000000',
10978 '00000000000000000000',
10979 '000000000000000000000',
10980 '0000000000000000000000',
10981 '00000000000000000000000',
10982 '000000000000000000000000',
10983 '0000000000000000000000000'
10984 ];
10985
10986 var groupSizes = [
10987 0, 0,
10988 25, 16, 12, 11, 10, 9, 8,
10989 8, 7, 7, 7, 7, 6, 6,
10990 6, 6, 6, 6, 6, 5, 5,
10991 5, 5, 5, 5, 5, 5, 5,
10992 5, 5, 5, 5, 5, 5, 5
10993 ];
10994
10995 var groupBases = [
10996 0, 0,
10997 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
10998 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
10999 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
11000 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
11001 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
11002 ];
11003
11004 BN.prototype.toString = function toString (base, padding) {
11005 base = base || 10;
11006 padding = padding | 0 || 1;
11007
11008 var out;
11009 if (base === 16 || base === 'hex') {
11010 out = '';
11011 var off = 0;
11012 var carry = 0;
11013 for (var i = 0; i < this.length; i++) {
11014 var w = this.words[i];
11015 var word = (((w << off) | carry) & 0xffffff).toString(16);
11016 carry = (w >>> (24 - off)) & 0xffffff;
11017 if (carry !== 0 || i !== this.length - 1) {
11018 out = zeros[6 - word.length] + word + out;
11019 } else {
11020 out = word + out;
11021 }
11022 off += 2;
11023 if (off >= 26) {
11024 off -= 26;
11025 i--;
11026 }
11027 }
11028 if (carry !== 0) {
11029 out = carry.toString(16) + out;
11030 }
11031 while (out.length % padding !== 0) {
11032 out = '0' + out;
11033 }
11034 if (this.negative !== 0) {
11035 out = '-' + out;
11036 }
11037 return out;
11038 }
11039
11040 if (base === (base | 0) && base >= 2 && base <= 36) {
11041 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
11042 var groupSize = groupSizes[base];
11043 // var groupBase = Math.pow(base, groupSize);
11044 var groupBase = groupBases[base];
11045 out = '';
11046 var c = this.clone();
11047 c.negative = 0;
11048 while (!c.isZero()) {
11049 var r = c.modn(groupBase).toString(base);
11050 c = c.idivn(groupBase);
11051
11052 if (!c.isZero()) {
11053 out = zeros[groupSize - r.length] + r + out;
11054 } else {
11055 out = r + out;
11056 }
11057 }
11058 if (this.isZero()) {
11059 out = '0' + out;
11060 }
11061 while (out.length % padding !== 0) {
11062 out = '0' + out;
11063 }
11064 if (this.negative !== 0) {
11065 out = '-' + out;
11066 }
11067 return out;
11068 }
11069
11070 assert(false, 'Base should be between 2 and 36');
11071 };
11072
11073 BN.prototype.toNumber = function toNumber () {
11074 var ret = this.words[0];
11075 if (this.length === 2) {
11076 ret += this.words[1] * 0x4000000;
11077 } else if (this.length === 3 && this.words[2] === 0x01) {
11078 // NOTE: at this stage it is known that the top bit is set
11079 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
11080 } else if (this.length > 2) {
11081 assert(false, 'Number can only safely store up to 53 bits');
11082 }
11083 return (this.negative !== 0) ? -ret : ret;
11084 };
11085
11086 BN.prototype.toJSON = function toJSON () {
11087 return this.toString(16);
11088 };
11089
11090 BN.prototype.toBuffer = function toBuffer (endian, length) {
11091 assert(typeof Buffer !== 'undefined');
11092 return this.toArrayLike(Buffer, endian, length);
11093 };
11094
11095 BN.prototype.toArray = function toArray (endian, length) {
11096 return this.toArrayLike(Array, endian, length);
11097 };
11098
11099 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
11100 var byteLength = this.byteLength();
11101 var reqLength = length || Math.max(1, byteLength);
11102 assert(byteLength <= reqLength, 'byte array longer than desired length');
11103 assert(reqLength > 0, 'Requested array length <= 0');
11104
11105 this.strip();
11106 var littleEndian = endian === 'le';
11107 var res = new ArrayType(reqLength);
11108
11109 var b, i;
11110 var q = this.clone();
11111 if (!littleEndian) {
11112 // Assume big-endian
11113 for (i = 0; i < reqLength - byteLength; i++) {
11114 res[i] = 0;
11115 }
11116
11117 for (i = 0; !q.isZero(); i++) {
11118 b = q.andln(0xff);
11119 q.iushrn(8);
11120
11121 res[reqLength - i - 1] = b;
11122 }
11123 } else {
11124 for (i = 0; !q.isZero(); i++) {
11125 b = q.andln(0xff);
11126 q.iushrn(8);
11127
11128 res[i] = b;
11129 }
11130
11131 for (; i < reqLength; i++) {
11132 res[i] = 0;
11133 }
11134 }
11135
11136 return res;
11137 };
11138
11139 if (Math.clz32) {
11140 BN.prototype._countBits = function _countBits (w) {
11141 return 32 - Math.clz32(w);
11142 };
11143 } else {
11144 BN.prototype._countBits = function _countBits (w) {
11145 var t = w;
11146 var r = 0;
11147 if (t >= 0x1000) {
11148 r += 13;
11149 t >>>= 13;
11150 }
11151 if (t >= 0x40) {
11152 r += 7;
11153 t >>>= 7;
11154 }
11155 if (t >= 0x8) {
11156 r += 4;
11157 t >>>= 4;
11158 }
11159 if (t >= 0x02) {
11160 r += 2;
11161 t >>>= 2;
11162 }
11163 return r + t;
11164 };
11165 }
11166
11167 BN.prototype._zeroBits = function _zeroBits (w) {
11168 // Short-cut
11169 if (w === 0) return 26;
11170
11171 var t = w;
11172 var r = 0;
11173 if ((t & 0x1fff) === 0) {
11174 r += 13;
11175 t >>>= 13;
11176 }
11177 if ((t & 0x7f) === 0) {
11178 r += 7;
11179 t >>>= 7;
11180 }
11181 if ((t & 0xf) === 0) {
11182 r += 4;
11183 t >>>= 4;
11184 }
11185 if ((t & 0x3) === 0) {
11186 r += 2;
11187 t >>>= 2;
11188 }
11189 if ((t & 0x1) === 0) {
11190 r++;
11191 }
11192 return r;
11193 };
11194
11195 // Return number of used bits in a BN
11196 BN.prototype.bitLength = function bitLength () {
11197 var w = this.words[this.length - 1];
11198 var hi = this._countBits(w);
11199 return (this.length - 1) * 26 + hi;
11200 };
11201
11202 function toBitArray (num) {
11203 var w = new Array(num.bitLength());
11204
11205 for (var bit = 0; bit < w.length; bit++) {
11206 var off = (bit / 26) | 0;
11207 var wbit = bit % 26;
11208
11209 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
11210 }
11211
11212 return w;
11213 }
11214
11215 // Number of trailing zero bits
11216 BN.prototype.zeroBits = function zeroBits () {
11217 if (this.isZero()) return 0;
11218
11219 var r = 0;
11220 for (var i = 0; i < this.length; i++) {
11221 var b = this._zeroBits(this.words[i]);
11222 r += b;
11223 if (b !== 26) break;
11224 }
11225 return r;
11226 };
11227
11228 BN.prototype.byteLength = function byteLength () {
11229 return Math.ceil(this.bitLength() / 8);
11230 };
11231
11232 BN.prototype.toTwos = function toTwos (width) {
11233 if (this.negative !== 0) {
11234 return this.abs().inotn(width).iaddn(1);
11235 }
11236 return this.clone();
11237 };
11238
11239 BN.prototype.fromTwos = function fromTwos (width) {
11240 if (this.testn(width - 1)) {
11241 return this.notn(width).iaddn(1).ineg();
11242 }
11243 return this.clone();
11244 };
11245
11246 BN.prototype.isNeg = function isNeg () {
11247 return this.negative !== 0;
11248 };
11249
11250 // Return negative clone of `this`
11251 BN.prototype.neg = function neg () {
11252 return this.clone().ineg();
11253 };
11254
11255 BN.prototype.ineg = function ineg () {
11256 if (!this.isZero()) {
11257 this.negative ^= 1;
11258 }
11259
11260 return this;
11261 };
11262
11263 // Or `num` with `this` in-place
11264 BN.prototype.iuor = function iuor (num) {
11265 while (this.length < num.length) {
11266 this.words[this.length++] = 0;
11267 }
11268
11269 for (var i = 0; i < num.length; i++) {
11270 this.words[i] = this.words[i] | num.words[i];
11271 }
11272
11273 return this.strip();
11274 };
11275
11276 BN.prototype.ior = function ior (num) {
11277 assert((this.negative | num.negative) === 0);
11278 return this.iuor(num);
11279 };
11280
11281 // Or `num` with `this`
11282 BN.prototype.or = function or (num) {
11283 if (this.length > num.length) return this.clone().ior(num);
11284 return num.clone().ior(this);
11285 };
11286
11287 BN.prototype.uor = function uor (num) {
11288 if (this.length > num.length) return this.clone().iuor(num);
11289 return num.clone().iuor(this);
11290 };
11291
11292 // And `num` with `this` in-place
11293 BN.prototype.iuand = function iuand (num) {
11294 // b = min-length(num, this)
11295 var b;
11296 if (this.length > num.length) {
11297 b = num;
11298 } else {
11299 b = this;
11300 }
11301
11302 for (var i = 0; i < b.length; i++) {
11303 this.words[i] = this.words[i] & num.words[i];
11304 }
11305
11306 this.length = b.length;
11307
11308 return this.strip();
11309 };
11310
11311 BN.prototype.iand = function iand (num) {
11312 assert((this.negative | num.negative) === 0);
11313 return this.iuand(num);
11314 };
11315
11316 // And `num` with `this`
11317 BN.prototype.and = function and (num) {
11318 if (this.length > num.length) return this.clone().iand(num);
11319 return num.clone().iand(this);
11320 };
11321
11322 BN.prototype.uand = function uand (num) {
11323 if (this.length > num.length) return this.clone().iuand(num);
11324 return num.clone().iuand(this);
11325 };
11326
11327 // Xor `num` with `this` in-place
11328 BN.prototype.iuxor = function iuxor (num) {
11329 // a.length > b.length
11330 var a;
11331 var b;
11332 if (this.length > num.length) {
11333 a = this;
11334 b = num;
11335 } else {
11336 a = num;
11337 b = this;
11338 }
11339
11340 for (var i = 0; i < b.length; i++) {
11341 this.words[i] = a.words[i] ^ b.words[i];
11342 }
11343
11344 if (this !== a) {
11345 for (; i < a.length; i++) {
11346 this.words[i] = a.words[i];
11347 }
11348 }
11349
11350 this.length = a.length;
11351
11352 return this.strip();
11353 };
11354
11355 BN.prototype.ixor = function ixor (num) {
11356 assert((this.negative | num.negative) === 0);
11357 return this.iuxor(num);
11358 };
11359
11360 // Xor `num` with `this`
11361 BN.prototype.xor = function xor (num) {
11362 if (this.length > num.length) return this.clone().ixor(num);
11363 return num.clone().ixor(this);
11364 };
11365
11366 BN.prototype.uxor = function uxor (num) {
11367 if (this.length > num.length) return this.clone().iuxor(num);
11368 return num.clone().iuxor(this);
11369 };
11370
11371 // Not ``this`` with ``width`` bitwidth
11372 BN.prototype.inotn = function inotn (width) {
11373 assert(typeof width === 'number' && width >= 0);
11374
11375 var bytesNeeded = Math.ceil(width / 26) | 0;
11376 var bitsLeft = width % 26;
11377
11378 // Extend the buffer with leading zeroes
11379 this._expand(bytesNeeded);
11380
11381 if (bitsLeft > 0) {
11382 bytesNeeded--;
11383 }
11384
11385 // Handle complete words
11386 for (var i = 0; i < bytesNeeded; i++) {
11387 this.words[i] = ~this.words[i] & 0x3ffffff;
11388 }
11389
11390 // Handle the residue
11391 if (bitsLeft > 0) {
11392 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
11393 }
11394
11395 // And remove leading zeroes
11396 return this.strip();
11397 };
11398
11399 BN.prototype.notn = function notn (width) {
11400 return this.clone().inotn(width);
11401 };
11402
11403 // Set `bit` of `this`
11404 BN.prototype.setn = function setn (bit, val) {
11405 assert(typeof bit === 'number' && bit >= 0);
11406
11407 var off = (bit / 26) | 0;
11408 var wbit = bit % 26;
11409
11410 this._expand(off + 1);
11411
11412 if (val) {
11413 this.words[off] = this.words[off] | (1 << wbit);
11414 } else {
11415 this.words[off] = this.words[off] & ~(1 << wbit);
11416 }
11417
11418 return this.strip();
11419 };
11420
11421 // Add `num` to `this` in-place
11422 BN.prototype.iadd = function iadd (num) {
11423 var r;
11424
11425 // negative + positive
11426 if (this.negative !== 0 && num.negative === 0) {
11427 this.negative = 0;
11428 r = this.isub(num);
11429 this.negative ^= 1;
11430 return this._normSign();
11431
11432 // positive + negative
11433 } else if (this.negative === 0 && num.negative !== 0) {
11434 num.negative = 0;
11435 r = this.isub(num);
11436 num.negative = 1;
11437 return r._normSign();
11438 }
11439
11440 // a.length > b.length
11441 var a, b;
11442 if (this.length > num.length) {
11443 a = this;
11444 b = num;
11445 } else {
11446 a = num;
11447 b = this;
11448 }
11449
11450 var carry = 0;
11451 for (var i = 0; i < b.length; i++) {
11452 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
11453 this.words[i] = r & 0x3ffffff;
11454 carry = r >>> 26;
11455 }
11456 for (; carry !== 0 && i < a.length; i++) {
11457 r = (a.words[i] | 0) + carry;
11458 this.words[i] = r & 0x3ffffff;
11459 carry = r >>> 26;
11460 }
11461
11462 this.length = a.length;
11463 if (carry !== 0) {
11464 this.words[this.length] = carry;
11465 this.length++;
11466 // Copy the rest of the words
11467 } else if (a !== this) {
11468 for (; i < a.length; i++) {
11469 this.words[i] = a.words[i];
11470 }
11471 }
11472
11473 return this;
11474 };
11475
11476 // Add `num` to `this`
11477 BN.prototype.add = function add (num) {
11478 var res;
11479 if (num.negative !== 0 && this.negative === 0) {
11480 num.negative = 0;
11481 res = this.sub(num);
11482 num.negative ^= 1;
11483 return res;
11484 } else if (num.negative === 0 && this.negative !== 0) {
11485 this.negative = 0;
11486 res = num.sub(this);
11487 this.negative = 1;
11488 return res;
11489 }
11490
11491 if (this.length > num.length) return this.clone().iadd(num);
11492
11493 return num.clone().iadd(this);
11494 };
11495
11496 // Subtract `num` from `this` in-place
11497 BN.prototype.isub = function isub (num) {
11498 // this - (-num) = this + num
11499 if (num.negative !== 0) {
11500 num.negative = 0;
11501 var r = this.iadd(num);
11502 num.negative = 1;
11503 return r._normSign();
11504
11505 // -this - num = -(this + num)
11506 } else if (this.negative !== 0) {
11507 this.negative = 0;
11508 this.iadd(num);
11509 this.negative = 1;
11510 return this._normSign();
11511 }
11512
11513 // At this point both numbers are positive
11514 var cmp = this.cmp(num);
11515
11516 // Optimization - zeroify
11517 if (cmp === 0) {
11518 this.negative = 0;
11519 this.length = 1;
11520 this.words[0] = 0;
11521 return this;
11522 }
11523
11524 // a > b
11525 var a, b;
11526 if (cmp > 0) {
11527 a = this;
11528 b = num;
11529 } else {
11530 a = num;
11531 b = this;
11532 }
11533
11534 var carry = 0;
11535 for (var i = 0; i < b.length; i++) {
11536 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
11537 carry = r >> 26;
11538 this.words[i] = r & 0x3ffffff;
11539 }
11540 for (; carry !== 0 && i < a.length; i++) {
11541 r = (a.words[i] | 0) + carry;
11542 carry = r >> 26;
11543 this.words[i] = r & 0x3ffffff;
11544 }
11545
11546 // Copy rest of the words
11547 if (carry === 0 && i < a.length && a !== this) {
11548 for (; i < a.length; i++) {
11549 this.words[i] = a.words[i];
11550 }
11551 }
11552
11553 this.length = Math.max(this.length, i);
11554
11555 if (a !== this) {
11556 this.negative = 1;
11557 }
11558
11559 return this.strip();
11560 };
11561
11562 // Subtract `num` from `this`
11563 BN.prototype.sub = function sub (num) {
11564 return this.clone().isub(num);
11565 };
11566
11567 function smallMulTo (self, num, out) {
11568 out.negative = num.negative ^ self.negative;
11569 var len = (self.length + num.length) | 0;
11570 out.length = len;
11571 len = (len - 1) | 0;
11572
11573 // Peel one iteration (compiler can't do it, because of code complexity)
11574 var a = self.words[0] | 0;
11575 var b = num.words[0] | 0;
11576 var r = a * b;
11577
11578 var lo = r & 0x3ffffff;
11579 var carry = (r / 0x4000000) | 0;
11580 out.words[0] = lo;
11581
11582 for (var k = 1; k < len; k++) {
11583 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
11584 // note that ncarry could be >= 0x3ffffff
11585 var ncarry = carry >>> 26;
11586 var rword = carry & 0x3ffffff;
11587 var maxJ = Math.min(k, num.length - 1);
11588 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
11589 var i = (k - j) | 0;
11590 a = self.words[i] | 0;
11591 b = num.words[j] | 0;
11592 r = a * b + rword;
11593 ncarry += (r / 0x4000000) | 0;
11594 rword = r & 0x3ffffff;
11595 }
11596 out.words[k] = rword | 0;
11597 carry = ncarry | 0;
11598 }
11599 if (carry !== 0) {
11600 out.words[k] = carry | 0;
11601 } else {
11602 out.length--;
11603 }
11604
11605 return out.strip();
11606 }
11607
11608 // TODO(indutny): it may be reasonable to omit it for users who don't need
11609 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
11610 // multiplication (like elliptic secp256k1).
11611 var comb10MulTo = function comb10MulTo (self, num, out) {
11612 var a = self.words;
11613 var b = num.words;
11614 var o = out.words;
11615 var c = 0;
11616 var lo;
11617 var mid;
11618 var hi;
11619 var a0 = a[0] | 0;
11620 var al0 = a0 & 0x1fff;
11621 var ah0 = a0 >>> 13;
11622 var a1 = a[1] | 0;
11623 var al1 = a1 & 0x1fff;
11624 var ah1 = a1 >>> 13;
11625 var a2 = a[2] | 0;
11626 var al2 = a2 & 0x1fff;
11627 var ah2 = a2 >>> 13;
11628 var a3 = a[3] | 0;
11629 var al3 = a3 & 0x1fff;
11630 var ah3 = a3 >>> 13;
11631 var a4 = a[4] | 0;
11632 var al4 = a4 & 0x1fff;
11633 var ah4 = a4 >>> 13;
11634 var a5 = a[5] | 0;
11635 var al5 = a5 & 0x1fff;
11636 var ah5 = a5 >>> 13;
11637 var a6 = a[6] | 0;
11638 var al6 = a6 & 0x1fff;
11639 var ah6 = a6 >>> 13;
11640 var a7 = a[7] | 0;
11641 var al7 = a7 & 0x1fff;
11642 var ah7 = a7 >>> 13;
11643 var a8 = a[8] | 0;
11644 var al8 = a8 & 0x1fff;
11645 var ah8 = a8 >>> 13;
11646 var a9 = a[9] | 0;
11647 var al9 = a9 & 0x1fff;
11648 var ah9 = a9 >>> 13;
11649 var b0 = b[0] | 0;
11650 var bl0 = b0 & 0x1fff;
11651 var bh0 = b0 >>> 13;
11652 var b1 = b[1] | 0;
11653 var bl1 = b1 & 0x1fff;
11654 var bh1 = b1 >>> 13;
11655 var b2 = b[2] | 0;
11656 var bl2 = b2 & 0x1fff;
11657 var bh2 = b2 >>> 13;
11658 var b3 = b[3] | 0;
11659 var bl3 = b3 & 0x1fff;
11660 var bh3 = b3 >>> 13;
11661 var b4 = b[4] | 0;
11662 var bl4 = b4 & 0x1fff;
11663 var bh4 = b4 >>> 13;
11664 var b5 = b[5] | 0;
11665 var bl5 = b5 & 0x1fff;
11666 var bh5 = b5 >>> 13;
11667 var b6 = b[6] | 0;
11668 var bl6 = b6 & 0x1fff;
11669 var bh6 = b6 >>> 13;
11670 var b7 = b[7] | 0;
11671 var bl7 = b7 & 0x1fff;
11672 var bh7 = b7 >>> 13;
11673 var b8 = b[8] | 0;
11674 var bl8 = b8 & 0x1fff;
11675 var bh8 = b8 >>> 13;
11676 var b9 = b[9] | 0;
11677 var bl9 = b9 & 0x1fff;
11678 var bh9 = b9 >>> 13;
11679
11680 out.negative = self.negative ^ num.negative;
11681 out.length = 19;
11682 /* k = 0 */
11683 lo = Math.imul(al0, bl0);
11684 mid = Math.imul(al0, bh0);
11685 mid = (mid + Math.imul(ah0, bl0)) | 0;
11686 hi = Math.imul(ah0, bh0);
11687 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11688 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
11689 w0 &= 0x3ffffff;
11690 /* k = 1 */
11691 lo = Math.imul(al1, bl0);
11692 mid = Math.imul(al1, bh0);
11693 mid = (mid + Math.imul(ah1, bl0)) | 0;
11694 hi = Math.imul(ah1, bh0);
11695 lo = (lo + Math.imul(al0, bl1)) | 0;
11696 mid = (mid + Math.imul(al0, bh1)) | 0;
11697 mid = (mid + Math.imul(ah0, bl1)) | 0;
11698 hi = (hi + Math.imul(ah0, bh1)) | 0;
11699 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11700 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
11701 w1 &= 0x3ffffff;
11702 /* k = 2 */
11703 lo = Math.imul(al2, bl0);
11704 mid = Math.imul(al2, bh0);
11705 mid = (mid + Math.imul(ah2, bl0)) | 0;
11706 hi = Math.imul(ah2, bh0);
11707 lo = (lo + Math.imul(al1, bl1)) | 0;
11708 mid = (mid + Math.imul(al1, bh1)) | 0;
11709 mid = (mid + Math.imul(ah1, bl1)) | 0;
11710 hi = (hi + Math.imul(ah1, bh1)) | 0;
11711 lo = (lo + Math.imul(al0, bl2)) | 0;
11712 mid = (mid + Math.imul(al0, bh2)) | 0;
11713 mid = (mid + Math.imul(ah0, bl2)) | 0;
11714 hi = (hi + Math.imul(ah0, bh2)) | 0;
11715 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11716 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
11717 w2 &= 0x3ffffff;
11718 /* k = 3 */
11719 lo = Math.imul(al3, bl0);
11720 mid = Math.imul(al3, bh0);
11721 mid = (mid + Math.imul(ah3, bl0)) | 0;
11722 hi = Math.imul(ah3, bh0);
11723 lo = (lo + Math.imul(al2, bl1)) | 0;
11724 mid = (mid + Math.imul(al2, bh1)) | 0;
11725 mid = (mid + Math.imul(ah2, bl1)) | 0;
11726 hi = (hi + Math.imul(ah2, bh1)) | 0;
11727 lo = (lo + Math.imul(al1, bl2)) | 0;
11728 mid = (mid + Math.imul(al1, bh2)) | 0;
11729 mid = (mid + Math.imul(ah1, bl2)) | 0;
11730 hi = (hi + Math.imul(ah1, bh2)) | 0;
11731 lo = (lo + Math.imul(al0, bl3)) | 0;
11732 mid = (mid + Math.imul(al0, bh3)) | 0;
11733 mid = (mid + Math.imul(ah0, bl3)) | 0;
11734 hi = (hi + Math.imul(ah0, bh3)) | 0;
11735 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11736 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
11737 w3 &= 0x3ffffff;
11738 /* k = 4 */
11739 lo = Math.imul(al4, bl0);
11740 mid = Math.imul(al4, bh0);
11741 mid = (mid + Math.imul(ah4, bl0)) | 0;
11742 hi = Math.imul(ah4, bh0);
11743 lo = (lo + Math.imul(al3, bl1)) | 0;
11744 mid = (mid + Math.imul(al3, bh1)) | 0;
11745 mid = (mid + Math.imul(ah3, bl1)) | 0;
11746 hi = (hi + Math.imul(ah3, bh1)) | 0;
11747 lo = (lo + Math.imul(al2, bl2)) | 0;
11748 mid = (mid + Math.imul(al2, bh2)) | 0;
11749 mid = (mid + Math.imul(ah2, bl2)) | 0;
11750 hi = (hi + Math.imul(ah2, bh2)) | 0;
11751 lo = (lo + Math.imul(al1, bl3)) | 0;
11752 mid = (mid + Math.imul(al1, bh3)) | 0;
11753 mid = (mid + Math.imul(ah1, bl3)) | 0;
11754 hi = (hi + Math.imul(ah1, bh3)) | 0;
11755 lo = (lo + Math.imul(al0, bl4)) | 0;
11756 mid = (mid + Math.imul(al0, bh4)) | 0;
11757 mid = (mid + Math.imul(ah0, bl4)) | 0;
11758 hi = (hi + Math.imul(ah0, bh4)) | 0;
11759 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11760 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
11761 w4 &= 0x3ffffff;
11762 /* k = 5 */
11763 lo = Math.imul(al5, bl0);
11764 mid = Math.imul(al5, bh0);
11765 mid = (mid + Math.imul(ah5, bl0)) | 0;
11766 hi = Math.imul(ah5, bh0);
11767 lo = (lo + Math.imul(al4, bl1)) | 0;
11768 mid = (mid + Math.imul(al4, bh1)) | 0;
11769 mid = (mid + Math.imul(ah4, bl1)) | 0;
11770 hi = (hi + Math.imul(ah4, bh1)) | 0;
11771 lo = (lo + Math.imul(al3, bl2)) | 0;
11772 mid = (mid + Math.imul(al3, bh2)) | 0;
11773 mid = (mid + Math.imul(ah3, bl2)) | 0;
11774 hi = (hi + Math.imul(ah3, bh2)) | 0;
11775 lo = (lo + Math.imul(al2, bl3)) | 0;
11776 mid = (mid + Math.imul(al2, bh3)) | 0;
11777 mid = (mid + Math.imul(ah2, bl3)) | 0;
11778 hi = (hi + Math.imul(ah2, bh3)) | 0;
11779 lo = (lo + Math.imul(al1, bl4)) | 0;
11780 mid = (mid + Math.imul(al1, bh4)) | 0;
11781 mid = (mid + Math.imul(ah1, bl4)) | 0;
11782 hi = (hi + Math.imul(ah1, bh4)) | 0;
11783 lo = (lo + Math.imul(al0, bl5)) | 0;
11784 mid = (mid + Math.imul(al0, bh5)) | 0;
11785 mid = (mid + Math.imul(ah0, bl5)) | 0;
11786 hi = (hi + Math.imul(ah0, bh5)) | 0;
11787 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11788 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
11789 w5 &= 0x3ffffff;
11790 /* k = 6 */
11791 lo = Math.imul(al6, bl0);
11792 mid = Math.imul(al6, bh0);
11793 mid = (mid + Math.imul(ah6, bl0)) | 0;
11794 hi = Math.imul(ah6, bh0);
11795 lo = (lo + Math.imul(al5, bl1)) | 0;
11796 mid = (mid + Math.imul(al5, bh1)) | 0;
11797 mid = (mid + Math.imul(ah5, bl1)) | 0;
11798 hi = (hi + Math.imul(ah5, bh1)) | 0;
11799 lo = (lo + Math.imul(al4, bl2)) | 0;
11800 mid = (mid + Math.imul(al4, bh2)) | 0;
11801 mid = (mid + Math.imul(ah4, bl2)) | 0;
11802 hi = (hi + Math.imul(ah4, bh2)) | 0;
11803 lo = (lo + Math.imul(al3, bl3)) | 0;
11804 mid = (mid + Math.imul(al3, bh3)) | 0;
11805 mid = (mid + Math.imul(ah3, bl3)) | 0;
11806 hi = (hi + Math.imul(ah3, bh3)) | 0;
11807 lo = (lo + Math.imul(al2, bl4)) | 0;
11808 mid = (mid + Math.imul(al2, bh4)) | 0;
11809 mid = (mid + Math.imul(ah2, bl4)) | 0;
11810 hi = (hi + Math.imul(ah2, bh4)) | 0;
11811 lo = (lo + Math.imul(al1, bl5)) | 0;
11812 mid = (mid + Math.imul(al1, bh5)) | 0;
11813 mid = (mid + Math.imul(ah1, bl5)) | 0;
11814 hi = (hi + Math.imul(ah1, bh5)) | 0;
11815 lo = (lo + Math.imul(al0, bl6)) | 0;
11816 mid = (mid + Math.imul(al0, bh6)) | 0;
11817 mid = (mid + Math.imul(ah0, bl6)) | 0;
11818 hi = (hi + Math.imul(ah0, bh6)) | 0;
11819 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11820 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
11821 w6 &= 0x3ffffff;
11822 /* k = 7 */
11823 lo = Math.imul(al7, bl0);
11824 mid = Math.imul(al7, bh0);
11825 mid = (mid + Math.imul(ah7, bl0)) | 0;
11826 hi = Math.imul(ah7, bh0);
11827 lo = (lo + Math.imul(al6, bl1)) | 0;
11828 mid = (mid + Math.imul(al6, bh1)) | 0;
11829 mid = (mid + Math.imul(ah6, bl1)) | 0;
11830 hi = (hi + Math.imul(ah6, bh1)) | 0;
11831 lo = (lo + Math.imul(al5, bl2)) | 0;
11832 mid = (mid + Math.imul(al5, bh2)) | 0;
11833 mid = (mid + Math.imul(ah5, bl2)) | 0;
11834 hi = (hi + Math.imul(ah5, bh2)) | 0;
11835 lo = (lo + Math.imul(al4, bl3)) | 0;
11836 mid = (mid + Math.imul(al4, bh3)) | 0;
11837 mid = (mid + Math.imul(ah4, bl3)) | 0;
11838 hi = (hi + Math.imul(ah4, bh3)) | 0;
11839 lo = (lo + Math.imul(al3, bl4)) | 0;
11840 mid = (mid + Math.imul(al3, bh4)) | 0;
11841 mid = (mid + Math.imul(ah3, bl4)) | 0;
11842 hi = (hi + Math.imul(ah3, bh4)) | 0;
11843 lo = (lo + Math.imul(al2, bl5)) | 0;
11844 mid = (mid + Math.imul(al2, bh5)) | 0;
11845 mid = (mid + Math.imul(ah2, bl5)) | 0;
11846 hi = (hi + Math.imul(ah2, bh5)) | 0;
11847 lo = (lo + Math.imul(al1, bl6)) | 0;
11848 mid = (mid + Math.imul(al1, bh6)) | 0;
11849 mid = (mid + Math.imul(ah1, bl6)) | 0;
11850 hi = (hi + Math.imul(ah1, bh6)) | 0;
11851 lo = (lo + Math.imul(al0, bl7)) | 0;
11852 mid = (mid + Math.imul(al0, bh7)) | 0;
11853 mid = (mid + Math.imul(ah0, bl7)) | 0;
11854 hi = (hi + Math.imul(ah0, bh7)) | 0;
11855 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11856 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
11857 w7 &= 0x3ffffff;
11858 /* k = 8 */
11859 lo = Math.imul(al8, bl0);
11860 mid = Math.imul(al8, bh0);
11861 mid = (mid + Math.imul(ah8, bl0)) | 0;
11862 hi = Math.imul(ah8, bh0);
11863 lo = (lo + Math.imul(al7, bl1)) | 0;
11864 mid = (mid + Math.imul(al7, bh1)) | 0;
11865 mid = (mid + Math.imul(ah7, bl1)) | 0;
11866 hi = (hi + Math.imul(ah7, bh1)) | 0;
11867 lo = (lo + Math.imul(al6, bl2)) | 0;
11868 mid = (mid + Math.imul(al6, bh2)) | 0;
11869 mid = (mid + Math.imul(ah6, bl2)) | 0;
11870 hi = (hi + Math.imul(ah6, bh2)) | 0;
11871 lo = (lo + Math.imul(al5, bl3)) | 0;
11872 mid = (mid + Math.imul(al5, bh3)) | 0;
11873 mid = (mid + Math.imul(ah5, bl3)) | 0;
11874 hi = (hi + Math.imul(ah5, bh3)) | 0;
11875 lo = (lo + Math.imul(al4, bl4)) | 0;
11876 mid = (mid + Math.imul(al4, bh4)) | 0;
11877 mid = (mid + Math.imul(ah4, bl4)) | 0;
11878 hi = (hi + Math.imul(ah4, bh4)) | 0;
11879 lo = (lo + Math.imul(al3, bl5)) | 0;
11880 mid = (mid + Math.imul(al3, bh5)) | 0;
11881 mid = (mid + Math.imul(ah3, bl5)) | 0;
11882 hi = (hi + Math.imul(ah3, bh5)) | 0;
11883 lo = (lo + Math.imul(al2, bl6)) | 0;
11884 mid = (mid + Math.imul(al2, bh6)) | 0;
11885 mid = (mid + Math.imul(ah2, bl6)) | 0;
11886 hi = (hi + Math.imul(ah2, bh6)) | 0;
11887 lo = (lo + Math.imul(al1, bl7)) | 0;
11888 mid = (mid + Math.imul(al1, bh7)) | 0;
11889 mid = (mid + Math.imul(ah1, bl7)) | 0;
11890 hi = (hi + Math.imul(ah1, bh7)) | 0;
11891 lo = (lo + Math.imul(al0, bl8)) | 0;
11892 mid = (mid + Math.imul(al0, bh8)) | 0;
11893 mid = (mid + Math.imul(ah0, bl8)) | 0;
11894 hi = (hi + Math.imul(ah0, bh8)) | 0;
11895 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11896 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
11897 w8 &= 0x3ffffff;
11898 /* k = 9 */
11899 lo = Math.imul(al9, bl0);
11900 mid = Math.imul(al9, bh0);
11901 mid = (mid + Math.imul(ah9, bl0)) | 0;
11902 hi = Math.imul(ah9, bh0);
11903 lo = (lo + Math.imul(al8, bl1)) | 0;
11904 mid = (mid + Math.imul(al8, bh1)) | 0;
11905 mid = (mid + Math.imul(ah8, bl1)) | 0;
11906 hi = (hi + Math.imul(ah8, bh1)) | 0;
11907 lo = (lo + Math.imul(al7, bl2)) | 0;
11908 mid = (mid + Math.imul(al7, bh2)) | 0;
11909 mid = (mid + Math.imul(ah7, bl2)) | 0;
11910 hi = (hi + Math.imul(ah7, bh2)) | 0;
11911 lo = (lo + Math.imul(al6, bl3)) | 0;
11912 mid = (mid + Math.imul(al6, bh3)) | 0;
11913 mid = (mid + Math.imul(ah6, bl3)) | 0;
11914 hi = (hi + Math.imul(ah6, bh3)) | 0;
11915 lo = (lo + Math.imul(al5, bl4)) | 0;
11916 mid = (mid + Math.imul(al5, bh4)) | 0;
11917 mid = (mid + Math.imul(ah5, bl4)) | 0;
11918 hi = (hi + Math.imul(ah5, bh4)) | 0;
11919 lo = (lo + Math.imul(al4, bl5)) | 0;
11920 mid = (mid + Math.imul(al4, bh5)) | 0;
11921 mid = (mid + Math.imul(ah4, bl5)) | 0;
11922 hi = (hi + Math.imul(ah4, bh5)) | 0;
11923 lo = (lo + Math.imul(al3, bl6)) | 0;
11924 mid = (mid + Math.imul(al3, bh6)) | 0;
11925 mid = (mid + Math.imul(ah3, bl6)) | 0;
11926 hi = (hi + Math.imul(ah3, bh6)) | 0;
11927 lo = (lo + Math.imul(al2, bl7)) | 0;
11928 mid = (mid + Math.imul(al2, bh7)) | 0;
11929 mid = (mid + Math.imul(ah2, bl7)) | 0;
11930 hi = (hi + Math.imul(ah2, bh7)) | 0;
11931 lo = (lo + Math.imul(al1, bl8)) | 0;
11932 mid = (mid + Math.imul(al1, bh8)) | 0;
11933 mid = (mid + Math.imul(ah1, bl8)) | 0;
11934 hi = (hi + Math.imul(ah1, bh8)) | 0;
11935 lo = (lo + Math.imul(al0, bl9)) | 0;
11936 mid = (mid + Math.imul(al0, bh9)) | 0;
11937 mid = (mid + Math.imul(ah0, bl9)) | 0;
11938 hi = (hi + Math.imul(ah0, bh9)) | 0;
11939 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11940 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
11941 w9 &= 0x3ffffff;
11942 /* k = 10 */
11943 lo = Math.imul(al9, bl1);
11944 mid = Math.imul(al9, bh1);
11945 mid = (mid + Math.imul(ah9, bl1)) | 0;
11946 hi = Math.imul(ah9, bh1);
11947 lo = (lo + Math.imul(al8, bl2)) | 0;
11948 mid = (mid + Math.imul(al8, bh2)) | 0;
11949 mid = (mid + Math.imul(ah8, bl2)) | 0;
11950 hi = (hi + Math.imul(ah8, bh2)) | 0;
11951 lo = (lo + Math.imul(al7, bl3)) | 0;
11952 mid = (mid + Math.imul(al7, bh3)) | 0;
11953 mid = (mid + Math.imul(ah7, bl3)) | 0;
11954 hi = (hi + Math.imul(ah7, bh3)) | 0;
11955 lo = (lo + Math.imul(al6, bl4)) | 0;
11956 mid = (mid + Math.imul(al6, bh4)) | 0;
11957 mid = (mid + Math.imul(ah6, bl4)) | 0;
11958 hi = (hi + Math.imul(ah6, bh4)) | 0;
11959 lo = (lo + Math.imul(al5, bl5)) | 0;
11960 mid = (mid + Math.imul(al5, bh5)) | 0;
11961 mid = (mid + Math.imul(ah5, bl5)) | 0;
11962 hi = (hi + Math.imul(ah5, bh5)) | 0;
11963 lo = (lo + Math.imul(al4, bl6)) | 0;
11964 mid = (mid + Math.imul(al4, bh6)) | 0;
11965 mid = (mid + Math.imul(ah4, bl6)) | 0;
11966 hi = (hi + Math.imul(ah4, bh6)) | 0;
11967 lo = (lo + Math.imul(al3, bl7)) | 0;
11968 mid = (mid + Math.imul(al3, bh7)) | 0;
11969 mid = (mid + Math.imul(ah3, bl7)) | 0;
11970 hi = (hi + Math.imul(ah3, bh7)) | 0;
11971 lo = (lo + Math.imul(al2, bl8)) | 0;
11972 mid = (mid + Math.imul(al2, bh8)) | 0;
11973 mid = (mid + Math.imul(ah2, bl8)) | 0;
11974 hi = (hi + Math.imul(ah2, bh8)) | 0;
11975 lo = (lo + Math.imul(al1, bl9)) | 0;
11976 mid = (mid + Math.imul(al1, bh9)) | 0;
11977 mid = (mid + Math.imul(ah1, bl9)) | 0;
11978 hi = (hi + Math.imul(ah1, bh9)) | 0;
11979 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11980 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
11981 w10 &= 0x3ffffff;
11982 /* k = 11 */
11983 lo = Math.imul(al9, bl2);
11984 mid = Math.imul(al9, bh2);
11985 mid = (mid + Math.imul(ah9, bl2)) | 0;
11986 hi = Math.imul(ah9, bh2);
11987 lo = (lo + Math.imul(al8, bl3)) | 0;
11988 mid = (mid + Math.imul(al8, bh3)) | 0;
11989 mid = (mid + Math.imul(ah8, bl3)) | 0;
11990 hi = (hi + Math.imul(ah8, bh3)) | 0;
11991 lo = (lo + Math.imul(al7, bl4)) | 0;
11992 mid = (mid + Math.imul(al7, bh4)) | 0;
11993 mid = (mid + Math.imul(ah7, bl4)) | 0;
11994 hi = (hi + Math.imul(ah7, bh4)) | 0;
11995 lo = (lo + Math.imul(al6, bl5)) | 0;
11996 mid = (mid + Math.imul(al6, bh5)) | 0;
11997 mid = (mid + Math.imul(ah6, bl5)) | 0;
11998 hi = (hi + Math.imul(ah6, bh5)) | 0;
11999 lo = (lo + Math.imul(al5, bl6)) | 0;
12000 mid = (mid + Math.imul(al5, bh6)) | 0;
12001 mid = (mid + Math.imul(ah5, bl6)) | 0;
12002 hi = (hi + Math.imul(ah5, bh6)) | 0;
12003 lo = (lo + Math.imul(al4, bl7)) | 0;
12004 mid = (mid + Math.imul(al4, bh7)) | 0;
12005 mid = (mid + Math.imul(ah4, bl7)) | 0;
12006 hi = (hi + Math.imul(ah4, bh7)) | 0;
12007 lo = (lo + Math.imul(al3, bl8)) | 0;
12008 mid = (mid + Math.imul(al3, bh8)) | 0;
12009 mid = (mid + Math.imul(ah3, bl8)) | 0;
12010 hi = (hi + Math.imul(ah3, bh8)) | 0;
12011 lo = (lo + Math.imul(al2, bl9)) | 0;
12012 mid = (mid + Math.imul(al2, bh9)) | 0;
12013 mid = (mid + Math.imul(ah2, bl9)) | 0;
12014 hi = (hi + Math.imul(ah2, bh9)) | 0;
12015 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12016 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
12017 w11 &= 0x3ffffff;
12018 /* k = 12 */
12019 lo = Math.imul(al9, bl3);
12020 mid = Math.imul(al9, bh3);
12021 mid = (mid + Math.imul(ah9, bl3)) | 0;
12022 hi = Math.imul(ah9, bh3);
12023 lo = (lo + Math.imul(al8, bl4)) | 0;
12024 mid = (mid + Math.imul(al8, bh4)) | 0;
12025 mid = (mid + Math.imul(ah8, bl4)) | 0;
12026 hi = (hi + Math.imul(ah8, bh4)) | 0;
12027 lo = (lo + Math.imul(al7, bl5)) | 0;
12028 mid = (mid + Math.imul(al7, bh5)) | 0;
12029 mid = (mid + Math.imul(ah7, bl5)) | 0;
12030 hi = (hi + Math.imul(ah7, bh5)) | 0;
12031 lo = (lo + Math.imul(al6, bl6)) | 0;
12032 mid = (mid + Math.imul(al6, bh6)) | 0;
12033 mid = (mid + Math.imul(ah6, bl6)) | 0;
12034 hi = (hi + Math.imul(ah6, bh6)) | 0;
12035 lo = (lo + Math.imul(al5, bl7)) | 0;
12036 mid = (mid + Math.imul(al5, bh7)) | 0;
12037 mid = (mid + Math.imul(ah5, bl7)) | 0;
12038 hi = (hi + Math.imul(ah5, bh7)) | 0;
12039 lo = (lo + Math.imul(al4, bl8)) | 0;
12040 mid = (mid + Math.imul(al4, bh8)) | 0;
12041 mid = (mid + Math.imul(ah4, bl8)) | 0;
12042 hi = (hi + Math.imul(ah4, bh8)) | 0;
12043 lo = (lo + Math.imul(al3, bl9)) | 0;
12044 mid = (mid + Math.imul(al3, bh9)) | 0;
12045 mid = (mid + Math.imul(ah3, bl9)) | 0;
12046 hi = (hi + Math.imul(ah3, bh9)) | 0;
12047 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12048 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
12049 w12 &= 0x3ffffff;
12050 /* k = 13 */
12051 lo = Math.imul(al9, bl4);
12052 mid = Math.imul(al9, bh4);
12053 mid = (mid + Math.imul(ah9, bl4)) | 0;
12054 hi = Math.imul(ah9, bh4);
12055 lo = (lo + Math.imul(al8, bl5)) | 0;
12056 mid = (mid + Math.imul(al8, bh5)) | 0;
12057 mid = (mid + Math.imul(ah8, bl5)) | 0;
12058 hi = (hi + Math.imul(ah8, bh5)) | 0;
12059 lo = (lo + Math.imul(al7, bl6)) | 0;
12060 mid = (mid + Math.imul(al7, bh6)) | 0;
12061 mid = (mid + Math.imul(ah7, bl6)) | 0;
12062 hi = (hi + Math.imul(ah7, bh6)) | 0;
12063 lo = (lo + Math.imul(al6, bl7)) | 0;
12064 mid = (mid + Math.imul(al6, bh7)) | 0;
12065 mid = (mid + Math.imul(ah6, bl7)) | 0;
12066 hi = (hi + Math.imul(ah6, bh7)) | 0;
12067 lo = (lo + Math.imul(al5, bl8)) | 0;
12068 mid = (mid + Math.imul(al5, bh8)) | 0;
12069 mid = (mid + Math.imul(ah5, bl8)) | 0;
12070 hi = (hi + Math.imul(ah5, bh8)) | 0;
12071 lo = (lo + Math.imul(al4, bl9)) | 0;
12072 mid = (mid + Math.imul(al4, bh9)) | 0;
12073 mid = (mid + Math.imul(ah4, bl9)) | 0;
12074 hi = (hi + Math.imul(ah4, bh9)) | 0;
12075 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12076 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
12077 w13 &= 0x3ffffff;
12078 /* k = 14 */
12079 lo = Math.imul(al9, bl5);
12080 mid = Math.imul(al9, bh5);
12081 mid = (mid + Math.imul(ah9, bl5)) | 0;
12082 hi = Math.imul(ah9, bh5);
12083 lo = (lo + Math.imul(al8, bl6)) | 0;
12084 mid = (mid + Math.imul(al8, bh6)) | 0;
12085 mid = (mid + Math.imul(ah8, bl6)) | 0;
12086 hi = (hi + Math.imul(ah8, bh6)) | 0;
12087 lo = (lo + Math.imul(al7, bl7)) | 0;
12088 mid = (mid + Math.imul(al7, bh7)) | 0;
12089 mid = (mid + Math.imul(ah7, bl7)) | 0;
12090 hi = (hi + Math.imul(ah7, bh7)) | 0;
12091 lo = (lo + Math.imul(al6, bl8)) | 0;
12092 mid = (mid + Math.imul(al6, bh8)) | 0;
12093 mid = (mid + Math.imul(ah6, bl8)) | 0;
12094 hi = (hi + Math.imul(ah6, bh8)) | 0;
12095 lo = (lo + Math.imul(al5, bl9)) | 0;
12096 mid = (mid + Math.imul(al5, bh9)) | 0;
12097 mid = (mid + Math.imul(ah5, bl9)) | 0;
12098 hi = (hi + Math.imul(ah5, bh9)) | 0;
12099 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12100 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
12101 w14 &= 0x3ffffff;
12102 /* k = 15 */
12103 lo = Math.imul(al9, bl6);
12104 mid = Math.imul(al9, bh6);
12105 mid = (mid + Math.imul(ah9, bl6)) | 0;
12106 hi = Math.imul(ah9, bh6);
12107 lo = (lo + Math.imul(al8, bl7)) | 0;
12108 mid = (mid + Math.imul(al8, bh7)) | 0;
12109 mid = (mid + Math.imul(ah8, bl7)) | 0;
12110 hi = (hi + Math.imul(ah8, bh7)) | 0;
12111 lo = (lo + Math.imul(al7, bl8)) | 0;
12112 mid = (mid + Math.imul(al7, bh8)) | 0;
12113 mid = (mid + Math.imul(ah7, bl8)) | 0;
12114 hi = (hi + Math.imul(ah7, bh8)) | 0;
12115 lo = (lo + Math.imul(al6, bl9)) | 0;
12116 mid = (mid + Math.imul(al6, bh9)) | 0;
12117 mid = (mid + Math.imul(ah6, bl9)) | 0;
12118 hi = (hi + Math.imul(ah6, bh9)) | 0;
12119 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12120 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
12121 w15 &= 0x3ffffff;
12122 /* k = 16 */
12123 lo = Math.imul(al9, bl7);
12124 mid = Math.imul(al9, bh7);
12125 mid = (mid + Math.imul(ah9, bl7)) | 0;
12126 hi = Math.imul(ah9, bh7);
12127 lo = (lo + Math.imul(al8, bl8)) | 0;
12128 mid = (mid + Math.imul(al8, bh8)) | 0;
12129 mid = (mid + Math.imul(ah8, bl8)) | 0;
12130 hi = (hi + Math.imul(ah8, bh8)) | 0;
12131 lo = (lo + Math.imul(al7, bl9)) | 0;
12132 mid = (mid + Math.imul(al7, bh9)) | 0;
12133 mid = (mid + Math.imul(ah7, bl9)) | 0;
12134 hi = (hi + Math.imul(ah7, bh9)) | 0;
12135 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12136 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
12137 w16 &= 0x3ffffff;
12138 /* k = 17 */
12139 lo = Math.imul(al9, bl8);
12140 mid = Math.imul(al9, bh8);
12141 mid = (mid + Math.imul(ah9, bl8)) | 0;
12142 hi = Math.imul(ah9, bh8);
12143 lo = (lo + Math.imul(al8, bl9)) | 0;
12144 mid = (mid + Math.imul(al8, bh9)) | 0;
12145 mid = (mid + Math.imul(ah8, bl9)) | 0;
12146 hi = (hi + Math.imul(ah8, bh9)) | 0;
12147 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12148 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
12149 w17 &= 0x3ffffff;
12150 /* k = 18 */
12151 lo = Math.imul(al9, bl9);
12152 mid = Math.imul(al9, bh9);
12153 mid = (mid + Math.imul(ah9, bl9)) | 0;
12154 hi = Math.imul(ah9, bh9);
12155 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
12156 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
12157 w18 &= 0x3ffffff;
12158 o[0] = w0;
12159 o[1] = w1;
12160 o[2] = w2;
12161 o[3] = w3;
12162 o[4] = w4;
12163 o[5] = w5;
12164 o[6] = w6;
12165 o[7] = w7;
12166 o[8] = w8;
12167 o[9] = w9;
12168 o[10] = w10;
12169 o[11] = w11;
12170 o[12] = w12;
12171 o[13] = w13;
12172 o[14] = w14;
12173 o[15] = w15;
12174 o[16] = w16;
12175 o[17] = w17;
12176 o[18] = w18;
12177 if (c !== 0) {
12178 o[19] = c;
12179 out.length++;
12180 }
12181 return out;
12182 };
12183
12184 // Polyfill comb
12185 if (!Math.imul) {
12186 comb10MulTo = smallMulTo;
12187 }
12188
12189 function bigMulTo (self, num, out) {
12190 out.negative = num.negative ^ self.negative;
12191 out.length = self.length + num.length;
12192
12193 var carry = 0;
12194 var hncarry = 0;
12195 for (var k = 0; k < out.length - 1; k++) {
12196 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
12197 // note that ncarry could be >= 0x3ffffff
12198 var ncarry = hncarry;
12199 hncarry = 0;
12200 var rword = carry & 0x3ffffff;
12201 var maxJ = Math.min(k, num.length - 1);
12202 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
12203 var i = k - j;
12204 var a = self.words[i] | 0;
12205 var b = num.words[j] | 0;
12206 var r = a * b;
12207
12208 var lo = r & 0x3ffffff;
12209 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
12210 lo = (lo + rword) | 0;
12211 rword = lo & 0x3ffffff;
12212 ncarry = (ncarry + (lo >>> 26)) | 0;
12213
12214 hncarry += ncarry >>> 26;
12215 ncarry &= 0x3ffffff;
12216 }
12217 out.words[k] = rword;
12218 carry = ncarry;
12219 ncarry = hncarry;
12220 }
12221 if (carry !== 0) {
12222 out.words[k] = carry;
12223 } else {
12224 out.length--;
12225 }
12226
12227 return out.strip();
12228 }
12229
12230 function jumboMulTo (self, num, out) {
12231 var fftm = new FFTM();
12232 return fftm.mulp(self, num, out);
12233 }
12234
12235 BN.prototype.mulTo = function mulTo (num, out) {
12236 var res;
12237 var len = this.length + num.length;
12238 if (this.length === 10 && num.length === 10) {
12239 res = comb10MulTo(this, num, out);
12240 } else if (len < 63) {
12241 res = smallMulTo(this, num, out);
12242 } else if (len < 1024) {
12243 res = bigMulTo(this, num, out);
12244 } else {
12245 res = jumboMulTo(this, num, out);
12246 }
12247
12248 return res;
12249 };
12250
12251 // Cooley-Tukey algorithm for FFT
12252 // slightly revisited to rely on looping instead of recursion
12253
12254 function FFTM (x, y) {
12255 this.x = x;
12256 this.y = y;
12257 }
12258
12259 FFTM.prototype.makeRBT = function makeRBT (N) {
12260 var t = new Array(N);
12261 var l = BN.prototype._countBits(N) - 1;
12262 for (var i = 0; i < N; i++) {
12263 t[i] = this.revBin(i, l, N);
12264 }
12265
12266 return t;
12267 };
12268
12269 // Returns binary-reversed representation of `x`
12270 FFTM.prototype.revBin = function revBin (x, l, N) {
12271 if (x === 0 || x === N - 1) return x;
12272
12273 var rb = 0;
12274 for (var i = 0; i < l; i++) {
12275 rb |= (x & 1) << (l - i - 1);
12276 x >>= 1;
12277 }
12278
12279 return rb;
12280 };
12281
12282 // Performs "tweedling" phase, therefore 'emulating'
12283 // behaviour of the recursive algorithm
12284 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
12285 for (var i = 0; i < N; i++) {
12286 rtws[i] = rws[rbt[i]];
12287 itws[i] = iws[rbt[i]];
12288 }
12289 };
12290
12291 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
12292 this.permute(rbt, rws, iws, rtws, itws, N);
12293
12294 for (var s = 1; s < N; s <<= 1) {
12295 var l = s << 1;
12296
12297 var rtwdf = Math.cos(2 * Math.PI / l);
12298 var itwdf = Math.sin(2 * Math.PI / l);
12299
12300 for (var p = 0; p < N; p += l) {
12301 var rtwdf_ = rtwdf;
12302 var itwdf_ = itwdf;
12303
12304 for (var j = 0; j < s; j++) {
12305 var re = rtws[p + j];
12306 var ie = itws[p + j];
12307
12308 var ro = rtws[p + j + s];
12309 var io = itws[p + j + s];
12310
12311 var rx = rtwdf_ * ro - itwdf_ * io;
12312
12313 io = rtwdf_ * io + itwdf_ * ro;
12314 ro = rx;
12315
12316 rtws[p + j] = re + ro;
12317 itws[p + j] = ie + io;
12318
12319 rtws[p + j + s] = re - ro;
12320 itws[p + j + s] = ie - io;
12321
12322 /* jshint maxdepth : false */
12323 if (j !== l) {
12324 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
12325
12326 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
12327 rtwdf_ = rx;
12328 }
12329 }
12330 }
12331 }
12332 };
12333
12334 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
12335 var N = Math.max(m, n) | 1;
12336 var odd = N & 1;
12337 var i = 0;
12338 for (N = N / 2 | 0; N; N = N >>> 1) {
12339 i++;
12340 }
12341
12342 return 1 << i + 1 + odd;
12343 };
12344
12345 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
12346 if (N <= 1) return;
12347
12348 for (var i = 0; i < N / 2; i++) {
12349 var t = rws[i];
12350
12351 rws[i] = rws[N - i - 1];
12352 rws[N - i - 1] = t;
12353
12354 t = iws[i];
12355
12356 iws[i] = -iws[N - i - 1];
12357 iws[N - i - 1] = -t;
12358 }
12359 };
12360
12361 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
12362 var carry = 0;
12363 for (var i = 0; i < N / 2; i++) {
12364 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
12365 Math.round(ws[2 * i] / N) +
12366 carry;
12367
12368 ws[i] = w & 0x3ffffff;
12369
12370 if (w < 0x4000000) {
12371 carry = 0;
12372 } else {
12373 carry = w / 0x4000000 | 0;
12374 }
12375 }
12376
12377 return ws;
12378 };
12379
12380 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
12381 var carry = 0;
12382 for (var i = 0; i < len; i++) {
12383 carry = carry + (ws[i] | 0);
12384
12385 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
12386 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
12387 }
12388
12389 // Pad with zeroes
12390 for (i = 2 * len; i < N; ++i) {
12391 rws[i] = 0;
12392 }
12393
12394 assert(carry === 0);
12395 assert((carry & ~0x1fff) === 0);
12396 };
12397
12398 FFTM.prototype.stub = function stub (N) {
12399 var ph = new Array(N);
12400 for (var i = 0; i < N; i++) {
12401 ph[i] = 0;
12402 }
12403
12404 return ph;
12405 };
12406
12407 FFTM.prototype.mulp = function mulp (x, y, out) {
12408 var N = 2 * this.guessLen13b(x.length, y.length);
12409
12410 var rbt = this.makeRBT(N);
12411
12412 var _ = this.stub(N);
12413
12414 var rws = new Array(N);
12415 var rwst = new Array(N);
12416 var iwst = new Array(N);
12417
12418 var nrws = new Array(N);
12419 var nrwst = new Array(N);
12420 var niwst = new Array(N);
12421
12422 var rmws = out.words;
12423 rmws.length = N;
12424
12425 this.convert13b(x.words, x.length, rws, N);
12426 this.convert13b(y.words, y.length, nrws, N);
12427
12428 this.transform(rws, _, rwst, iwst, N, rbt);
12429 this.transform(nrws, _, nrwst, niwst, N, rbt);
12430
12431 for (var i = 0; i < N; i++) {
12432 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
12433 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
12434 rwst[i] = rx;
12435 }
12436
12437 this.conjugate(rwst, iwst, N);
12438 this.transform(rwst, iwst, rmws, _, N, rbt);
12439 this.conjugate(rmws, _, N);
12440 this.normalize13b(rmws, N);
12441
12442 out.negative = x.negative ^ y.negative;
12443 out.length = x.length + y.length;
12444 return out.strip();
12445 };
12446
12447 // Multiply `this` by `num`
12448 BN.prototype.mul = function mul (num) {
12449 var out = new BN(null);
12450 out.words = new Array(this.length + num.length);
12451 return this.mulTo(num, out);
12452 };
12453
12454 // Multiply employing FFT
12455 BN.prototype.mulf = function mulf (num) {
12456 var out = new BN(null);
12457 out.words = new Array(this.length + num.length);
12458 return jumboMulTo(this, num, out);
12459 };
12460
12461 // In-place Multiplication
12462 BN.prototype.imul = function imul (num) {
12463 return this.clone().mulTo(num, this);
12464 };
12465
12466 BN.prototype.imuln = function imuln (num) {
12467 assert(typeof num === 'number');
12468 assert(num < 0x4000000);
12469
12470 // Carry
12471 var carry = 0;
12472 for (var i = 0; i < this.length; i++) {
12473 var w = (this.words[i] | 0) * num;
12474 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
12475 carry >>= 26;
12476 carry += (w / 0x4000000) | 0;
12477 // NOTE: lo is 27bit maximum
12478 carry += lo >>> 26;
12479 this.words[i] = lo & 0x3ffffff;
12480 }
12481
12482 if (carry !== 0) {
12483 this.words[i] = carry;
12484 this.length++;
12485 }
12486
12487 return this;
12488 };
12489
12490 BN.prototype.muln = function muln (num) {
12491 return this.clone().imuln(num);
12492 };
12493
12494 // `this` * `this`
12495 BN.prototype.sqr = function sqr () {
12496 return this.mul(this);
12497 };
12498
12499 // `this` * `this` in-place
12500 BN.prototype.isqr = function isqr () {
12501 return this.imul(this.clone());
12502 };
12503
12504 // Math.pow(`this`, `num`)
12505 BN.prototype.pow = function pow (num) {
12506 var w = toBitArray(num);
12507 if (w.length === 0) return new BN(1);
12508
12509 // Skip leading zeroes
12510 var res = this;
12511 for (var i = 0; i < w.length; i++, res = res.sqr()) {
12512 if (w[i] !== 0) break;
12513 }
12514
12515 if (++i < w.length) {
12516 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
12517 if (w[i] === 0) continue;
12518
12519 res = res.mul(q);
12520 }
12521 }
12522
12523 return res;
12524 };
12525
12526 // Shift-left in-place
12527 BN.prototype.iushln = function iushln (bits) {
12528 assert(typeof bits === 'number' && bits >= 0);
12529 var r = bits % 26;
12530 var s = (bits - r) / 26;
12531 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
12532 var i;
12533
12534 if (r !== 0) {
12535 var carry = 0;
12536
12537 for (i = 0; i < this.length; i++) {
12538 var newCarry = this.words[i] & carryMask;
12539 var c = ((this.words[i] | 0) - newCarry) << r;
12540 this.words[i] = c | carry;
12541 carry = newCarry >>> (26 - r);
12542 }
12543
12544 if (carry) {
12545 this.words[i] = carry;
12546 this.length++;
12547 }
12548 }
12549
12550 if (s !== 0) {
12551 for (i = this.length - 1; i >= 0; i--) {
12552 this.words[i + s] = this.words[i];
12553 }
12554
12555 for (i = 0; i < s; i++) {
12556 this.words[i] = 0;
12557 }
12558
12559 this.length += s;
12560 }
12561
12562 return this.strip();
12563 };
12564
12565 BN.prototype.ishln = function ishln (bits) {
12566 // TODO(indutny): implement me
12567 assert(this.negative === 0);
12568 return this.iushln(bits);
12569 };
12570
12571 // Shift-right in-place
12572 // NOTE: `hint` is a lowest bit before trailing zeroes
12573 // NOTE: if `extended` is present - it will be filled with destroyed bits
12574 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
12575 assert(typeof bits === 'number' && bits >= 0);
12576 var h;
12577 if (hint) {
12578 h = (hint - (hint % 26)) / 26;
12579 } else {
12580 h = 0;
12581 }
12582
12583 var r = bits % 26;
12584 var s = Math.min((bits - r) / 26, this.length);
12585 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
12586 var maskedWords = extended;
12587
12588 h -= s;
12589 h = Math.max(0, h);
12590
12591 // Extended mode, copy masked part
12592 if (maskedWords) {
12593 for (var i = 0; i < s; i++) {
12594 maskedWords.words[i] = this.words[i];
12595 }
12596 maskedWords.length = s;
12597 }
12598
12599 if (s === 0) {
12600 // No-op, we should not move anything at all
12601 } else if (this.length > s) {
12602 this.length -= s;
12603 for (i = 0; i < this.length; i++) {
12604 this.words[i] = this.words[i + s];
12605 }
12606 } else {
12607 this.words[0] = 0;
12608 this.length = 1;
12609 }
12610
12611 var carry = 0;
12612 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
12613 var word = this.words[i] | 0;
12614 this.words[i] = (carry << (26 - r)) | (word >>> r);
12615 carry = word & mask;
12616 }
12617
12618 // Push carried bits as a mask
12619 if (maskedWords && carry !== 0) {
12620 maskedWords.words[maskedWords.length++] = carry;
12621 }
12622
12623 if (this.length === 0) {
12624 this.words[0] = 0;
12625 this.length = 1;
12626 }
12627
12628 return this.strip();
12629 };
12630
12631 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
12632 // TODO(indutny): implement me
12633 assert(this.negative === 0);
12634 return this.iushrn(bits, hint, extended);
12635 };
12636
12637 // Shift-left
12638 BN.prototype.shln = function shln (bits) {
12639 return this.clone().ishln(bits);
12640 };
12641
12642 BN.prototype.ushln = function ushln (bits) {
12643 return this.clone().iushln(bits);
12644 };
12645
12646 // Shift-right
12647 BN.prototype.shrn = function shrn (bits) {
12648 return this.clone().ishrn(bits);
12649 };
12650
12651 BN.prototype.ushrn = function ushrn (bits) {
12652 return this.clone().iushrn(bits);
12653 };
12654
12655 // Test if n bit is set
12656 BN.prototype.testn = function testn (bit) {
12657 assert(typeof bit === 'number' && bit >= 0);
12658 var r = bit % 26;
12659 var s = (bit - r) / 26;
12660 var q = 1 << r;
12661
12662 // Fast case: bit is much higher than all existing words
12663 if (this.length <= s) return false;
12664
12665 // Check bit and return
12666 var w = this.words[s];
12667
12668 return !!(w & q);
12669 };
12670
12671 // Return only lowers bits of number (in-place)
12672 BN.prototype.imaskn = function imaskn (bits) {
12673 assert(typeof bits === 'number' && bits >= 0);
12674 var r = bits % 26;
12675 var s = (bits - r) / 26;
12676
12677 assert(this.negative === 0, 'imaskn works only with positive numbers');
12678
12679 if (this.length <= s) {
12680 return this;
12681 }
12682
12683 if (r !== 0) {
12684 s++;
12685 }
12686 this.length = Math.min(s, this.length);
12687
12688 if (r !== 0) {
12689 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
12690 this.words[this.length - 1] &= mask;
12691 }
12692
12693 return this.strip();
12694 };
12695
12696 // Return only lowers bits of number
12697 BN.prototype.maskn = function maskn (bits) {
12698 return this.clone().imaskn(bits);
12699 };
12700
12701 // Add plain number `num` to `this`
12702 BN.prototype.iaddn = function iaddn (num) {
12703 assert(typeof num === 'number');
12704 assert(num < 0x4000000);
12705 if (num < 0) return this.isubn(-num);
12706
12707 // Possible sign change
12708 if (this.negative !== 0) {
12709 if (this.length === 1 && (this.words[0] | 0) < num) {
12710 this.words[0] = num - (this.words[0] | 0);
12711 this.negative = 0;
12712 return this;
12713 }
12714
12715 this.negative = 0;
12716 this.isubn(num);
12717 this.negative = 1;
12718 return this;
12719 }
12720
12721 // Add without checks
12722 return this._iaddn(num);
12723 };
12724
12725 BN.prototype._iaddn = function _iaddn (num) {
12726 this.words[0] += num;
12727
12728 // Carry
12729 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
12730 this.words[i] -= 0x4000000;
12731 if (i === this.length - 1) {
12732 this.words[i + 1] = 1;
12733 } else {
12734 this.words[i + 1]++;
12735 }
12736 }
12737 this.length = Math.max(this.length, i + 1);
12738
12739 return this;
12740 };
12741
12742 // Subtract plain number `num` from `this`
12743 BN.prototype.isubn = function isubn (num) {
12744 assert(typeof num === 'number');
12745 assert(num < 0x4000000);
12746 if (num < 0) return this.iaddn(-num);
12747
12748 if (this.negative !== 0) {
12749 this.negative = 0;
12750 this.iaddn(num);
12751 this.negative = 1;
12752 return this;
12753 }
12754
12755 this.words[0] -= num;
12756
12757 if (this.length === 1 && this.words[0] < 0) {
12758 this.words[0] = -this.words[0];
12759 this.negative = 1;
12760 } else {
12761 // Carry
12762 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
12763 this.words[i] += 0x4000000;
12764 this.words[i + 1] -= 1;
12765 }
12766 }
12767
12768 return this.strip();
12769 };
12770
12771 BN.prototype.addn = function addn (num) {
12772 return this.clone().iaddn(num);
12773 };
12774
12775 BN.prototype.subn = function subn (num) {
12776 return this.clone().isubn(num);
12777 };
12778
12779 BN.prototype.iabs = function iabs () {
12780 this.negative = 0;
12781
12782 return this;
12783 };
12784
12785 BN.prototype.abs = function abs () {
12786 return this.clone().iabs();
12787 };
12788
12789 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
12790 var len = num.length + shift;
12791 var i;
12792
12793 this._expand(len);
12794
12795 var w;
12796 var carry = 0;
12797 for (i = 0; i < num.length; i++) {
12798 w = (this.words[i + shift] | 0) + carry;
12799 var right = (num.words[i] | 0) * mul;
12800 w -= right & 0x3ffffff;
12801 carry = (w >> 26) - ((right / 0x4000000) | 0);
12802 this.words[i + shift] = w & 0x3ffffff;
12803 }
12804 for (; i < this.length - shift; i++) {
12805 w = (this.words[i + shift] | 0) + carry;
12806 carry = w >> 26;
12807 this.words[i + shift] = w & 0x3ffffff;
12808 }
12809
12810 if (carry === 0) return this.strip();
12811
12812 // Subtraction overflow
12813 assert(carry === -1);
12814 carry = 0;
12815 for (i = 0; i < this.length; i++) {
12816 w = -(this.words[i] | 0) + carry;
12817 carry = w >> 26;
12818 this.words[i] = w & 0x3ffffff;
12819 }
12820 this.negative = 1;
12821
12822 return this.strip();
12823 };
12824
12825 BN.prototype._wordDiv = function _wordDiv (num, mode) {
12826 var shift = this.length - num.length;
12827
12828 var a = this.clone();
12829 var b = num;
12830
12831 // Normalize
12832 var bhi = b.words[b.length - 1] | 0;
12833 var bhiBits = this._countBits(bhi);
12834 shift = 26 - bhiBits;
12835 if (shift !== 0) {
12836 b = b.ushln(shift);
12837 a.iushln(shift);
12838 bhi = b.words[b.length - 1] | 0;
12839 }
12840
12841 // Initialize quotient
12842 var m = a.length - b.length;
12843 var q;
12844
12845 if (mode !== 'mod') {
12846 q = new BN(null);
12847 q.length = m + 1;
12848 q.words = new Array(q.length);
12849 for (var i = 0; i < q.length; i++) {
12850 q.words[i] = 0;
12851 }
12852 }
12853
12854 var diff = a.clone()._ishlnsubmul(b, 1, m);
12855 if (diff.negative === 0) {
12856 a = diff;
12857 if (q) {
12858 q.words[m] = 1;
12859 }
12860 }
12861
12862 for (var j = m - 1; j >= 0; j--) {
12863 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
12864 (a.words[b.length + j - 1] | 0);
12865
12866 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
12867 // (0x7ffffff)
12868 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
12869
12870 a._ishlnsubmul(b, qj, j);
12871 while (a.negative !== 0) {
12872 qj--;
12873 a.negative = 0;
12874 a._ishlnsubmul(b, 1, j);
12875 if (!a.isZero()) {
12876 a.negative ^= 1;
12877 }
12878 }
12879 if (q) {
12880 q.words[j] = qj;
12881 }
12882 }
12883 if (q) {
12884 q.strip();
12885 }
12886 a.strip();
12887
12888 // Denormalize
12889 if (mode !== 'div' && shift !== 0) {
12890 a.iushrn(shift);
12891 }
12892
12893 return {
12894 div: q || null,
12895 mod: a
12896 };
12897 };
12898
12899 // NOTE: 1) `mode` can be set to `mod` to request mod only,
12900 // to `div` to request div only, or be absent to
12901 // request both div & mod
12902 // 2) `positive` is true if unsigned mod is requested
12903 BN.prototype.divmod = function divmod (num, mode, positive) {
12904 assert(!num.isZero());
12905
12906 if (this.isZero()) {
12907 return {
12908 div: new BN(0),
12909 mod: new BN(0)
12910 };
12911 }
12912
12913 var div, mod, res;
12914 if (this.negative !== 0 && num.negative === 0) {
12915 res = this.neg().divmod(num, mode);
12916
12917 if (mode !== 'mod') {
12918 div = res.div.neg();
12919 }
12920
12921 if (mode !== 'div') {
12922 mod = res.mod.neg();
12923 if (positive && mod.negative !== 0) {
12924 mod.iadd(num);
12925 }
12926 }
12927
12928 return {
12929 div: div,
12930 mod: mod
12931 };
12932 }
12933
12934 if (this.negative === 0 && num.negative !== 0) {
12935 res = this.divmod(num.neg(), mode);
12936
12937 if (mode !== 'mod') {
12938 div = res.div.neg();
12939 }
12940
12941 return {
12942 div: div,
12943 mod: res.mod
12944 };
12945 }
12946
12947 if ((this.negative & num.negative) !== 0) {
12948 res = this.neg().divmod(num.neg(), mode);
12949
12950 if (mode !== 'div') {
12951 mod = res.mod.neg();
12952 if (positive && mod.negative !== 0) {
12953 mod.isub(num);
12954 }
12955 }
12956
12957 return {
12958 div: res.div,
12959 mod: mod
12960 };
12961 }
12962
12963 // Both numbers are positive at this point
12964
12965 // Strip both numbers to approximate shift value
12966 if (num.length > this.length || this.cmp(num) < 0) {
12967 return {
12968 div: new BN(0),
12969 mod: this
12970 };
12971 }
12972
12973 // Very short reduction
12974 if (num.length === 1) {
12975 if (mode === 'div') {
12976 return {
12977 div: this.divn(num.words[0]),
12978 mod: null
12979 };
12980 }
12981
12982 if (mode === 'mod') {
12983 return {
12984 div: null,
12985 mod: new BN(this.modn(num.words[0]))
12986 };
12987 }
12988
12989 return {
12990 div: this.divn(num.words[0]),
12991 mod: new BN(this.modn(num.words[0]))
12992 };
12993 }
12994
12995 return this._wordDiv(num, mode);
12996 };
12997
12998 // Find `this` / `num`
12999 BN.prototype.div = function div (num) {
13000 return this.divmod(num, 'div', false).div;
13001 };
13002
13003 // Find `this` % `num`
13004 BN.prototype.mod = function mod (num) {
13005 return this.divmod(num, 'mod', false).mod;
13006 };
13007
13008 BN.prototype.umod = function umod (num) {
13009 return this.divmod(num, 'mod', true).mod;
13010 };
13011
13012 // Find Round(`this` / `num`)
13013 BN.prototype.divRound = function divRound (num) {
13014 var dm = this.divmod(num);
13015
13016 // Fast case - exact division
13017 if (dm.mod.isZero()) return dm.div;
13018
13019 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
13020
13021 var half = num.ushrn(1);
13022 var r2 = num.andln(1);
13023 var cmp = mod.cmp(half);
13024
13025 // Round down
13026 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
13027
13028 // Round up
13029 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
13030 };
13031
13032 BN.prototype.modn = function modn (num) {
13033 assert(num <= 0x3ffffff);
13034 var p = (1 << 26) % num;
13035
13036 var acc = 0;
13037 for (var i = this.length - 1; i >= 0; i--) {
13038 acc = (p * acc + (this.words[i] | 0)) % num;
13039 }
13040
13041 return acc;
13042 };
13043
13044 // In-place division by number
13045 BN.prototype.idivn = function idivn (num) {
13046 assert(num <= 0x3ffffff);
13047
13048 var carry = 0;
13049 for (var i = this.length - 1; i >= 0; i--) {
13050 var w = (this.words[i] | 0) + carry * 0x4000000;
13051 this.words[i] = (w / num) | 0;
13052 carry = w % num;
13053 }
13054
13055 return this.strip();
13056 };
13057
13058 BN.prototype.divn = function divn (num) {
13059 return this.clone().idivn(num);
13060 };
13061
13062 BN.prototype.egcd = function egcd (p) {
13063 assert(p.negative === 0);
13064 assert(!p.isZero());
13065
13066 var x = this;
13067 var y = p.clone();
13068
13069 if (x.negative !== 0) {
13070 x = x.umod(p);
13071 } else {
13072 x = x.clone();
13073 }
13074
13075 // A * x + B * y = x
13076 var A = new BN(1);
13077 var B = new BN(0);
13078
13079 // C * x + D * y = y
13080 var C = new BN(0);
13081 var D = new BN(1);
13082
13083 var g = 0;
13084
13085 while (x.isEven() && y.isEven()) {
13086 x.iushrn(1);
13087 y.iushrn(1);
13088 ++g;
13089 }
13090
13091 var yp = y.clone();
13092 var xp = x.clone();
13093
13094 while (!x.isZero()) {
13095 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
13096 if (i > 0) {
13097 x.iushrn(i);
13098 while (i-- > 0) {
13099 if (A.isOdd() || B.isOdd()) {
13100 A.iadd(yp);
13101 B.isub(xp);
13102 }
13103
13104 A.iushrn(1);
13105 B.iushrn(1);
13106 }
13107 }
13108
13109 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
13110 if (j > 0) {
13111 y.iushrn(j);
13112 while (j-- > 0) {
13113 if (C.isOdd() || D.isOdd()) {
13114 C.iadd(yp);
13115 D.isub(xp);
13116 }
13117
13118 C.iushrn(1);
13119 D.iushrn(1);
13120 }
13121 }
13122
13123 if (x.cmp(y) >= 0) {
13124 x.isub(y);
13125 A.isub(C);
13126 B.isub(D);
13127 } else {
13128 y.isub(x);
13129 C.isub(A);
13130 D.isub(B);
13131 }
13132 }
13133
13134 return {
13135 a: C,
13136 b: D,
13137 gcd: y.iushln(g)
13138 };
13139 };
13140
13141 // This is reduced incarnation of the binary EEA
13142 // above, designated to invert members of the
13143 // _prime_ fields F(p) at a maximal speed
13144 BN.prototype._invmp = function _invmp (p) {
13145 assert(p.negative === 0);
13146 assert(!p.isZero());
13147
13148 var a = this;
13149 var b = p.clone();
13150
13151 if (a.negative !== 0) {
13152 a = a.umod(p);
13153 } else {
13154 a = a.clone();
13155 }
13156
13157 var x1 = new BN(1);
13158 var x2 = new BN(0);
13159
13160 var delta = b.clone();
13161
13162 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
13163 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
13164 if (i > 0) {
13165 a.iushrn(i);
13166 while (i-- > 0) {
13167 if (x1.isOdd()) {
13168 x1.iadd(delta);
13169 }
13170
13171 x1.iushrn(1);
13172 }
13173 }
13174
13175 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
13176 if (j > 0) {
13177 b.iushrn(j);
13178 while (j-- > 0) {
13179 if (x2.isOdd()) {
13180 x2.iadd(delta);
13181 }
13182
13183 x2.iushrn(1);
13184 }
13185 }
13186
13187 if (a.cmp(b) >= 0) {
13188 a.isub(b);
13189 x1.isub(x2);
13190 } else {
13191 b.isub(a);
13192 x2.isub(x1);
13193 }
13194 }
13195
13196 var res;
13197 if (a.cmpn(1) === 0) {
13198 res = x1;
13199 } else {
13200 res = x2;
13201 }
13202
13203 if (res.cmpn(0) < 0) {
13204 res.iadd(p);
13205 }
13206
13207 return res;
13208 };
13209
13210 BN.prototype.gcd = function gcd (num) {
13211 if (this.isZero()) return num.abs();
13212 if (num.isZero()) return this.abs();
13213
13214 var a = this.clone();
13215 var b = num.clone();
13216 a.negative = 0;
13217 b.negative = 0;
13218
13219 // Remove common factor of two
13220 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
13221 a.iushrn(1);
13222 b.iushrn(1);
13223 }
13224
13225 do {
13226 while (a.isEven()) {
13227 a.iushrn(1);
13228 }
13229 while (b.isEven()) {
13230 b.iushrn(1);
13231 }
13232
13233 var r = a.cmp(b);
13234 if (r < 0) {
13235 // Swap `a` and `b` to make `a` always bigger than `b`
13236 var t = a;
13237 a = b;
13238 b = t;
13239 } else if (r === 0 || b.cmpn(1) === 0) {
13240 break;
13241 }
13242
13243 a.isub(b);
13244 } while (true);
13245
13246 return b.iushln(shift);
13247 };
13248
13249 // Invert number in the field F(num)
13250 BN.prototype.invm = function invm (num) {
13251 return this.egcd(num).a.umod(num);
13252 };
13253
13254 BN.prototype.isEven = function isEven () {
13255 return (this.words[0] & 1) === 0;
13256 };
13257
13258 BN.prototype.isOdd = function isOdd () {
13259 return (this.words[0] & 1) === 1;
13260 };
13261
13262 // And first word and num
13263 BN.prototype.andln = function andln (num) {
13264 return this.words[0] & num;
13265 };
13266
13267 // Increment at the bit position in-line
13268 BN.prototype.bincn = function bincn (bit) {
13269 assert(typeof bit === 'number');
13270 var r = bit % 26;
13271 var s = (bit - r) / 26;
13272 var q = 1 << r;
13273
13274 // Fast case: bit is much higher than all existing words
13275 if (this.length <= s) {
13276 this._expand(s + 1);
13277 this.words[s] |= q;
13278 return this;
13279 }
13280
13281 // Add bit and propagate, if needed
13282 var carry = q;
13283 for (var i = s; carry !== 0 && i < this.length; i++) {
13284 var w = this.words[i] | 0;
13285 w += carry;
13286 carry = w >>> 26;
13287 w &= 0x3ffffff;
13288 this.words[i] = w;
13289 }
13290 if (carry !== 0) {
13291 this.words[i] = carry;
13292 this.length++;
13293 }
13294 return this;
13295 };
13296
13297 BN.prototype.isZero = function isZero () {
13298 return this.length === 1 && this.words[0] === 0;
13299 };
13300
13301 BN.prototype.cmpn = function cmpn (num) {
13302 var negative = num < 0;
13303
13304 if (this.negative !== 0 && !negative) return -1;
13305 if (this.negative === 0 && negative) return 1;
13306
13307 this.strip();
13308
13309 var res;
13310 if (this.length > 1) {
13311 res = 1;
13312 } else {
13313 if (negative) {
13314 num = -num;
13315 }
13316
13317 assert(num <= 0x3ffffff, 'Number is too big');
13318
13319 var w = this.words[0] | 0;
13320 res = w === num ? 0 : w < num ? -1 : 1;
13321 }
13322 if (this.negative !== 0) return -res | 0;
13323 return res;
13324 };
13325
13326 // Compare two numbers and return:
13327 // 1 - if `this` > `num`
13328 // 0 - if `this` == `num`
13329 // -1 - if `this` < `num`
13330 BN.prototype.cmp = function cmp (num) {
13331 if (this.negative !== 0 && num.negative === 0) return -1;
13332 if (this.negative === 0 && num.negative !== 0) return 1;
13333
13334 var res = this.ucmp(num);
13335 if (this.negative !== 0) return -res | 0;
13336 return res;
13337 };
13338
13339 // Unsigned comparison
13340 BN.prototype.ucmp = function ucmp (num) {
13341 // At this point both numbers have the same sign
13342 if (this.length > num.length) return 1;
13343 if (this.length < num.length) return -1;
13344
13345 var res = 0;
13346 for (var i = this.length - 1; i >= 0; i--) {
13347 var a = this.words[i] | 0;
13348 var b = num.words[i] | 0;
13349
13350 if (a === b) continue;
13351 if (a < b) {
13352 res = -1;
13353 } else if (a > b) {
13354 res = 1;
13355 }
13356 break;
13357 }
13358 return res;
13359 };
13360
13361 BN.prototype.gtn = function gtn (num) {
13362 return this.cmpn(num) === 1;
13363 };
13364
13365 BN.prototype.gt = function gt (num) {
13366 return this.cmp(num) === 1;
13367 };
13368
13369 BN.prototype.gten = function gten (num) {
13370 return this.cmpn(num) >= 0;
13371 };
13372
13373 BN.prototype.gte = function gte (num) {
13374 return this.cmp(num) >= 0;
13375 };
13376
13377 BN.prototype.ltn = function ltn (num) {
13378 return this.cmpn(num) === -1;
13379 };
13380
13381 BN.prototype.lt = function lt (num) {
13382 return this.cmp(num) === -1;
13383 };
13384
13385 BN.prototype.lten = function lten (num) {
13386 return this.cmpn(num) <= 0;
13387 };
13388
13389 BN.prototype.lte = function lte (num) {
13390 return this.cmp(num) <= 0;
13391 };
13392
13393 BN.prototype.eqn = function eqn (num) {
13394 return this.cmpn(num) === 0;
13395 };
13396
13397 BN.prototype.eq = function eq (num) {
13398 return this.cmp(num) === 0;
13399 };
13400
13401 //
13402 // A reduce context, could be using montgomery or something better, depending
13403 // on the `m` itself.
13404 //
13405 BN.red = function red (num) {
13406 return new Red(num);
13407 };
13408
13409 BN.prototype.toRed = function toRed (ctx) {
13410 assert(!this.red, 'Already a number in reduction context');
13411 assert(this.negative === 0, 'red works only with positives');
13412 return ctx.convertTo(this)._forceRed(ctx);
13413 };
13414
13415 BN.prototype.fromRed = function fromRed () {
13416 assert(this.red, 'fromRed works only with numbers in reduction context');
13417 return this.red.convertFrom(this);
13418 };
13419
13420 BN.prototype._forceRed = function _forceRed (ctx) {
13421 this.red = ctx;
13422 return this;
13423 };
13424
13425 BN.prototype.forceRed = function forceRed (ctx) {
13426 assert(!this.red, 'Already a number in reduction context');
13427 return this._forceRed(ctx);
13428 };
13429
13430 BN.prototype.redAdd = function redAdd (num) {
13431 assert(this.red, 'redAdd works only with red numbers');
13432 return this.red.add(this, num);
13433 };
13434
13435 BN.prototype.redIAdd = function redIAdd (num) {
13436 assert(this.red, 'redIAdd works only with red numbers');
13437 return this.red.iadd(this, num);
13438 };
13439
13440 BN.prototype.redSub = function redSub (num) {
13441 assert(this.red, 'redSub works only with red numbers');
13442 return this.red.sub(this, num);
13443 };
13444
13445 BN.prototype.redISub = function redISub (num) {
13446 assert(this.red, 'redISub works only with red numbers');
13447 return this.red.isub(this, num);
13448 };
13449
13450 BN.prototype.redShl = function redShl (num) {
13451 assert(this.red, 'redShl works only with red numbers');
13452 return this.red.shl(this, num);
13453 };
13454
13455 BN.prototype.redMul = function redMul (num) {
13456 assert(this.red, 'redMul works only with red numbers');
13457 this.red._verify2(this, num);
13458 return this.red.mul(this, num);
13459 };
13460
13461 BN.prototype.redIMul = function redIMul (num) {
13462 assert(this.red, 'redMul works only with red numbers');
13463 this.red._verify2(this, num);
13464 return this.red.imul(this, num);
13465 };
13466
13467 BN.prototype.redSqr = function redSqr () {
13468 assert(this.red, 'redSqr works only with red numbers');
13469 this.red._verify1(this);
13470 return this.red.sqr(this);
13471 };
13472
13473 BN.prototype.redISqr = function redISqr () {
13474 assert(this.red, 'redISqr works only with red numbers');
13475 this.red._verify1(this);
13476 return this.red.isqr(this);
13477 };
13478
13479 // Square root over p
13480 BN.prototype.redSqrt = function redSqrt () {
13481 assert(this.red, 'redSqrt works only with red numbers');
13482 this.red._verify1(this);
13483 return this.red.sqrt(this);
13484 };
13485
13486 BN.prototype.redInvm = function redInvm () {
13487 assert(this.red, 'redInvm works only with red numbers');
13488 this.red._verify1(this);
13489 return this.red.invm(this);
13490 };
13491
13492 // Return negative clone of `this` % `red modulo`
13493 BN.prototype.redNeg = function redNeg () {
13494 assert(this.red, 'redNeg works only with red numbers');
13495 this.red._verify1(this);
13496 return this.red.neg(this);
13497 };
13498
13499 BN.prototype.redPow = function redPow (num) {
13500 assert(this.red && !num.red, 'redPow(normalNum)');
13501 this.red._verify1(this);
13502 return this.red.pow(this, num);
13503 };
13504
13505 // Prime numbers with efficient reduction
13506 var primes = {
13507 k256: null,
13508 p224: null,
13509 p192: null,
13510 p25519: null
13511 };
13512
13513 // Pseudo-Mersenne prime
13514 function MPrime (name, p) {
13515 // P = 2 ^ N - K
13516 this.name = name;
13517 this.p = new BN(p, 16);
13518 this.n = this.p.bitLength();
13519 this.k = new BN(1).iushln(this.n).isub(this.p);
13520
13521 this.tmp = this._tmp();
13522 }
13523
13524 MPrime.prototype._tmp = function _tmp () {
13525 var tmp = new BN(null);
13526 tmp.words = new Array(Math.ceil(this.n / 13));
13527 return tmp;
13528 };
13529
13530 MPrime.prototype.ireduce = function ireduce (num) {
13531 // Assumes that `num` is less than `P^2`
13532 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
13533 var r = num;
13534 var rlen;
13535
13536 do {
13537 this.split(r, this.tmp);
13538 r = this.imulK(r);
13539 r = r.iadd(this.tmp);
13540 rlen = r.bitLength();
13541 } while (rlen > this.n);
13542
13543 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
13544 if (cmp === 0) {
13545 r.words[0] = 0;
13546 r.length = 1;
13547 } else if (cmp > 0) {
13548 r.isub(this.p);
13549 } else {
13550 if (r.strip !== undefined) {
13551 // r is BN v4 instance
13552 r.strip();
13553 } else {
13554 // r is BN v5 instance
13555 r._strip();
13556 }
13557 }
13558
13559 return r;
13560 };
13561
13562 MPrime.prototype.split = function split (input, out) {
13563 input.iushrn(this.n, 0, out);
13564 };
13565
13566 MPrime.prototype.imulK = function imulK (num) {
13567 return num.imul(this.k);
13568 };
13569
13570 function K256 () {
13571 MPrime.call(
13572 this,
13573 'k256',
13574 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
13575 }
13576 inherits(K256, MPrime);
13577
13578 K256.prototype.split = function split (input, output) {
13579 // 256 = 9 * 26 + 22
13580 var mask = 0x3fffff;
13581
13582 var outLen = Math.min(input.length, 9);
13583 for (var i = 0; i < outLen; i++) {
13584 output.words[i] = input.words[i];
13585 }
13586 output.length = outLen;
13587
13588 if (input.length <= 9) {
13589 input.words[0] = 0;
13590 input.length = 1;
13591 return;
13592 }
13593
13594 // Shift by 9 limbs
13595 var prev = input.words[9];
13596 output.words[output.length++] = prev & mask;
13597
13598 for (i = 10; i < input.length; i++) {
13599 var next = input.words[i] | 0;
13600 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
13601 prev = next;
13602 }
13603 prev >>>= 22;
13604 input.words[i - 10] = prev;
13605 if (prev === 0 && input.length > 10) {
13606 input.length -= 10;
13607 } else {
13608 input.length -= 9;
13609 }
13610 };
13611
13612 K256.prototype.imulK = function imulK (num) {
13613 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
13614 num.words[num.length] = 0;
13615 num.words[num.length + 1] = 0;
13616 num.length += 2;
13617
13618 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
13619 var lo = 0;
13620 for (var i = 0; i < num.length; i++) {
13621 var w = num.words[i] | 0;
13622 lo += w * 0x3d1;
13623 num.words[i] = lo & 0x3ffffff;
13624 lo = w * 0x40 + ((lo / 0x4000000) | 0);
13625 }
13626
13627 // Fast length reduction
13628 if (num.words[num.length - 1] === 0) {
13629 num.length--;
13630 if (num.words[num.length - 1] === 0) {
13631 num.length--;
13632 }
13633 }
13634 return num;
13635 };
13636
13637 function P224 () {
13638 MPrime.call(
13639 this,
13640 'p224',
13641 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
13642 }
13643 inherits(P224, MPrime);
13644
13645 function P192 () {
13646 MPrime.call(
13647 this,
13648 'p192',
13649 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
13650 }
13651 inherits(P192, MPrime);
13652
13653 function P25519 () {
13654 // 2 ^ 255 - 19
13655 MPrime.call(
13656 this,
13657 '25519',
13658 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
13659 }
13660 inherits(P25519, MPrime);
13661
13662 P25519.prototype.imulK = function imulK (num) {
13663 // K = 0x13
13664 var carry = 0;
13665 for (var i = 0; i < num.length; i++) {
13666 var hi = (num.words[i] | 0) * 0x13 + carry;
13667 var lo = hi & 0x3ffffff;
13668 hi >>>= 26;
13669
13670 num.words[i] = lo;
13671 carry = hi;
13672 }
13673 if (carry !== 0) {
13674 num.words[num.length++] = carry;
13675 }
13676 return num;
13677 };
13678
13679 // Exported mostly for testing purposes, use plain name instead
13680 BN._prime = function prime (name) {
13681 // Cached version of prime
13682 if (primes[name]) return primes[name];
13683
13684 var prime;
13685 if (name === 'k256') {
13686 prime = new K256();
13687 } else if (name === 'p224') {
13688 prime = new P224();
13689 } else if (name === 'p192') {
13690 prime = new P192();
13691 } else if (name === 'p25519') {
13692 prime = new P25519();
13693 } else {
13694 throw new Error('Unknown prime ' + name);
13695 }
13696 primes[name] = prime;
13697
13698 return prime;
13699 };
13700
13701 //
13702 // Base reduction engine
13703 //
13704 function Red (m) {
13705 if (typeof m === 'string') {
13706 var prime = BN._prime(m);
13707 this.m = prime.p;
13708 this.prime = prime;
13709 } else {
13710 assert(m.gtn(1), 'modulus must be greater than 1');
13711 this.m = m;
13712 this.prime = null;
13713 }
13714 }
13715
13716 Red.prototype._verify1 = function _verify1 (a) {
13717 assert(a.negative === 0, 'red works only with positives');
13718 assert(a.red, 'red works only with red numbers');
13719 };
13720
13721 Red.prototype._verify2 = function _verify2 (a, b) {
13722 assert((a.negative | b.negative) === 0, 'red works only with positives');
13723 assert(a.red && a.red === b.red,
13724 'red works only with red numbers');
13725 };
13726
13727 Red.prototype.imod = function imod (a) {
13728 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
13729 return a.umod(this.m)._forceRed(this);
13730 };
13731
13732 Red.prototype.neg = function neg (a) {
13733 if (a.isZero()) {
13734 return a.clone();
13735 }
13736
13737 return this.m.sub(a)._forceRed(this);
13738 };
13739
13740 Red.prototype.add = function add (a, b) {
13741 this._verify2(a, b);
13742
13743 var res = a.add(b);
13744 if (res.cmp(this.m) >= 0) {
13745 res.isub(this.m);
13746 }
13747 return res._forceRed(this);
13748 };
13749
13750 Red.prototype.iadd = function iadd (a, b) {
13751 this._verify2(a, b);
13752
13753 var res = a.iadd(b);
13754 if (res.cmp(this.m) >= 0) {
13755 res.isub(this.m);
13756 }
13757 return res;
13758 };
13759
13760 Red.prototype.sub = function sub (a, b) {
13761 this._verify2(a, b);
13762
13763 var res = a.sub(b);
13764 if (res.cmpn(0) < 0) {
13765 res.iadd(this.m);
13766 }
13767 return res._forceRed(this);
13768 };
13769
13770 Red.prototype.isub = function isub (a, b) {
13771 this._verify2(a, b);
13772
13773 var res = a.isub(b);
13774 if (res.cmpn(0) < 0) {
13775 res.iadd(this.m);
13776 }
13777 return res;
13778 };
13779
13780 Red.prototype.shl = function shl (a, num) {
13781 this._verify1(a);
13782 return this.imod(a.ushln(num));
13783 };
13784
13785 Red.prototype.imul = function imul (a, b) {
13786 this._verify2(a, b);
13787 return this.imod(a.imul(b));
13788 };
13789
13790 Red.prototype.mul = function mul (a, b) {
13791 this._verify2(a, b);
13792 return this.imod(a.mul(b));
13793 };
13794
13795 Red.prototype.isqr = function isqr (a) {
13796 return this.imul(a, a.clone());
13797 };
13798
13799 Red.prototype.sqr = function sqr (a) {
13800 return this.mul(a, a);
13801 };
13802
13803 Red.prototype.sqrt = function sqrt (a) {
13804 if (a.isZero()) return a.clone();
13805
13806 var mod3 = this.m.andln(3);
13807 assert(mod3 % 2 === 1);
13808
13809 // Fast case
13810 if (mod3 === 3) {
13811 var pow = this.m.add(new BN(1)).iushrn(2);
13812 return this.pow(a, pow);
13813 }
13814
13815 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
13816 //
13817 // Find Q and S, that Q * 2 ^ S = (P - 1)
13818 var q = this.m.subn(1);
13819 var s = 0;
13820 while (!q.isZero() && q.andln(1) === 0) {
13821 s++;
13822 q.iushrn(1);
13823 }
13824 assert(!q.isZero());
13825
13826 var one = new BN(1).toRed(this);
13827 var nOne = one.redNeg();
13828
13829 // Find quadratic non-residue
13830 // NOTE: Max is such because of generalized Riemann hypothesis.
13831 var lpow = this.m.subn(1).iushrn(1);
13832 var z = this.m.bitLength();
13833 z = new BN(2 * z * z).toRed(this);
13834
13835 while (this.pow(z, lpow).cmp(nOne) !== 0) {
13836 z.redIAdd(nOne);
13837 }
13838
13839 var c = this.pow(z, q);
13840 var r = this.pow(a, q.addn(1).iushrn(1));
13841 var t = this.pow(a, q);
13842 var m = s;
13843 while (t.cmp(one) !== 0) {
13844 var tmp = t;
13845 for (var i = 0; tmp.cmp(one) !== 0; i++) {
13846 tmp = tmp.redSqr();
13847 }
13848 assert(i < m);
13849 var b = this.pow(c, new BN(1).iushln(m - i - 1));
13850
13851 r = r.redMul(b);
13852 c = b.redSqr();
13853 t = t.redMul(c);
13854 m = i;
13855 }
13856
13857 return r;
13858 };
13859
13860 Red.prototype.invm = function invm (a) {
13861 var inv = a._invmp(this.m);
13862 if (inv.negative !== 0) {
13863 inv.negative = 0;
13864 return this.imod(inv).redNeg();
13865 } else {
13866 return this.imod(inv);
13867 }
13868 };
13869
13870 Red.prototype.pow = function pow (a, num) {
13871 if (num.isZero()) return new BN(1).toRed(this);
13872 if (num.cmpn(1) === 0) return a.clone();
13873
13874 var windowSize = 4;
13875 var wnd = new Array(1 << windowSize);
13876 wnd[0] = new BN(1).toRed(this);
13877 wnd[1] = a;
13878 for (var i = 2; i < wnd.length; i++) {
13879 wnd[i] = this.mul(wnd[i - 1], a);
13880 }
13881
13882 var res = wnd[0];
13883 var current = 0;
13884 var currentLen = 0;
13885 var start = num.bitLength() % 26;
13886 if (start === 0) {
13887 start = 26;
13888 }
13889
13890 for (i = num.length - 1; i >= 0; i--) {
13891 var word = num.words[i];
13892 for (var j = start - 1; j >= 0; j--) {
13893 var bit = (word >> j) & 1;
13894 if (res !== wnd[0]) {
13895 res = this.sqr(res);
13896 }
13897
13898 if (bit === 0 && current === 0) {
13899 currentLen = 0;
13900 continue;
13901 }
13902
13903 current <<= 1;
13904 current |= bit;
13905 currentLen++;
13906 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
13907
13908 res = this.mul(res, wnd[current]);
13909 currentLen = 0;
13910 current = 0;
13911 }
13912 start = 26;
13913 }
13914
13915 return res;
13916 };
13917
13918 Red.prototype.convertTo = function convertTo (num) {
13919 var r = num.umod(this.m);
13920
13921 return r === num ? r.clone() : r;
13922 };
13923
13924 Red.prototype.convertFrom = function convertFrom (num) {
13925 var res = num.clone();
13926 res.red = null;
13927 return res;
13928 };
13929
13930 //
13931 // Montgomery method engine
13932 //
13933
13934 BN.mont = function mont (num) {
13935 return new Mont(num);
13936 };
13937
13938 function Mont (m) {
13939 Red.call(this, m);
13940
13941 this.shift = this.m.bitLength();
13942 if (this.shift % 26 !== 0) {
13943 this.shift += 26 - (this.shift % 26);
13944 }
13945
13946 this.r = new BN(1).iushln(this.shift);
13947 this.r2 = this.imod(this.r.sqr());
13948 this.rinv = this.r._invmp(this.m);
13949
13950 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
13951 this.minv = this.minv.umod(this.r);
13952 this.minv = this.r.sub(this.minv);
13953 }
13954 inherits(Mont, Red);
13955
13956 Mont.prototype.convertTo = function convertTo (num) {
13957 return this.imod(num.ushln(this.shift));
13958 };
13959
13960 Mont.prototype.convertFrom = function convertFrom (num) {
13961 var r = this.imod(num.mul(this.rinv));
13962 r.red = null;
13963 return r;
13964 };
13965
13966 Mont.prototype.imul = function imul (a, b) {
13967 if (a.isZero() || b.isZero()) {
13968 a.words[0] = 0;
13969 a.length = 1;
13970 return a;
13971 }
13972
13973 var t = a.imul(b);
13974 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
13975 var u = t.isub(c).iushrn(this.shift);
13976 var res = u;
13977
13978 if (u.cmp(this.m) >= 0) {
13979 res = u.isub(this.m);
13980 } else if (u.cmpn(0) < 0) {
13981 res = u.iadd(this.m);
13982 }
13983
13984 return res._forceRed(this);
13985 };
13986
13987 Mont.prototype.mul = function mul (a, b) {
13988 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
13989
13990 var t = a.mul(b);
13991 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
13992 var u = t.isub(c).iushrn(this.shift);
13993 var res = u;
13994 if (u.cmp(this.m) >= 0) {
13995 res = u.isub(this.m);
13996 } else if (u.cmpn(0) < 0) {
13997 res = u.iadd(this.m);
13998 }
13999
14000 return res._forceRed(this);
14001 };
14002
14003 Mont.prototype.invm = function invm (a) {
14004 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
14005 var res = this.imod(a._invmp(this.m).mul(this.r2));
14006 return res._forceRed(this);
14007 };
14008})('object' === 'undefined' || module, commonjsGlobal);
14009});
14010
14011var utils_1 = createCommonjsModule(function (module, exports) {
14012'use strict';
14013
14014var utils = exports;
14015
14016function toArray(msg, enc) {
14017 if (Array.isArray(msg))
14018 return msg.slice();
14019 if (!msg)
14020 return [];
14021 var res = [];
14022 if (typeof msg !== 'string') {
14023 for (var i = 0; i < msg.length; i++)
14024 res[i] = msg[i] | 0;
14025 return res;
14026 }
14027 if (enc === 'hex') {
14028 msg = msg.replace(/[^a-z0-9]+/ig, '');
14029 if (msg.length % 2 !== 0)
14030 msg = '0' + msg;
14031 for (var i = 0; i < msg.length; i += 2)
14032 res.push(parseInt(msg[i] + msg[i + 1], 16));
14033 } else {
14034 for (var i = 0; i < msg.length; i++) {
14035 var c = msg.charCodeAt(i);
14036 var hi = c >> 8;
14037 var lo = c & 0xff;
14038 if (hi)
14039 res.push(hi, lo);
14040 else
14041 res.push(lo);
14042 }
14043 }
14044 return res;
14045}
14046utils.toArray = toArray;
14047
14048function zero2(word) {
14049 if (word.length === 1)
14050 return '0' + word;
14051 else
14052 return word;
14053}
14054utils.zero2 = zero2;
14055
14056function toHex(msg) {
14057 var res = '';
14058 for (var i = 0; i < msg.length; i++)
14059 res += zero2(msg[i].toString(16));
14060 return res;
14061}
14062utils.toHex = toHex;
14063
14064utils.encode = function encode(arr, enc) {
14065 if (enc === 'hex')
14066 return toHex(arr);
14067 else
14068 return arr;
14069};
14070});
14071
14072var utils_1$1 = createCommonjsModule(function (module, exports) {
14073'use strict';
14074
14075var utils = exports;
14076
14077
14078
14079
14080utils.assert = minimalisticAssert;
14081utils.toArray = utils_1.toArray;
14082utils.zero2 = utils_1.zero2;
14083utils.toHex = utils_1.toHex;
14084utils.encode = utils_1.encode;
14085
14086// Represent num in a w-NAF form
14087function getNAF(num, w, bits) {
14088 var naf = new Array(Math.max(num.bitLength(), bits) + 1);
14089 naf.fill(0);
14090
14091 var ws = 1 << (w + 1);
14092 var k = num.clone();
14093
14094 for (var i = 0; i < naf.length; i++) {
14095 var z;
14096 var mod = k.andln(ws - 1);
14097 if (k.isOdd()) {
14098 if (mod > (ws >> 1) - 1)
14099 z = (ws >> 1) - mod;
14100 else
14101 z = mod;
14102 k.isubn(z);
14103 } else {
14104 z = 0;
14105 }
14106
14107 naf[i] = z;
14108 k.iushrn(1);
14109 }
14110
14111 return naf;
14112}
14113utils.getNAF = getNAF;
14114
14115// Represent k1, k2 in a Joint Sparse Form
14116function getJSF(k1, k2) {
14117 var jsf = [
14118 [],
14119 []
14120 ];
14121
14122 k1 = k1.clone();
14123 k2 = k2.clone();
14124 var d1 = 0;
14125 var d2 = 0;
14126 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
14127
14128 // First phase
14129 var m14 = (k1.andln(3) + d1) & 3;
14130 var m24 = (k2.andln(3) + d2) & 3;
14131 if (m14 === 3)
14132 m14 = -1;
14133 if (m24 === 3)
14134 m24 = -1;
14135 var u1;
14136 if ((m14 & 1) === 0) {
14137 u1 = 0;
14138 } else {
14139 var m8 = (k1.andln(7) + d1) & 7;
14140 if ((m8 === 3 || m8 === 5) && m24 === 2)
14141 u1 = -m14;
14142 else
14143 u1 = m14;
14144 }
14145 jsf[0].push(u1);
14146
14147 var u2;
14148 if ((m24 & 1) === 0) {
14149 u2 = 0;
14150 } else {
14151 var m8 = (k2.andln(7) + d2) & 7;
14152 if ((m8 === 3 || m8 === 5) && m14 === 2)
14153 u2 = -m24;
14154 else
14155 u2 = m24;
14156 }
14157 jsf[1].push(u2);
14158
14159 // Second phase
14160 if (2 * d1 === u1 + 1)
14161 d1 = 1 - d1;
14162 if (2 * d2 === u2 + 1)
14163 d2 = 1 - d2;
14164 k1.iushrn(1);
14165 k2.iushrn(1);
14166 }
14167
14168 return jsf;
14169}
14170utils.getJSF = getJSF;
14171
14172function cachedProperty(obj, name, computer) {
14173 var key = '_' + name;
14174 obj.prototype[name] = function cachedProperty() {
14175 return this[key] !== undefined ? this[key] :
14176 this[key] = computer.call(this);
14177 };
14178}
14179utils.cachedProperty = cachedProperty;
14180
14181function parseBytes(bytes) {
14182 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
14183 bytes;
14184}
14185utils.parseBytes = parseBytes;
14186
14187function intFromLE(bytes) {
14188 return new bn$1(bytes, 'hex', 'le');
14189}
14190utils.intFromLE = intFromLE;
14191});
14192
14193var brorand = function(length) { var result = new Uint8Array(length); (commonjsGlobal.crypto || commonjsGlobal.msCrypto).getRandomValues(result); return result; };
14194
14195'use strict';
14196
14197
14198
14199var getNAF = utils_1$1.getNAF;
14200var getJSF = utils_1$1.getJSF;
14201var assert$1 = utils_1$1.assert;
14202
14203function BaseCurve(type, conf) {
14204 this.type = type;
14205 this.p = new bn$1(conf.p, 16);
14206
14207 // Use Montgomery, when there is no fast reduction for the prime
14208 this.red = conf.prime ? bn$1.red(conf.prime) : bn$1.mont(this.p);
14209
14210 // Useful for many curves
14211 this.zero = new bn$1(0).toRed(this.red);
14212 this.one = new bn$1(1).toRed(this.red);
14213 this.two = new bn$1(2).toRed(this.red);
14214
14215 // Curve configuration, optional
14216 this.n = conf.n && new bn$1(conf.n, 16);
14217 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
14218
14219 // Temporary arrays
14220 this._wnafT1 = new Array(4);
14221 this._wnafT2 = new Array(4);
14222 this._wnafT3 = new Array(4);
14223 this._wnafT4 = new Array(4);
14224
14225 this._bitLength = this.n ? this.n.bitLength() : 0;
14226
14227 // Generalized Greg Maxwell's trick
14228 var adjustCount = this.n && this.p.div(this.n);
14229 if (!adjustCount || adjustCount.cmpn(100) > 0) {
14230 this.redN = null;
14231 } else {
14232 this._maxwellTrick = true;
14233 this.redN = this.n.toRed(this.red);
14234 }
14235}
14236var base = BaseCurve;
14237
14238BaseCurve.prototype.point = function point() {
14239 throw new Error('Not implemented');
14240};
14241
14242BaseCurve.prototype.validate = function validate() {
14243 throw new Error('Not implemented');
14244};
14245
14246BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
14247 assert$1(p.precomputed);
14248 var doubles = p._getDoubles();
14249
14250 var naf = getNAF(k, 1, this._bitLength);
14251 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
14252 I /= 3;
14253
14254 // Translate into more windowed form
14255 var repr = [];
14256 for (var j = 0; j < naf.length; j += doubles.step) {
14257 var nafW = 0;
14258 for (var k = j + doubles.step - 1; k >= j; k--)
14259 nafW = (nafW << 1) + naf[k];
14260 repr.push(nafW);
14261 }
14262
14263 var a = this.jpoint(null, null, null);
14264 var b = this.jpoint(null, null, null);
14265 for (var i = I; i > 0; i--) {
14266 for (var j = 0; j < repr.length; j++) {
14267 var nafW = repr[j];
14268 if (nafW === i)
14269 b = b.mixedAdd(doubles.points[j]);
14270 else if (nafW === -i)
14271 b = b.mixedAdd(doubles.points[j].neg());
14272 }
14273 a = a.add(b);
14274 }
14275 return a.toP();
14276};
14277
14278BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
14279 var w = 4;
14280
14281 // Precompute window
14282 var nafPoints = p._getNAFPoints(w);
14283 w = nafPoints.wnd;
14284 var wnd = nafPoints.points;
14285
14286 // Get NAF form
14287 var naf = getNAF(k, w, this._bitLength);
14288
14289 // Add `this`*(N+1) for every w-NAF index
14290 var acc = this.jpoint(null, null, null);
14291 for (var i = naf.length - 1; i >= 0; i--) {
14292 // Count zeroes
14293 for (var k = 0; i >= 0 && naf[i] === 0; i--)
14294 k++;
14295 if (i >= 0)
14296 k++;
14297 acc = acc.dblp(k);
14298
14299 if (i < 0)
14300 break;
14301 var z = naf[i];
14302 assert$1(z !== 0);
14303 if (p.type === 'affine') {
14304 // J +- P
14305 if (z > 0)
14306 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
14307 else
14308 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
14309 } else {
14310 // J +- J
14311 if (z > 0)
14312 acc = acc.add(wnd[(z - 1) >> 1]);
14313 else
14314 acc = acc.add(wnd[(-z - 1) >> 1].neg());
14315 }
14316 }
14317 return p.type === 'affine' ? acc.toP() : acc;
14318};
14319
14320BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
14321 points,
14322 coeffs,
14323 len,
14324 jacobianResult) {
14325 var wndWidth = this._wnafT1;
14326 var wnd = this._wnafT2;
14327 var naf = this._wnafT3;
14328
14329 // Fill all arrays
14330 var max = 0;
14331 for (var i = 0; i < len; i++) {
14332 var p = points[i];
14333 var nafPoints = p._getNAFPoints(defW);
14334 wndWidth[i] = nafPoints.wnd;
14335 wnd[i] = nafPoints.points;
14336 }
14337
14338 // Comb small window NAFs
14339 for (var i = len - 1; i >= 1; i -= 2) {
14340 var a = i - 1;
14341 var b = i;
14342 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
14343 naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
14344 naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
14345 max = Math.max(naf[a].length, max);
14346 max = Math.max(naf[b].length, max);
14347 continue;
14348 }
14349
14350 var comb = [
14351 points[a], /* 1 */
14352 null, /* 3 */
14353 null, /* 5 */
14354 points[b] /* 7 */
14355 ];
14356
14357 // Try to avoid Projective points, if possible
14358 if (points[a].y.cmp(points[b].y) === 0) {
14359 comb[1] = points[a].add(points[b]);
14360 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
14361 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
14362 comb[1] = points[a].toJ().mixedAdd(points[b]);
14363 comb[2] = points[a].add(points[b].neg());
14364 } else {
14365 comb[1] = points[a].toJ().mixedAdd(points[b]);
14366 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
14367 }
14368
14369 var index = [
14370 -3, /* -1 -1 */
14371 -1, /* -1 0 */
14372 -5, /* -1 1 */
14373 -7, /* 0 -1 */
14374 0, /* 0 0 */
14375 7, /* 0 1 */
14376 5, /* 1 -1 */
14377 1, /* 1 0 */
14378 3 /* 1 1 */
14379 ];
14380
14381 var jsf = getJSF(coeffs[a], coeffs[b]);
14382 max = Math.max(jsf[0].length, max);
14383 naf[a] = new Array(max);
14384 naf[b] = new Array(max);
14385 for (var j = 0; j < max; j++) {
14386 var ja = jsf[0][j] | 0;
14387 var jb = jsf[1][j] | 0;
14388
14389 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
14390 naf[b][j] = 0;
14391 wnd[a] = comb;
14392 }
14393 }
14394
14395 var acc = this.jpoint(null, null, null);
14396 var tmp = this._wnafT4;
14397 for (var i = max; i >= 0; i--) {
14398 var k = 0;
14399
14400 while (i >= 0) {
14401 var zero = true;
14402 for (var j = 0; j < len; j++) {
14403 tmp[j] = naf[j][i] | 0;
14404 if (tmp[j] !== 0)
14405 zero = false;
14406 }
14407 if (!zero)
14408 break;
14409 k++;
14410 i--;
14411 }
14412 if (i >= 0)
14413 k++;
14414 acc = acc.dblp(k);
14415 if (i < 0)
14416 break;
14417
14418 for (var j = 0; j < len; j++) {
14419 var z = tmp[j];
14420 var p;
14421 if (z === 0)
14422 continue;
14423 else if (z > 0)
14424 p = wnd[j][(z - 1) >> 1];
14425 else if (z < 0)
14426 p = wnd[j][(-z - 1) >> 1].neg();
14427
14428 if (p.type === 'affine')
14429 acc = acc.mixedAdd(p);
14430 else
14431 acc = acc.add(p);
14432 }
14433 }
14434 // Zeroify references
14435 for (var i = 0; i < len; i++)
14436 wnd[i] = null;
14437
14438 if (jacobianResult)
14439 return acc;
14440 else
14441 return acc.toP();
14442};
14443
14444function BasePoint(curve, type) {
14445 this.curve = curve;
14446 this.type = type;
14447 this.precomputed = null;
14448}
14449BaseCurve.BasePoint = BasePoint;
14450
14451BasePoint.prototype.eq = function eq(/*other*/) {
14452 throw new Error('Not implemented');
14453};
14454
14455BasePoint.prototype.validate = function validate() {
14456 return this.curve.validate(this);
14457};
14458
14459BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
14460 bytes = utils_1$1.toArray(bytes, enc);
14461
14462 var len = this.p.byteLength();
14463
14464 // uncompressed, hybrid-odd, hybrid-even
14465 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
14466 bytes.length - 1 === 2 * len) {
14467 if (bytes[0] === 0x06)
14468 assert$1(bytes[bytes.length - 1] % 2 === 0);
14469 else if (bytes[0] === 0x07)
14470 assert$1(bytes[bytes.length - 1] % 2 === 1);
14471
14472 var res = this.point(bytes.slice(1, 1 + len),
14473 bytes.slice(1 + len, 1 + 2 * len));
14474
14475 return res;
14476 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
14477 bytes.length - 1 === len) {
14478 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
14479 }
14480 throw new Error('Unknown point format');
14481};
14482
14483BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
14484 return this.encode(enc, true);
14485};
14486
14487BasePoint.prototype._encode = function _encode(compact) {
14488 var len = this.curve.p.byteLength();
14489 var x = this.getX().toArray('be', len);
14490
14491 if (compact)
14492 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
14493
14494 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
14495};
14496
14497BasePoint.prototype.encode = function encode(enc, compact) {
14498 return utils_1$1.encode(this._encode(compact), enc);
14499};
14500
14501BasePoint.prototype.precompute = function precompute(power) {
14502 if (this.precomputed)
14503 return this;
14504
14505 var precomputed = {
14506 doubles: null,
14507 naf: null,
14508 beta: null
14509 };
14510 precomputed.naf = this._getNAFPoints(8);
14511 precomputed.doubles = this._getDoubles(4, power);
14512 precomputed.beta = this._getBeta();
14513 this.precomputed = precomputed;
14514
14515 return this;
14516};
14517
14518BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
14519 if (!this.precomputed)
14520 return false;
14521
14522 var doubles = this.precomputed.doubles;
14523 if (!doubles)
14524 return false;
14525
14526 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
14527};
14528
14529BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
14530 if (this.precomputed && this.precomputed.doubles)
14531 return this.precomputed.doubles;
14532
14533 var doubles = [ this ];
14534 var acc = this;
14535 for (var i = 0; i < power; i += step) {
14536 for (var j = 0; j < step; j++)
14537 acc = acc.dbl();
14538 doubles.push(acc);
14539 }
14540 return {
14541 step: step,
14542 points: doubles
14543 };
14544};
14545
14546BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
14547 if (this.precomputed && this.precomputed.naf)
14548 return this.precomputed.naf;
14549
14550 var res = [ this ];
14551 var max = (1 << wnd) - 1;
14552 var dbl = max === 1 ? null : this.dbl();
14553 for (var i = 1; i < max; i++)
14554 res[i] = res[i - 1].add(dbl);
14555 return {
14556 wnd: wnd,
14557 points: res
14558 };
14559};
14560
14561BasePoint.prototype._getBeta = function _getBeta() {
14562 return null;
14563};
14564
14565BasePoint.prototype.dblp = function dblp(k) {
14566 var r = this;
14567 for (var i = 0; i < k; i++)
14568 r = r.dbl();
14569 return r;
14570};
14571
14572'use strict';
14573
14574
14575
14576
14577
14578
14579var assert$2 = utils_1$1.assert;
14580
14581function ShortCurve(conf) {
14582 base.call(this, 'short', conf);
14583
14584 this.a = new bn$1(conf.a, 16).toRed(this.red);
14585 this.b = new bn$1(conf.b, 16).toRed(this.red);
14586 this.tinv = this.two.redInvm();
14587
14588 this.zeroA = this.a.fromRed().cmpn(0) === 0;
14589 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
14590
14591 // If the curve is endomorphic, precalculate beta and lambda
14592 this.endo = this._getEndomorphism(conf);
14593 this._endoWnafT1 = new Array(4);
14594 this._endoWnafT2 = new Array(4);
14595}
14596inherits_browser(ShortCurve, base);
14597var short_1 = ShortCurve;
14598
14599ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
14600 // No efficient endomorphism
14601 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
14602 return;
14603
14604 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
14605 var beta;
14606 var lambda;
14607 if (conf.beta) {
14608 beta = new bn$1(conf.beta, 16).toRed(this.red);
14609 } else {
14610 var betas = this._getEndoRoots(this.p);
14611 // Choose the smallest beta
14612 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
14613 beta = beta.toRed(this.red);
14614 }
14615 if (conf.lambda) {
14616 lambda = new bn$1(conf.lambda, 16);
14617 } else {
14618 // Choose the lambda that is matching selected beta
14619 var lambdas = this._getEndoRoots(this.n);
14620 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
14621 lambda = lambdas[0];
14622 } else {
14623 lambda = lambdas[1];
14624 assert$2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
14625 }
14626 }
14627
14628 // Get basis vectors, used for balanced length-two representation
14629 var basis;
14630 if (conf.basis) {
14631 basis = conf.basis.map(function(vec) {
14632 return {
14633 a: new bn$1(vec.a, 16),
14634 b: new bn$1(vec.b, 16)
14635 };
14636 });
14637 } else {
14638 basis = this._getEndoBasis(lambda);
14639 }
14640
14641 return {
14642 beta: beta,
14643 lambda: lambda,
14644 basis: basis
14645 };
14646};
14647
14648ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
14649 // Find roots of for x^2 + x + 1 in F
14650 // Root = (-1 +- Sqrt(-3)) / 2
14651 //
14652 var red = num === this.p ? this.red : bn$1.mont(num);
14653 var tinv = new bn$1(2).toRed(red).redInvm();
14654 var ntinv = tinv.redNeg();
14655
14656 var s = new bn$1(3).toRed(red).redNeg().redSqrt().redMul(tinv);
14657
14658 var l1 = ntinv.redAdd(s).fromRed();
14659 var l2 = ntinv.redSub(s).fromRed();
14660 return [ l1, l2 ];
14661};
14662
14663ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
14664 // aprxSqrt >= sqrt(this.n)
14665 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
14666
14667 // 3.74
14668 // Run EGCD, until r(L + 1) < aprxSqrt
14669 var u = lambda;
14670 var v = this.n.clone();
14671 var x1 = new bn$1(1);
14672 var y1 = new bn$1(0);
14673 var x2 = new bn$1(0);
14674 var y2 = new bn$1(1);
14675
14676 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
14677 var a0;
14678 var b0;
14679 // First vector
14680 var a1;
14681 var b1;
14682 // Second vector
14683 var a2;
14684 var b2;
14685
14686 var prevR;
14687 var i = 0;
14688 var r;
14689 var x;
14690 while (u.cmpn(0) !== 0) {
14691 var q = v.div(u);
14692 r = v.sub(q.mul(u));
14693 x = x2.sub(q.mul(x1));
14694 var y = y2.sub(q.mul(y1));
14695
14696 if (!a1 && r.cmp(aprxSqrt) < 0) {
14697 a0 = prevR.neg();
14698 b0 = x1;
14699 a1 = r.neg();
14700 b1 = x;
14701 } else if (a1 && ++i === 2) {
14702 break;
14703 }
14704 prevR = r;
14705
14706 v = u;
14707 u = r;
14708 x2 = x1;
14709 x1 = x;
14710 y2 = y1;
14711 y1 = y;
14712 }
14713 a2 = r.neg();
14714 b2 = x;
14715
14716 var len1 = a1.sqr().add(b1.sqr());
14717 var len2 = a2.sqr().add(b2.sqr());
14718 if (len2.cmp(len1) >= 0) {
14719 a2 = a0;
14720 b2 = b0;
14721 }
14722
14723 // Normalize signs
14724 if (a1.negative) {
14725 a1 = a1.neg();
14726 b1 = b1.neg();
14727 }
14728 if (a2.negative) {
14729 a2 = a2.neg();
14730 b2 = b2.neg();
14731 }
14732
14733 return [
14734 { a: a1, b: b1 },
14735 { a: a2, b: b2 }
14736 ];
14737};
14738
14739ShortCurve.prototype._endoSplit = function _endoSplit(k) {
14740 var basis = this.endo.basis;
14741 var v1 = basis[0];
14742 var v2 = basis[1];
14743
14744 var c1 = v2.b.mul(k).divRound(this.n);
14745 var c2 = v1.b.neg().mul(k).divRound(this.n);
14746
14747 var p1 = c1.mul(v1.a);
14748 var p2 = c2.mul(v2.a);
14749 var q1 = c1.mul(v1.b);
14750 var q2 = c2.mul(v2.b);
14751
14752 // Calculate answer
14753 var k1 = k.sub(p1).sub(p2);
14754 var k2 = q1.add(q2).neg();
14755 return { k1: k1, k2: k2 };
14756};
14757
14758ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
14759 x = new bn$1(x, 16);
14760 if (!x.red)
14761 x = x.toRed(this.red);
14762
14763 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
14764 var y = y2.redSqrt();
14765 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
14766 throw new Error('invalid point');
14767
14768 // XXX Is there any way to tell if the number is odd without converting it
14769 // to non-red form?
14770 var isOdd = y.fromRed().isOdd();
14771 if (odd && !isOdd || !odd && isOdd)
14772 y = y.redNeg();
14773
14774 return this.point(x, y);
14775};
14776
14777ShortCurve.prototype.validate = function validate(point) {
14778 if (point.inf)
14779 return true;
14780
14781 var x = point.x;
14782 var y = point.y;
14783
14784 var ax = this.a.redMul(x);
14785 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
14786 return y.redSqr().redISub(rhs).cmpn(0) === 0;
14787};
14788
14789ShortCurve.prototype._endoWnafMulAdd =
14790 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
14791 var npoints = this._endoWnafT1;
14792 var ncoeffs = this._endoWnafT2;
14793 for (var i = 0; i < points.length; i++) {
14794 var split = this._endoSplit(coeffs[i]);
14795 var p = points[i];
14796 var beta = p._getBeta();
14797
14798 if (split.k1.negative) {
14799 split.k1.ineg();
14800 p = p.neg(true);
14801 }
14802 if (split.k2.negative) {
14803 split.k2.ineg();
14804 beta = beta.neg(true);
14805 }
14806
14807 npoints[i * 2] = p;
14808 npoints[i * 2 + 1] = beta;
14809 ncoeffs[i * 2] = split.k1;
14810 ncoeffs[i * 2 + 1] = split.k2;
14811 }
14812 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
14813
14814 // Clean-up references to points and coefficients
14815 for (var j = 0; j < i * 2; j++) {
14816 npoints[j] = null;
14817 ncoeffs[j] = null;
14818 }
14819 return res;
14820};
14821
14822function Point(curve, x, y, isRed) {
14823 base.BasePoint.call(this, curve, 'affine');
14824 if (x === null && y === null) {
14825 this.x = null;
14826 this.y = null;
14827 this.inf = true;
14828 } else {
14829 this.x = new bn$1(x, 16);
14830 this.y = new bn$1(y, 16);
14831 // Force redgomery representation when loading from JSON
14832 if (isRed) {
14833 this.x.forceRed(this.curve.red);
14834 this.y.forceRed(this.curve.red);
14835 }
14836 if (!this.x.red)
14837 this.x = this.x.toRed(this.curve.red);
14838 if (!this.y.red)
14839 this.y = this.y.toRed(this.curve.red);
14840 this.inf = false;
14841 }
14842}
14843inherits_browser(Point, base.BasePoint);
14844
14845ShortCurve.prototype.point = function point(x, y, isRed) {
14846 return new Point(this, x, y, isRed);
14847};
14848
14849ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
14850 return Point.fromJSON(this, obj, red);
14851};
14852
14853Point.prototype._getBeta = function _getBeta() {
14854 if (!this.curve.endo)
14855 return;
14856
14857 var pre = this.precomputed;
14858 if (pre && pre.beta)
14859 return pre.beta;
14860
14861 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
14862 if (pre) {
14863 var curve = this.curve;
14864 var endoMul = function(p) {
14865 return curve.point(p.x.redMul(curve.endo.beta), p.y);
14866 };
14867 pre.beta = beta;
14868 beta.precomputed = {
14869 beta: null,
14870 naf: pre.naf && {
14871 wnd: pre.naf.wnd,
14872 points: pre.naf.points.map(endoMul)
14873 },
14874 doubles: pre.doubles && {
14875 step: pre.doubles.step,
14876 points: pre.doubles.points.map(endoMul)
14877 }
14878 };
14879 }
14880 return beta;
14881};
14882
14883Point.prototype.toJSON = function toJSON() {
14884 if (!this.precomputed)
14885 return [ this.x, this.y ];
14886
14887 return [ this.x, this.y, this.precomputed && {
14888 doubles: this.precomputed.doubles && {
14889 step: this.precomputed.doubles.step,
14890 points: this.precomputed.doubles.points.slice(1)
14891 },
14892 naf: this.precomputed.naf && {
14893 wnd: this.precomputed.naf.wnd,
14894 points: this.precomputed.naf.points.slice(1)
14895 }
14896 } ];
14897};
14898
14899Point.fromJSON = function fromJSON(curve, obj, red) {
14900 if (typeof obj === 'string')
14901 obj = JSON.parse(obj);
14902 var res = curve.point(obj[0], obj[1], red);
14903 if (!obj[2])
14904 return res;
14905
14906 function obj2point(obj) {
14907 return curve.point(obj[0], obj[1], red);
14908 }
14909
14910 var pre = obj[2];
14911 res.precomputed = {
14912 beta: null,
14913 doubles: pre.doubles && {
14914 step: pre.doubles.step,
14915 points: [ res ].concat(pre.doubles.points.map(obj2point))
14916 },
14917 naf: pre.naf && {
14918 wnd: pre.naf.wnd,
14919 points: [ res ].concat(pre.naf.points.map(obj2point))
14920 }
14921 };
14922 return res;
14923};
14924
14925Point.prototype.inspect = function inspect() {
14926 if (this.isInfinity())
14927 return '<EC Point Infinity>';
14928 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
14929 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
14930};
14931
14932Point.prototype.isInfinity = function isInfinity() {
14933 return this.inf;
14934};
14935
14936Point.prototype.add = function add(p) {
14937 // O + P = P
14938 if (this.inf)
14939 return p;
14940
14941 // P + O = P
14942 if (p.inf)
14943 return this;
14944
14945 // P + P = 2P
14946 if (this.eq(p))
14947 return this.dbl();
14948
14949 // P + (-P) = O
14950 if (this.neg().eq(p))
14951 return this.curve.point(null, null);
14952
14953 // P + Q = O
14954 if (this.x.cmp(p.x) === 0)
14955 return this.curve.point(null, null);
14956
14957 var c = this.y.redSub(p.y);
14958 if (c.cmpn(0) !== 0)
14959 c = c.redMul(this.x.redSub(p.x).redInvm());
14960 var nx = c.redSqr().redISub(this.x).redISub(p.x);
14961 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
14962 return this.curve.point(nx, ny);
14963};
14964
14965Point.prototype.dbl = function dbl() {
14966 if (this.inf)
14967 return this;
14968
14969 // 2P = O
14970 var ys1 = this.y.redAdd(this.y);
14971 if (ys1.cmpn(0) === 0)
14972 return this.curve.point(null, null);
14973
14974 var a = this.curve.a;
14975
14976 var x2 = this.x.redSqr();
14977 var dyinv = ys1.redInvm();
14978 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
14979
14980 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
14981 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
14982 return this.curve.point(nx, ny);
14983};
14984
14985Point.prototype.getX = function getX() {
14986 return this.x.fromRed();
14987};
14988
14989Point.prototype.getY = function getY() {
14990 return this.y.fromRed();
14991};
14992
14993Point.prototype.mul = function mul(k) {
14994 k = new bn$1(k, 16);
14995 if (this.isInfinity())
14996 return this;
14997 else if (this._hasDoubles(k))
14998 return this.curve._fixedNafMul(this, k);
14999 else if (this.curve.endo)
15000 return this.curve._endoWnafMulAdd([ this ], [ k ]);
15001 else
15002 return this.curve._wnafMul(this, k);
15003};
15004
15005Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
15006 var points = [ this, p2 ];
15007 var coeffs = [ k1, k2 ];
15008 if (this.curve.endo)
15009 return this.curve._endoWnafMulAdd(points, coeffs);
15010 else
15011 return this.curve._wnafMulAdd(1, points, coeffs, 2);
15012};
15013
15014Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
15015 var points = [ this, p2 ];
15016 var coeffs = [ k1, k2 ];
15017 if (this.curve.endo)
15018 return this.curve._endoWnafMulAdd(points, coeffs, true);
15019 else
15020 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
15021};
15022
15023Point.prototype.eq = function eq(p) {
15024 return this === p ||
15025 this.inf === p.inf &&
15026 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
15027};
15028
15029Point.prototype.neg = function neg(_precompute) {
15030 if (this.inf)
15031 return this;
15032
15033 var res = this.curve.point(this.x, this.y.redNeg());
15034 if (_precompute && this.precomputed) {
15035 var pre = this.precomputed;
15036 var negate = function(p) {
15037 return p.neg();
15038 };
15039 res.precomputed = {
15040 naf: pre.naf && {
15041 wnd: pre.naf.wnd,
15042 points: pre.naf.points.map(negate)
15043 },
15044 doubles: pre.doubles && {
15045 step: pre.doubles.step,
15046 points: pre.doubles.points.map(negate)
15047 }
15048 };
15049 }
15050 return res;
15051};
15052
15053Point.prototype.toJ = function toJ() {
15054 if (this.inf)
15055 return this.curve.jpoint(null, null, null);
15056
15057 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
15058 return res;
15059};
15060
15061function JPoint(curve, x, y, z) {
15062 base.BasePoint.call(this, curve, 'jacobian');
15063 if (x === null && y === null && z === null) {
15064 this.x = this.curve.one;
15065 this.y = this.curve.one;
15066 this.z = new bn$1(0);
15067 } else {
15068 this.x = new bn$1(x, 16);
15069 this.y = new bn$1(y, 16);
15070 this.z = new bn$1(z, 16);
15071 }
15072 if (!this.x.red)
15073 this.x = this.x.toRed(this.curve.red);
15074 if (!this.y.red)
15075 this.y = this.y.toRed(this.curve.red);
15076 if (!this.z.red)
15077 this.z = this.z.toRed(this.curve.red);
15078
15079 this.zOne = this.z === this.curve.one;
15080}
15081inherits_browser(JPoint, base.BasePoint);
15082
15083ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
15084 return new JPoint(this, x, y, z);
15085};
15086
15087JPoint.prototype.toP = function toP() {
15088 if (this.isInfinity())
15089 return this.curve.point(null, null);
15090
15091 var zinv = this.z.redInvm();
15092 var zinv2 = zinv.redSqr();
15093 var ax = this.x.redMul(zinv2);
15094 var ay = this.y.redMul(zinv2).redMul(zinv);
15095
15096 return this.curve.point(ax, ay);
15097};
15098
15099JPoint.prototype.neg = function neg() {
15100 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
15101};
15102
15103JPoint.prototype.add = function add(p) {
15104 // O + P = P
15105 if (this.isInfinity())
15106 return p;
15107
15108 // P + O = P
15109 if (p.isInfinity())
15110 return this;
15111
15112 // 12M + 4S + 7A
15113 var pz2 = p.z.redSqr();
15114 var z2 = this.z.redSqr();
15115 var u1 = this.x.redMul(pz2);
15116 var u2 = p.x.redMul(z2);
15117 var s1 = this.y.redMul(pz2.redMul(p.z));
15118 var s2 = p.y.redMul(z2.redMul(this.z));
15119
15120 var h = u1.redSub(u2);
15121 var r = s1.redSub(s2);
15122 if (h.cmpn(0) === 0) {
15123 if (r.cmpn(0) !== 0)
15124 return this.curve.jpoint(null, null, null);
15125 else
15126 return this.dbl();
15127 }
15128
15129 var h2 = h.redSqr();
15130 var h3 = h2.redMul(h);
15131 var v = u1.redMul(h2);
15132
15133 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
15134 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
15135 var nz = this.z.redMul(p.z).redMul(h);
15136
15137 return this.curve.jpoint(nx, ny, nz);
15138};
15139
15140JPoint.prototype.mixedAdd = function mixedAdd(p) {
15141 // O + P = P
15142 if (this.isInfinity())
15143 return p.toJ();
15144
15145 // P + O = P
15146 if (p.isInfinity())
15147 return this;
15148
15149 // 8M + 3S + 7A
15150 var z2 = this.z.redSqr();
15151 var u1 = this.x;
15152 var u2 = p.x.redMul(z2);
15153 var s1 = this.y;
15154 var s2 = p.y.redMul(z2).redMul(this.z);
15155
15156 var h = u1.redSub(u2);
15157 var r = s1.redSub(s2);
15158 if (h.cmpn(0) === 0) {
15159 if (r.cmpn(0) !== 0)
15160 return this.curve.jpoint(null, null, null);
15161 else
15162 return this.dbl();
15163 }
15164
15165 var h2 = h.redSqr();
15166 var h3 = h2.redMul(h);
15167 var v = u1.redMul(h2);
15168
15169 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
15170 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
15171 var nz = this.z.redMul(h);
15172
15173 return this.curve.jpoint(nx, ny, nz);
15174};
15175
15176JPoint.prototype.dblp = function dblp(pow) {
15177 if (pow === 0)
15178 return this;
15179 if (this.isInfinity())
15180 return this;
15181 if (!pow)
15182 return this.dbl();
15183
15184 if (this.curve.zeroA || this.curve.threeA) {
15185 var r = this;
15186 for (var i = 0; i < pow; i++)
15187 r = r.dbl();
15188 return r;
15189 }
15190
15191 // 1M + 2S + 1A + N * (4S + 5M + 8A)
15192 // N = 1 => 6M + 6S + 9A
15193 var a = this.curve.a;
15194 var tinv = this.curve.tinv;
15195
15196 var jx = this.x;
15197 var jy = this.y;
15198 var jz = this.z;
15199 var jz4 = jz.redSqr().redSqr();
15200
15201 // Reuse results
15202 var jyd = jy.redAdd(jy);
15203 for (var i = 0; i < pow; i++) {
15204 var jx2 = jx.redSqr();
15205 var jyd2 = jyd.redSqr();
15206 var jyd4 = jyd2.redSqr();
15207 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
15208
15209 var t1 = jx.redMul(jyd2);
15210 var nx = c.redSqr().redISub(t1.redAdd(t1));
15211 var t2 = t1.redISub(nx);
15212 var dny = c.redMul(t2);
15213 dny = dny.redIAdd(dny).redISub(jyd4);
15214 var nz = jyd.redMul(jz);
15215 if (i + 1 < pow)
15216 jz4 = jz4.redMul(jyd4);
15217
15218 jx = nx;
15219 jz = nz;
15220 jyd = dny;
15221 }
15222
15223 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
15224};
15225
15226JPoint.prototype.dbl = function dbl() {
15227 if (this.isInfinity())
15228 return this;
15229
15230 if (this.curve.zeroA)
15231 return this._zeroDbl();
15232 else if (this.curve.threeA)
15233 return this._threeDbl();
15234 else
15235 return this._dbl();
15236};
15237
15238JPoint.prototype._zeroDbl = function _zeroDbl() {
15239 var nx;
15240 var ny;
15241 var nz;
15242 // Z = 1
15243 if (this.zOne) {
15244 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
15245 // #doubling-mdbl-2007-bl
15246 // 1M + 5S + 14A
15247
15248 // XX = X1^2
15249 var xx = this.x.redSqr();
15250 // YY = Y1^2
15251 var yy = this.y.redSqr();
15252 // YYYY = YY^2
15253 var yyyy = yy.redSqr();
15254 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
15255 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
15256 s = s.redIAdd(s);
15257 // M = 3 * XX + a; a = 0
15258 var m = xx.redAdd(xx).redIAdd(xx);
15259 // T = M ^ 2 - 2*S
15260 var t = m.redSqr().redISub(s).redISub(s);
15261
15262 // 8 * YYYY
15263 var yyyy8 = yyyy.redIAdd(yyyy);
15264 yyyy8 = yyyy8.redIAdd(yyyy8);
15265 yyyy8 = yyyy8.redIAdd(yyyy8);
15266
15267 // X3 = T
15268 nx = t;
15269 // Y3 = M * (S - T) - 8 * YYYY
15270 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
15271 // Z3 = 2*Y1
15272 nz = this.y.redAdd(this.y);
15273 } else {
15274 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
15275 // #doubling-dbl-2009-l
15276 // 2M + 5S + 13A
15277
15278 // A = X1^2
15279 var a = this.x.redSqr();
15280 // B = Y1^2
15281 var b = this.y.redSqr();
15282 // C = B^2
15283 var c = b.redSqr();
15284 // D = 2 * ((X1 + B)^2 - A - C)
15285 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
15286 d = d.redIAdd(d);
15287 // E = 3 * A
15288 var e = a.redAdd(a).redIAdd(a);
15289 // F = E^2
15290 var f = e.redSqr();
15291
15292 // 8 * C
15293 var c8 = c.redIAdd(c);
15294 c8 = c8.redIAdd(c8);
15295 c8 = c8.redIAdd(c8);
15296
15297 // X3 = F - 2 * D
15298 nx = f.redISub(d).redISub(d);
15299 // Y3 = E * (D - X3) - 8 * C
15300 ny = e.redMul(d.redISub(nx)).redISub(c8);
15301 // Z3 = 2 * Y1 * Z1
15302 nz = this.y.redMul(this.z);
15303 nz = nz.redIAdd(nz);
15304 }
15305
15306 return this.curve.jpoint(nx, ny, nz);
15307};
15308
15309JPoint.prototype._threeDbl = function _threeDbl() {
15310 var nx;
15311 var ny;
15312 var nz;
15313 // Z = 1
15314 if (this.zOne) {
15315 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
15316 // #doubling-mdbl-2007-bl
15317 // 1M + 5S + 15A
15318
15319 // XX = X1^2
15320 var xx = this.x.redSqr();
15321 // YY = Y1^2
15322 var yy = this.y.redSqr();
15323 // YYYY = YY^2
15324 var yyyy = yy.redSqr();
15325 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
15326 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
15327 s = s.redIAdd(s);
15328 // M = 3 * XX + a
15329 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
15330 // T = M^2 - 2 * S
15331 var t = m.redSqr().redISub(s).redISub(s);
15332 // X3 = T
15333 nx = t;
15334 // Y3 = M * (S - T) - 8 * YYYY
15335 var yyyy8 = yyyy.redIAdd(yyyy);
15336 yyyy8 = yyyy8.redIAdd(yyyy8);
15337 yyyy8 = yyyy8.redIAdd(yyyy8);
15338 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
15339 // Z3 = 2 * Y1
15340 nz = this.y.redAdd(this.y);
15341 } else {
15342 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
15343 // 3M + 5S
15344
15345 // delta = Z1^2
15346 var delta = this.z.redSqr();
15347 // gamma = Y1^2
15348 var gamma = this.y.redSqr();
15349 // beta = X1 * gamma
15350 var beta = this.x.redMul(gamma);
15351 // alpha = 3 * (X1 - delta) * (X1 + delta)
15352 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
15353 alpha = alpha.redAdd(alpha).redIAdd(alpha);
15354 // X3 = alpha^2 - 8 * beta
15355 var beta4 = beta.redIAdd(beta);
15356 beta4 = beta4.redIAdd(beta4);
15357 var beta8 = beta4.redAdd(beta4);
15358 nx = alpha.redSqr().redISub(beta8);
15359 // Z3 = (Y1 + Z1)^2 - gamma - delta
15360 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
15361 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
15362 var ggamma8 = gamma.redSqr();
15363 ggamma8 = ggamma8.redIAdd(ggamma8);
15364 ggamma8 = ggamma8.redIAdd(ggamma8);
15365 ggamma8 = ggamma8.redIAdd(ggamma8);
15366 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
15367 }
15368
15369 return this.curve.jpoint(nx, ny, nz);
15370};
15371
15372JPoint.prototype._dbl = function _dbl() {
15373 var a = this.curve.a;
15374
15375 // 4M + 6S + 10A
15376 var jx = this.x;
15377 var jy = this.y;
15378 var jz = this.z;
15379 var jz4 = jz.redSqr().redSqr();
15380
15381 var jx2 = jx.redSqr();
15382 var jy2 = jy.redSqr();
15383
15384 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
15385
15386 var jxd4 = jx.redAdd(jx);
15387 jxd4 = jxd4.redIAdd(jxd4);
15388 var t1 = jxd4.redMul(jy2);
15389 var nx = c.redSqr().redISub(t1.redAdd(t1));
15390 var t2 = t1.redISub(nx);
15391
15392 var jyd8 = jy2.redSqr();
15393 jyd8 = jyd8.redIAdd(jyd8);
15394 jyd8 = jyd8.redIAdd(jyd8);
15395 jyd8 = jyd8.redIAdd(jyd8);
15396 var ny = c.redMul(t2).redISub(jyd8);
15397 var nz = jy.redAdd(jy).redMul(jz);
15398
15399 return this.curve.jpoint(nx, ny, nz);
15400};
15401
15402JPoint.prototype.trpl = function trpl() {
15403 if (!this.curve.zeroA)
15404 return this.dbl().add(this);
15405
15406 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
15407 // 5M + 10S + ...
15408
15409 // XX = X1^2
15410 var xx = this.x.redSqr();
15411 // YY = Y1^2
15412 var yy = this.y.redSqr();
15413 // ZZ = Z1^2
15414 var zz = this.z.redSqr();
15415 // YYYY = YY^2
15416 var yyyy = yy.redSqr();
15417 // M = 3 * XX + a * ZZ2; a = 0
15418 var m = xx.redAdd(xx).redIAdd(xx);
15419 // MM = M^2
15420 var mm = m.redSqr();
15421 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
15422 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
15423 e = e.redIAdd(e);
15424 e = e.redAdd(e).redIAdd(e);
15425 e = e.redISub(mm);
15426 // EE = E^2
15427 var ee = e.redSqr();
15428 // T = 16*YYYY
15429 var t = yyyy.redIAdd(yyyy);
15430 t = t.redIAdd(t);
15431 t = t.redIAdd(t);
15432 t = t.redIAdd(t);
15433 // U = (M + E)^2 - MM - EE - T
15434 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
15435 // X3 = 4 * (X1 * EE - 4 * YY * U)
15436 var yyu4 = yy.redMul(u);
15437 yyu4 = yyu4.redIAdd(yyu4);
15438 yyu4 = yyu4.redIAdd(yyu4);
15439 var nx = this.x.redMul(ee).redISub(yyu4);
15440 nx = nx.redIAdd(nx);
15441 nx = nx.redIAdd(nx);
15442 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
15443 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
15444 ny = ny.redIAdd(ny);
15445 ny = ny.redIAdd(ny);
15446 ny = ny.redIAdd(ny);
15447 // Z3 = (Z1 + E)^2 - ZZ - EE
15448 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
15449
15450 return this.curve.jpoint(nx, ny, nz);
15451};
15452
15453JPoint.prototype.mul = function mul(k, kbase) {
15454 k = new bn$1(k, kbase);
15455
15456 return this.curve._wnafMul(this, k);
15457};
15458
15459JPoint.prototype.eq = function eq(p) {
15460 if (p.type === 'affine')
15461 return this.eq(p.toJ());
15462
15463 if (this === p)
15464 return true;
15465
15466 // x1 * z2^2 == x2 * z1^2
15467 var z2 = this.z.redSqr();
15468 var pz2 = p.z.redSqr();
15469 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
15470 return false;
15471
15472 // y1 * z2^3 == y2 * z1^3
15473 var z3 = z2.redMul(this.z);
15474 var pz3 = pz2.redMul(p.z);
15475 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
15476};
15477
15478JPoint.prototype.eqXToP = function eqXToP(x) {
15479 var zs = this.z.redSqr();
15480 var rx = x.toRed(this.curve.red).redMul(zs);
15481 if (this.x.cmp(rx) === 0)
15482 return true;
15483
15484 var xc = x.clone();
15485 var t = this.curve.redN.redMul(zs);
15486 for (;;) {
15487 xc.iadd(this.curve.n);
15488 if (xc.cmp(this.curve.p) >= 0)
15489 return false;
15490
15491 rx.redIAdd(t);
15492 if (this.x.cmp(rx) === 0)
15493 return true;
15494 }
15495};
15496
15497JPoint.prototype.inspect = function inspect() {
15498 if (this.isInfinity())
15499 return '<EC JPoint Infinity>';
15500 return '<EC JPoint x: ' + this.x.toString(16, 2) +
15501 ' y: ' + this.y.toString(16, 2) +
15502 ' z: ' + this.z.toString(16, 2) + '>';
15503};
15504
15505JPoint.prototype.isInfinity = function isInfinity() {
15506 // XXX This code assumes that zero is always zero in red
15507 return this.z.cmpn(0) === 0;
15508};
15509
15510var mont = {};
15511
15512var edwards = {};
15513
15514var curve_1 = createCommonjsModule(function (module, exports) {
15515'use strict';
15516
15517var curve = exports;
15518
15519curve.base = base;
15520curve.short = short_1;
15521curve.mont = mont;
15522curve.edwards = edwards;
15523});
15524
15525var secp256k1 = undefined;
15526
15527var curves_1 = createCommonjsModule(function (module, exports) {
15528'use strict';
15529
15530var curves = exports;
15531
15532
15533
15534
15535
15536var assert = utils_1$1.assert;
15537
15538function PresetCurve(options) {
15539 if (options.type === 'short')
15540 this.curve = new curve_1.short(options);
15541 else if (options.type === 'edwards')
15542 this.curve = new curve_1.edwards(options);
15543 else
15544 this.curve = new curve_1.mont(options);
15545 this.g = this.curve.g;
15546 this.n = this.curve.n;
15547 this.hash = options.hash;
15548
15549 assert(this.g.validate(), 'Invalid curve');
15550 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
15551}
15552curves.PresetCurve = PresetCurve;
15553
15554function defineCurve(name, options) {
15555 Object.defineProperty(curves, name, {
15556 configurable: true,
15557 enumerable: true,
15558 get: function() {
15559 var curve = new PresetCurve(options);
15560 Object.defineProperty(curves, name, {
15561 configurable: true,
15562 enumerable: true,
15563 value: curve
15564 });
15565 return curve;
15566 }
15567 });
15568}
15569
15570defineCurve('p192', {
15571 type: 'short',
15572 prime: 'p192',
15573 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
15574 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
15575 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
15576 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
15577 hash: hash_1.sha256,
15578 gRed: false,
15579 g: [
15580 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
15581 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
15582 ]
15583});
15584
15585defineCurve('p224', {
15586 type: 'short',
15587 prime: 'p224',
15588 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
15589 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
15590 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
15591 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
15592 hash: hash_1.sha256,
15593 gRed: false,
15594 g: [
15595 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
15596 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
15597 ]
15598});
15599
15600defineCurve('p256', {
15601 type: 'short',
15602 prime: null,
15603 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
15604 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
15605 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
15606 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
15607 hash: hash_1.sha256,
15608 gRed: false,
15609 g: [
15610 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
15611 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
15612 ]
15613});
15614
15615defineCurve('p384', {
15616 type: 'short',
15617 prime: null,
15618 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
15619 'fffffffe ffffffff 00000000 00000000 ffffffff',
15620 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
15621 'fffffffe ffffffff 00000000 00000000 fffffffc',
15622 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
15623 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
15624 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
15625 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
15626 hash: hash_1.sha384,
15627 gRed: false,
15628 g: [
15629 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
15630 '5502f25d bf55296c 3a545e38 72760ab7',
15631 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
15632 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
15633 ]
15634});
15635
15636defineCurve('p521', {
15637 type: 'short',
15638 prime: null,
15639 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
15640 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
15641 'ffffffff ffffffff ffffffff ffffffff ffffffff',
15642 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
15643 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
15644 'ffffffff ffffffff ffffffff ffffffff fffffffc',
15645 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
15646 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
15647 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
15648 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
15649 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
15650 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
15651 hash: hash_1.sha512,
15652 gRed: false,
15653 g: [
15654 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
15655 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
15656 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
15657 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
15658 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
15659 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
15660 ]
15661});
15662
15663defineCurve('curve25519', {
15664 type: 'mont',
15665 prime: 'p25519',
15666 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
15667 a: '76d06',
15668 b: '1',
15669 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
15670 hash: hash_1.sha256,
15671 gRed: false,
15672 g: [
15673 '9'
15674 ]
15675});
15676
15677defineCurve('ed25519', {
15678 type: 'edwards',
15679 prime: 'p25519',
15680 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
15681 a: '-1',
15682 c: '1',
15683 // -121665 * (121666^(-1)) (mod P)
15684 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
15685 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
15686 hash: hash_1.sha256,
15687 gRed: false,
15688 g: [
15689 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
15690
15691 // 4/5
15692 '6666666666666666666666666666666666666666666666666666666666666658'
15693 ]
15694});
15695
15696var pre;
15697try {
15698 pre = secp256k1;
15699} catch (e) {
15700 pre = undefined;
15701}
15702
15703defineCurve('secp256k1', {
15704 type: 'short',
15705 prime: 'k256',
15706 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
15707 a: '0',
15708 b: '7',
15709 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
15710 h: '1',
15711 hash: hash_1.sha256,
15712
15713 // Precomputed endomorphism
15714 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
15715 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
15716 basis: [
15717 {
15718 a: '3086d221a7d46bcde86c90e49284eb15',
15719 b: '-e4437ed6010e88286f547fa90abfe4c3'
15720 },
15721 {
15722 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
15723 b: '3086d221a7d46bcde86c90e49284eb15'
15724 }
15725 ],
15726
15727 gRed: false,
15728 g: [
15729 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
15730 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
15731 pre
15732 ]
15733});
15734});
15735
15736'use strict';
15737
15738
15739
15740
15741
15742function HmacDRBG(options) {
15743 if (!(this instanceof HmacDRBG))
15744 return new HmacDRBG(options);
15745 this.hash = options.hash;
15746 this.predResist = !!options.predResist;
15747
15748 this.outLen = this.hash.outSize;
15749 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
15750
15751 this._reseed = null;
15752 this.reseedInterval = null;
15753 this.K = null;
15754 this.V = null;
15755
15756 var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
15757 var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
15758 var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
15759 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
15760 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
15761 this._init(entropy, nonce, pers);
15762}
15763var hmacDrbg = HmacDRBG;
15764
15765HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
15766 var seed = entropy.concat(nonce).concat(pers);
15767
15768 this.K = new Array(this.outLen / 8);
15769 this.V = new Array(this.outLen / 8);
15770 for (var i = 0; i < this.V.length; i++) {
15771 this.K[i] = 0x00;
15772 this.V[i] = 0x01;
15773 }
15774
15775 this._update(seed);
15776 this._reseed = 1;
15777 this.reseedInterval = 0x1000000000000; // 2^48
15778};
15779
15780HmacDRBG.prototype._hmac = function hmac() {
15781 return new hash_1.hmac(this.hash, this.K);
15782};
15783
15784HmacDRBG.prototype._update = function update(seed) {
15785 var kmac = this._hmac()
15786 .update(this.V)
15787 .update([ 0x00 ]);
15788 if (seed)
15789 kmac = kmac.update(seed);
15790 this.K = kmac.digest();
15791 this.V = this._hmac().update(this.V).digest();
15792 if (!seed)
15793 return;
15794
15795 this.K = this._hmac()
15796 .update(this.V)
15797 .update([ 0x01 ])
15798 .update(seed)
15799 .digest();
15800 this.V = this._hmac().update(this.V).digest();
15801};
15802
15803HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
15804 // Optional entropy enc
15805 if (typeof entropyEnc !== 'string') {
15806 addEnc = add;
15807 add = entropyEnc;
15808 entropyEnc = null;
15809 }
15810
15811 entropy = utils_1.toArray(entropy, entropyEnc);
15812 add = utils_1.toArray(add, addEnc);
15813
15814 minimalisticAssert(entropy.length >= (this.minEntropy / 8),
15815 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
15816
15817 this._update(entropy.concat(add || []));
15818 this._reseed = 1;
15819};
15820
15821HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
15822 if (this._reseed > this.reseedInterval)
15823 throw new Error('Reseed is required');
15824
15825 // Optional encoding
15826 if (typeof enc !== 'string') {
15827 addEnc = add;
15828 add = enc;
15829 enc = null;
15830 }
15831
15832 // Optional additional data
15833 if (add) {
15834 add = utils_1.toArray(add, addEnc || 'hex');
15835 this._update(add);
15836 }
15837
15838 var temp = [];
15839 while (temp.length < len) {
15840 this.V = this._hmac().update(this.V).digest();
15841 temp = temp.concat(this.V);
15842 }
15843
15844 var res = temp.slice(0, len);
15845 this._update(add);
15846 this._reseed++;
15847 return utils_1.encode(res, enc);
15848};
15849
15850'use strict';
15851
15852
15853
15854var assert$3 = utils_1$1.assert;
15855
15856function KeyPair(ec, options) {
15857 this.ec = ec;
15858 this.priv = null;
15859 this.pub = null;
15860
15861 // KeyPair(ec, { priv: ..., pub: ... })
15862 if (options.priv)
15863 this._importPrivate(options.priv, options.privEnc);
15864 if (options.pub)
15865 this._importPublic(options.pub, options.pubEnc);
15866}
15867var key = KeyPair;
15868
15869KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
15870 if (pub instanceof KeyPair)
15871 return pub;
15872
15873 return new KeyPair(ec, {
15874 pub: pub,
15875 pubEnc: enc
15876 });
15877};
15878
15879KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
15880 if (priv instanceof KeyPair)
15881 return priv;
15882
15883 return new KeyPair(ec, {
15884 priv: priv,
15885 privEnc: enc
15886 });
15887};
15888
15889KeyPair.prototype.validate = function validate() {
15890 var pub = this.getPublic();
15891
15892 if (pub.isInfinity())
15893 return { result: false, reason: 'Invalid public key' };
15894 if (!pub.validate())
15895 return { result: false, reason: 'Public key is not a point' };
15896 if (!pub.mul(this.ec.curve.n).isInfinity())
15897 return { result: false, reason: 'Public key * N != O' };
15898
15899 return { result: true, reason: null };
15900};
15901
15902KeyPair.prototype.getPublic = function getPublic(compact, enc) {
15903 // compact is optional argument
15904 if (typeof compact === 'string') {
15905 enc = compact;
15906 compact = null;
15907 }
15908
15909 if (!this.pub)
15910 this.pub = this.ec.g.mul(this.priv);
15911
15912 if (!enc)
15913 return this.pub;
15914
15915 return this.pub.encode(enc, compact);
15916};
15917
15918KeyPair.prototype.getPrivate = function getPrivate(enc) {
15919 if (enc === 'hex')
15920 return this.priv.toString(16, 2);
15921 else
15922 return this.priv;
15923};
15924
15925KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
15926 this.priv = new bn$1(key, enc || 16);
15927
15928 // Ensure that the priv won't be bigger than n, otherwise we may fail
15929 // in fixed multiplication method
15930 this.priv = this.priv.umod(this.ec.curve.n);
15931};
15932
15933KeyPair.prototype._importPublic = function _importPublic(key, enc) {
15934 if (key.x || key.y) {
15935 // Montgomery points only have an `x` coordinate.
15936 // Weierstrass/Edwards points on the other hand have both `x` and
15937 // `y` coordinates.
15938 if (this.ec.curve.type === 'mont') {
15939 assert$3(key.x, 'Need x coordinate');
15940 } else if (this.ec.curve.type === 'short' ||
15941 this.ec.curve.type === 'edwards') {
15942 assert$3(key.x && key.y, 'Need both x and y coordinate');
15943 }
15944 this.pub = this.ec.curve.point(key.x, key.y);
15945 return;
15946 }
15947 this.pub = this.ec.curve.decodePoint(key, enc);
15948};
15949
15950// ECDH
15951KeyPair.prototype.derive = function derive(pub) {
15952 return pub.mul(this.priv).getX();
15953};
15954
15955// ECDSA
15956KeyPair.prototype.sign = function sign(msg, enc, options) {
15957 return this.ec.sign(msg, this, enc, options);
15958};
15959
15960KeyPair.prototype.verify = function verify(msg, signature) {
15961 return this.ec.verify(msg, signature, this);
15962};
15963
15964KeyPair.prototype.inspect = function inspect() {
15965 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
15966 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
15967};
15968
15969'use strict';
15970
15971
15972
15973
15974var assert$4 = utils_1$1.assert;
15975
15976function Signature(options, enc) {
15977 if (options instanceof Signature)
15978 return options;
15979
15980 if (this._importDER(options, enc))
15981 return;
15982
15983 assert$4(options.r && options.s, 'Signature without r or s');
15984 this.r = new bn$1(options.r, 16);
15985 this.s = new bn$1(options.s, 16);
15986 if (options.recoveryParam === undefined)
15987 this.recoveryParam = null;
15988 else
15989 this.recoveryParam = options.recoveryParam;
15990}
15991var signature = Signature;
15992
15993function Position() {
15994 this.place = 0;
15995}
15996
15997function getLength(buf, p) {
15998 var initial = buf[p.place++];
15999 if (!(initial & 0x80)) {
16000 return initial;
16001 }
16002 var octetLen = initial & 0xf;
16003
16004 // Indefinite length or overflow
16005 if (octetLen === 0 || octetLen > 4) {
16006 return false;
16007 }
16008
16009 var val = 0;
16010 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
16011 val <<= 8;
16012 val |= buf[off];
16013 val >>>= 0;
16014 }
16015
16016 // Leading zeroes
16017 if (val <= 0x7f) {
16018 return false;
16019 }
16020
16021 p.place = off;
16022 return val;
16023}
16024
16025function rmPadding(buf) {
16026 var i = 0;
16027 var len = buf.length - 1;
16028 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
16029 i++;
16030 }
16031 if (i === 0) {
16032 return buf;
16033 }
16034 return buf.slice(i);
16035}
16036
16037Signature.prototype._importDER = function _importDER(data, enc) {
16038 data = utils_1$1.toArray(data, enc);
16039 var p = new Position();
16040 if (data[p.place++] !== 0x30) {
16041 return false;
16042 }
16043 var len = getLength(data, p);
16044 if (len === false) {
16045 return false;
16046 }
16047 if ((len + p.place) !== data.length) {
16048 return false;
16049 }
16050 if (data[p.place++] !== 0x02) {
16051 return false;
16052 }
16053 var rlen = getLength(data, p);
16054 if (rlen === false) {
16055 return false;
16056 }
16057 var r = data.slice(p.place, rlen + p.place);
16058 p.place += rlen;
16059 if (data[p.place++] !== 0x02) {
16060 return false;
16061 }
16062 var slen = getLength(data, p);
16063 if (slen === false) {
16064 return false;
16065 }
16066 if (data.length !== slen + p.place) {
16067 return false;
16068 }
16069 var s = data.slice(p.place, slen + p.place);
16070 if (r[0] === 0) {
16071 if (r[1] & 0x80) {
16072 r = r.slice(1);
16073 } else {
16074 // Leading zeroes
16075 return false;
16076 }
16077 }
16078 if (s[0] === 0) {
16079 if (s[1] & 0x80) {
16080 s = s.slice(1);
16081 } else {
16082 // Leading zeroes
16083 return false;
16084 }
16085 }
16086
16087 this.r = new bn$1(r);
16088 this.s = new bn$1(s);
16089 this.recoveryParam = null;
16090
16091 return true;
16092};
16093
16094function constructLength(arr, len) {
16095 if (len < 0x80) {
16096 arr.push(len);
16097 return;
16098 }
16099 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
16100 arr.push(octets | 0x80);
16101 while (--octets) {
16102 arr.push((len >>> (octets << 3)) & 0xff);
16103 }
16104 arr.push(len);
16105}
16106
16107Signature.prototype.toDER = function toDER(enc) {
16108 var r = this.r.toArray();
16109 var s = this.s.toArray();
16110
16111 // Pad values
16112 if (r[0] & 0x80)
16113 r = [ 0 ].concat(r);
16114 // Pad values
16115 if (s[0] & 0x80)
16116 s = [ 0 ].concat(s);
16117
16118 r = rmPadding(r);
16119 s = rmPadding(s);
16120
16121 while (!s[0] && !(s[1] & 0x80)) {
16122 s = s.slice(1);
16123 }
16124 var arr = [ 0x02 ];
16125 constructLength(arr, r.length);
16126 arr = arr.concat(r);
16127 arr.push(0x02);
16128 constructLength(arr, s.length);
16129 var backHalf = arr.concat(s);
16130 var res = [ 0x30 ];
16131 constructLength(res, backHalf.length);
16132 res = res.concat(backHalf);
16133 return utils_1$1.encode(res, enc);
16134};
16135
16136'use strict';
16137
16138
16139
16140
16141
16142
16143var assert$5 = utils_1$1.assert;
16144
16145
16146
16147
16148function EC(options) {
16149 if (!(this instanceof EC))
16150 return new EC(options);
16151
16152 // Shortcut `elliptic.ec(curve-name)`
16153 if (typeof options === 'string') {
16154 assert$5(curves_1.hasOwnProperty(options), 'Unknown curve ' + options);
16155
16156 options = curves_1[options];
16157 }
16158
16159 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
16160 if (options instanceof curves_1.PresetCurve)
16161 options = { curve: options };
16162
16163 this.curve = options.curve.curve;
16164 this.n = this.curve.n;
16165 this.nh = this.n.ushrn(1);
16166 this.g = this.curve.g;
16167
16168 // Point on curve
16169 this.g = options.curve.g;
16170 this.g.precompute(options.curve.n.bitLength() + 1);
16171
16172 // Hash for function for DRBG
16173 this.hash = options.hash || options.curve.hash;
16174}
16175var ec = EC;
16176
16177EC.prototype.keyPair = function keyPair(options) {
16178 return new key(this, options);
16179};
16180
16181EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
16182 return key.fromPrivate(this, priv, enc);
16183};
16184
16185EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
16186 return key.fromPublic(this, pub, enc);
16187};
16188
16189EC.prototype.genKeyPair = function genKeyPair(options) {
16190 if (!options)
16191 options = {};
16192
16193 // Instantiate Hmac_DRBG
16194 var drbg = new hmacDrbg({
16195 hash: this.hash,
16196 pers: options.pers,
16197 persEnc: options.persEnc || 'utf8',
16198 entropy: options.entropy || brorand(this.hash.hmacStrength),
16199 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
16200 nonce: this.n.toArray()
16201 });
16202
16203 var bytes = this.n.byteLength();
16204 var ns2 = this.n.sub(new bn$1(2));
16205 do {
16206 var priv = new bn$1(drbg.generate(bytes));
16207 if (priv.cmp(ns2) > 0)
16208 continue;
16209
16210 priv.iaddn(1);
16211 return this.keyFromPrivate(priv);
16212 } while (true);
16213};
16214
16215EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
16216 var delta = msg.byteLength() * 8 - this.n.bitLength();
16217 if (delta > 0)
16218 msg = msg.ushrn(delta);
16219 if (!truncOnly && msg.cmp(this.n) >= 0)
16220 return msg.sub(this.n);
16221 else
16222 return msg;
16223};
16224
16225EC.prototype.sign = function sign(msg, key, enc, options) {
16226 if (typeof enc === 'object') {
16227 options = enc;
16228 enc = null;
16229 }
16230 if (!options)
16231 options = {};
16232
16233 key = this.keyFromPrivate(key, enc);
16234 msg = this._truncateToN(new bn$1(msg, 16));
16235
16236 // Zero-extend key to provide enough entropy
16237 var bytes = this.n.byteLength();
16238 var bkey = key.getPrivate().toArray('be', bytes);
16239
16240 // Zero-extend nonce to have the same byte size as N
16241 var nonce = msg.toArray('be', bytes);
16242
16243 // Instantiate Hmac_DRBG
16244 var drbg = new hmacDrbg({
16245 hash: this.hash,
16246 entropy: bkey,
16247 nonce: nonce,
16248 pers: options.pers,
16249 persEnc: options.persEnc || 'utf8'
16250 });
16251
16252 // Number of bytes to generate
16253 var ns1 = this.n.sub(new bn$1(1));
16254
16255 for (var iter = 0; true; iter++) {
16256 var k = options.k ?
16257 options.k(iter) :
16258 new bn$1(drbg.generate(this.n.byteLength()));
16259 k = this._truncateToN(k, true);
16260 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
16261 continue;
16262
16263 var kp = this.g.mul(k);
16264 if (kp.isInfinity())
16265 continue;
16266
16267 var kpX = kp.getX();
16268 var r = kpX.umod(this.n);
16269 if (r.cmpn(0) === 0)
16270 continue;
16271
16272 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
16273 s = s.umod(this.n);
16274 if (s.cmpn(0) === 0)
16275 continue;
16276
16277 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
16278 (kpX.cmp(r) !== 0 ? 2 : 0);
16279
16280 // Use complement of `s`, if it is > `n / 2`
16281 if (options.canonical && s.cmp(this.nh) > 0) {
16282 s = this.n.sub(s);
16283 recoveryParam ^= 1;
16284 }
16285
16286 return new signature({ r: r, s: s, recoveryParam: recoveryParam });
16287 }
16288};
16289
16290EC.prototype.verify = function verify(msg, signature$1, key, enc) {
16291 msg = this._truncateToN(new bn$1(msg, 16));
16292 key = this.keyFromPublic(key, enc);
16293 signature$1 = new signature(signature$1, 'hex');
16294
16295 // Perform primitive values validation
16296 var r = signature$1.r;
16297 var s = signature$1.s;
16298 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
16299 return false;
16300 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
16301 return false;
16302
16303 // Validate signature
16304 var sinv = s.invm(this.n);
16305 var u1 = sinv.mul(msg).umod(this.n);
16306 var u2 = sinv.mul(r).umod(this.n);
16307
16308 if (!this.curve._maxwellTrick) {
16309 var p = this.g.mulAdd(u1, key.getPublic(), u2);
16310 if (p.isInfinity())
16311 return false;
16312
16313 return p.getX().umod(this.n).cmp(r) === 0;
16314 }
16315
16316 // NOTE: Greg Maxwell's trick, inspired by:
16317 // https://git.io/vad3K
16318
16319 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
16320 if (p.isInfinity())
16321 return false;
16322
16323 // Compare `p.x` of Jacobian point with `r`,
16324 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
16325 // inverse of `p.z^2`
16326 return p.eqXToP(r);
16327};
16328
16329EC.prototype.recoverPubKey = function(msg, signature$1, j, enc) {
16330 assert$5((3 & j) === j, 'The recovery param is more than two bits');
16331 signature$1 = new signature(signature$1, enc);
16332
16333 var n = this.n;
16334 var e = new bn$1(msg);
16335 var r = signature$1.r;
16336 var s = signature$1.s;
16337
16338 // A set LSB signifies that the y-coordinate is odd
16339 var isYOdd = j & 1;
16340 var isSecondKey = j >> 1;
16341 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
16342 throw new Error('Unable to find sencond key candinate');
16343
16344 // 1.1. Let x = r + jn.
16345 if (isSecondKey)
16346 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
16347 else
16348 r = this.curve.pointFromX(r, isYOdd);
16349
16350 var rInv = signature$1.r.invm(n);
16351 var s1 = n.sub(e).mul(rInv).umod(n);
16352 var s2 = s.mul(rInv).umod(n);
16353
16354 // 1.6.1 Compute Q = r^-1 (sR - eG)
16355 // Q = r^-1 (sR + -eG)
16356 return this.g.mulAdd(s1, r, s2);
16357};
16358
16359EC.prototype.getKeyRecoveryParam = function(e, signature$1, Q, enc) {
16360 signature$1 = new signature(signature$1, enc);
16361 if (signature$1.recoveryParam !== null)
16362 return signature$1.recoveryParam;
16363
16364 for (var i = 0; i < 4; i++) {
16365 var Qprime;
16366 try {
16367 Qprime = this.recoverPubKey(e, signature$1, i);
16368 } catch (e) {
16369 continue;
16370 }
16371
16372 if (Qprime.eq(Q))
16373 return i;
16374 }
16375 throw new Error('Unable to find valid recovery factor');
16376};
16377
16378var eddsa = {};
16379
16380var require$$0$1 = getCjsExportFromNamespace(_package$1);
16381
16382var elliptic_1 = createCommonjsModule(function (module, exports) {
16383'use strict';
16384
16385var elliptic = exports;
16386
16387elliptic.version = require$$0$1.version;
16388elliptic.utils = utils_1$1;
16389elliptic.rand = brorand;
16390elliptic.curve = curve_1;
16391elliptic.curves = curves_1;
16392
16393// Protocols
16394elliptic.ec = ec;
16395elliptic.eddsa = eddsa;
16396});
16397var elliptic_2 = elliptic_1.ec;
16398
16399const version$d = "signing-key/5.0.3";
16400
16401"use strict";
16402const logger$g = new Logger(version$d);
16403let _curve = null;
16404function getCurve() {
16405 if (!_curve) {
16406 _curve = new elliptic_2("secp256k1");
16407 }
16408 return _curve;
16409}
16410class SigningKey {
16411 constructor(privateKey) {
16412 defineReadOnly(this, "curve", "secp256k1");
16413 defineReadOnly(this, "privateKey", hexlify(privateKey));
16414 const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
16415 defineReadOnly(this, "publicKey", "0x" + keyPair.getPublic(false, "hex"));
16416 defineReadOnly(this, "compressedPublicKey", "0x" + keyPair.getPublic(true, "hex"));
16417 defineReadOnly(this, "_isSigningKey", true);
16418 }
16419 _addPoint(other) {
16420 const p0 = getCurve().keyFromPublic(arrayify(this.publicKey));
16421 const p1 = getCurve().keyFromPublic(arrayify(other));
16422 return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex");
16423 }
16424 signDigest(digest) {
16425 const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
16426 const signature = keyPair.sign(arrayify(digest), { canonical: true });
16427 return splitSignature({
16428 recoveryParam: signature.recoveryParam,
16429 r: hexZeroPad("0x" + signature.r.toString(16), 32),
16430 s: hexZeroPad("0x" + signature.s.toString(16), 32),
16431 });
16432 }
16433 computeSharedSecret(otherKey) {
16434 const keyPair = getCurve().keyFromPrivate(arrayify(this.privateKey));
16435 const otherKeyPair = getCurve().keyFromPublic(arrayify(computePublicKey(otherKey)));
16436 return hexZeroPad("0x" + keyPair.derive(otherKeyPair.getPublic()).toString(16), 32);
16437 }
16438 static isSigningKey(value) {
16439 return !!(value && value._isSigningKey);
16440 }
16441}
16442function recoverPublicKey(digest, signature) {
16443 const sig = splitSignature(signature);
16444 const rs = { r: arrayify(sig.r), s: arrayify(sig.s) };
16445 return "0x" + getCurve().recoverPubKey(arrayify(digest), rs, sig.recoveryParam).encode("hex", false);
16446}
16447function computePublicKey(key, compressed) {
16448 const bytes = arrayify(key);
16449 if (bytes.length === 32) {
16450 const signingKey = new SigningKey(bytes);
16451 if (compressed) {
16452 return "0x" + getCurve().keyFromPrivate(bytes).getPublic(true, "hex");
16453 }
16454 return signingKey.publicKey;
16455 }
16456 else if (bytes.length === 33) {
16457 if (compressed) {
16458 return hexlify(bytes);
16459 }
16460 return "0x" + getCurve().keyFromPublic(bytes).getPublic(false, "hex");
16461 }
16462 else if (bytes.length === 65) {
16463 if (!compressed) {
16464 return hexlify(bytes);
16465 }
16466 return "0x" + getCurve().keyFromPublic(bytes).getPublic(true, "hex");
16467 }
16468 return logger$g.throwArgumentError("invalid public or private key", "key", "[REDACTED]");
16469}
16470
16471const version$e = "transactions/5.0.2";
16472
16473"use strict";
16474const logger$h = new Logger(version$e);
16475///////////////////////////////
16476function handleAddress(value) {
16477 if (value === "0x") {
16478 return null;
16479 }
16480 return getAddress(value);
16481}
16482function handleNumber(value) {
16483 if (value === "0x") {
16484 return Zero$1;
16485 }
16486 return BigNumber.from(value);
16487}
16488const transactionFields = [
16489 { name: "nonce", maxLength: 32, numeric: true },
16490 { name: "gasPrice", maxLength: 32, numeric: true },
16491 { name: "gasLimit", maxLength: 32, numeric: true },
16492 { name: "to", length: 20 },
16493 { name: "value", maxLength: 32, numeric: true },
16494 { name: "data" },
16495];
16496const allowedTransactionKeys$2 = {
16497 chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true
16498};
16499function computeAddress(key) {
16500 const publicKey = computePublicKey(key);
16501 return getAddress(hexDataSlice(keccak256(hexDataSlice(publicKey, 1)), 12));
16502}
16503function recoverAddress(digest, signature) {
16504 return computeAddress(recoverPublicKey(arrayify(digest), signature));
16505}
16506function serialize(transaction, signature) {
16507 checkProperties(transaction, allowedTransactionKeys$2);
16508 const raw = [];
16509 transactionFields.forEach(function (fieldInfo) {
16510 let value = transaction[fieldInfo.name] || ([]);
16511 const options = {};
16512 if (fieldInfo.numeric) {
16513 options.hexPad = "left";
16514 }
16515 value = arrayify(hexlify(value, options));
16516 // Fixed-width field
16517 if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) {
16518 logger$h.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value);
16519 }
16520 // Variable-width (with a maximum)
16521 if (fieldInfo.maxLength) {
16522 value = stripZeros(value);
16523 if (value.length > fieldInfo.maxLength) {
16524 logger$h.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value);
16525 }
16526 }
16527 raw.push(hexlify(value));
16528 });
16529 let chainId = 0;
16530 if (transaction.chainId != null) {
16531 // A chainId was provided; if non-zero we'll use EIP-155
16532 chainId = transaction.chainId;
16533 if (typeof (chainId) !== "number") {
16534 logger$h.throwArgumentError("invalid transaction.chainId", "transaction", transaction);
16535 }
16536 }
16537 else if (signature && !isBytesLike(signature) && signature.v > 28) {
16538 // No chainId provided, but the signature is signing with EIP-155; derive chainId
16539 chainId = Math.floor((signature.v - 35) / 2);
16540 }
16541 // We have an EIP-155 transaction (chainId was specified and non-zero)
16542 if (chainId !== 0) {
16543 raw.push(hexlify(chainId));
16544 raw.push("0x");
16545 raw.push("0x");
16546 }
16547 // Requesting an unsigned transation
16548 if (!signature) {
16549 return encode(raw);
16550 }
16551 // The splitSignature will ensure the transaction has a recoveryParam in the
16552 // case that the signTransaction function only adds a v.
16553 const sig = splitSignature(signature);
16554 // We pushed a chainId and null r, s on for hashing only; remove those
16555 let v = 27 + sig.recoveryParam;
16556 if (chainId !== 0) {
16557 raw.pop();
16558 raw.pop();
16559 raw.pop();
16560 v += chainId * 2 + 8;
16561 // If an EIP-155 v (directly or indirectly; maybe _vs) was provided, check it!
16562 if (sig.v > 28 && sig.v !== v) {
16563 logger$h.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature);
16564 }
16565 }
16566 else if (sig.v !== v) {
16567 logger$h.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature);
16568 }
16569 raw.push(hexlify(v));
16570 raw.push(stripZeros(arrayify(sig.r)));
16571 raw.push(stripZeros(arrayify(sig.s)));
16572 return encode(raw);
16573}
16574function parse(rawTransaction) {
16575 const transaction = decode(rawTransaction);
16576 if (transaction.length !== 9 && transaction.length !== 6) {
16577 logger$h.throwArgumentError("invalid raw transaction", "rawTransaction", rawTransaction);
16578 }
16579 const tx = {
16580 nonce: handleNumber(transaction[0]).toNumber(),
16581 gasPrice: handleNumber(transaction[1]),
16582 gasLimit: handleNumber(transaction[2]),
16583 to: handleAddress(transaction[3]),
16584 value: handleNumber(transaction[4]),
16585 data: transaction[5],
16586 chainId: 0
16587 };
16588 // Legacy unsigned transaction
16589 if (transaction.length === 6) {
16590 return tx;
16591 }
16592 try {
16593 tx.v = BigNumber.from(transaction[6]).toNumber();
16594 }
16595 catch (error) {
16596 console.log(error);
16597 return tx;
16598 }
16599 tx.r = hexZeroPad(transaction[7], 32);
16600 tx.s = hexZeroPad(transaction[8], 32);
16601 if (BigNumber.from(tx.r).isZero() && BigNumber.from(tx.s).isZero()) {
16602 // EIP-155 unsigned transaction
16603 tx.chainId = tx.v;
16604 tx.v = 0;
16605 }
16606 else {
16607 // Signed Tranasaction
16608 tx.chainId = Math.floor((tx.v - 35) / 2);
16609 if (tx.chainId < 0) {
16610 tx.chainId = 0;
16611 }
16612 let recoveryParam = tx.v - 27;
16613 const raw = transaction.slice(0, 6);
16614 if (tx.chainId !== 0) {
16615 raw.push(hexlify(tx.chainId));
16616 raw.push("0x");
16617 raw.push("0x");
16618 recoveryParam -= tx.chainId * 2 + 8;
16619 }
16620 const digest = keccak256(encode(raw));
16621 try {
16622 tx.from = recoverAddress(digest, { r: hexlify(tx.r), s: hexlify(tx.s), recoveryParam: recoveryParam });
16623 }
16624 catch (error) {
16625 console.log(error);
16626 }
16627 tx.hash = keccak256(rawTransaction);
16628 }
16629 return tx;
16630}
16631
16632const version$f = "wordlists/5.0.2";
16633
16634"use strict";
16635// This gets overridden by rollup
16636const exportWordlist = false;
16637const logger$i = new Logger(version$f);
16638class Wordlist {
16639 constructor(locale) {
16640 logger$i.checkAbstract(new.target, Wordlist);
16641 defineReadOnly(this, "locale", locale);
16642 }
16643 // Subclasses may override this
16644 split(mnemonic) {
16645 return mnemonic.toLowerCase().split(/ +/g);
16646 }
16647 // Subclasses may override this
16648 join(words) {
16649 return words.join(" ");
16650 }
16651 static check(wordlist) {
16652 const words = [];
16653 for (let i = 0; i < 2048; i++) {
16654 const word = wordlist.getWord(i);
16655 /* istanbul ignore if */
16656 if (i !== wordlist.getWordIndex(word)) {
16657 return "0x";
16658 }
16659 words.push(word);
16660 }
16661 return id(words.join("\n") + "\n");
16662 }
16663 static register(lang, name) {
16664 if (!name) {
16665 name = lang.locale;
16666 }
16667 /* istanbul ignore if */
16668 if (exportWordlist) {
16669 try {
16670 const anyGlobal = window;
16671 if (anyGlobal._ethers && anyGlobal._ethers.wordlists) {
16672 if (!anyGlobal._ethers.wordlists[name]) {
16673 defineReadOnly(anyGlobal._ethers.wordlists, name, lang);
16674 }
16675 }
16676 }
16677 catch (error) { }
16678 }
16679 }
16680}
16681
16682"use strict";
16683const words = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo";
16684let wordlist = null;
16685function loadWords(lang) {
16686 if (wordlist != null) {
16687 return;
16688 }
16689 wordlist = words.replace(/([A-Z])/g, " $1").toLowerCase().substring(1).split(" ");
16690 // Verify the computed list matches the official list
16691 /* istanbul ignore if */
16692 if (Wordlist.check(lang) !== "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60") {
16693 wordlist = null;
16694 throw new Error("BIP39 Wordlist for en (English) FAILED");
16695 }
16696}
16697class LangEn extends Wordlist {
16698 constructor() {
16699 super("en");
16700 }
16701 getWord(index) {
16702 loadWords(this);
16703 return wordlist[index];
16704 }
16705 getWordIndex(word) {
16706 loadWords(this);
16707 return wordlist.indexOf(word);
16708 }
16709}
16710const langEn = new LangEn();
16711Wordlist.register(langEn);
16712
16713"use strict";
16714const wordlists = { en: langEn };
16715
16716const version$g = "hdnode/5.0.2";
16717
16718"use strict";
16719const logger$j = new Logger(version$g);
16720const N = BigNumber.from("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
16721// "Bitcoin seed"
16722const MasterSecret = toUtf8Bytes("Bitcoin seed");
16723const HardenedBit = 0x80000000;
16724// Returns a byte with the MSB bits set
16725function getUpperMask(bits) {
16726 return ((1 << bits) - 1) << (8 - bits);
16727}
16728// Returns a byte with the LSB bits set
16729function getLowerMask(bits) {
16730 return (1 << bits) - 1;
16731}
16732function bytes32(value) {
16733 return hexZeroPad(hexlify(value), 32);
16734}
16735function base58check(data) {
16736 return Base58.encode(concat([data, hexDataSlice(browser_3(browser_3(data)), 0, 4)]));
16737}
16738function getWordlist(wordlist) {
16739 if (wordlist == null) {
16740 return wordlists["en"];
16741 }
16742 if (typeof (wordlist) === "string") {
16743 const words = wordlists[wordlist];
16744 if (words == null) {
16745 logger$j.throwArgumentError("unknown locale", "wordlist", wordlist);
16746 }
16747 return words;
16748 }
16749 return wordlist;
16750}
16751const _constructorGuard$3 = {};
16752const defaultPath = "m/44'/60'/0'/0/0";
16753;
16754class HDNode {
16755 /**
16756 * This constructor should not be called directly.
16757 *
16758 * Please use:
16759 * - fromMnemonic
16760 * - fromSeed
16761 */
16762 constructor(constructorGuard, privateKey, publicKey, parentFingerprint, chainCode, index, depth, mnemonicOrPath) {
16763 logger$j.checkNew(new.target, HDNode);
16764 /* istanbul ignore if */
16765 if (constructorGuard !== _constructorGuard$3) {
16766 throw new Error("HDNode constructor cannot be called directly");
16767 }
16768 if (privateKey) {
16769 const signingKey = new SigningKey(privateKey);
16770 defineReadOnly(this, "privateKey", signingKey.privateKey);
16771 defineReadOnly(this, "publicKey", signingKey.compressedPublicKey);
16772 }
16773 else {
16774 defineReadOnly(this, "privateKey", null);
16775 defineReadOnly(this, "publicKey", hexlify(publicKey));
16776 }
16777 defineReadOnly(this, "parentFingerprint", parentFingerprint);
16778 defineReadOnly(this, "fingerprint", hexDataSlice(browser_2(browser_3(this.publicKey)), 0, 4));
16779 defineReadOnly(this, "address", computeAddress(this.publicKey));
16780 defineReadOnly(this, "chainCode", chainCode);
16781 defineReadOnly(this, "index", index);
16782 defineReadOnly(this, "depth", depth);
16783 if (mnemonicOrPath == null) {
16784 // From a source that does not preserve the path (e.g. extended keys)
16785 defineReadOnly(this, "mnemonic", null);
16786 defineReadOnly(this, "path", null);
16787 }
16788 else if (typeof (mnemonicOrPath) === "string") {
16789 // From a source that does not preserve the mnemonic (e.g. neutered)
16790 defineReadOnly(this, "mnemonic", null);
16791 defineReadOnly(this, "path", mnemonicOrPath);
16792 }
16793 else {
16794 // From a fully qualified source
16795 defineReadOnly(this, "mnemonic", mnemonicOrPath);
16796 defineReadOnly(this, "path", mnemonicOrPath.path);
16797 }
16798 }
16799 get extendedKey() {
16800 // We only support the mainnet values for now, but if anyone needs
16801 // testnet values, let me know. I believe current senitment is that
16802 // we should always use mainnet, and use BIP-44 to derive the network
16803 // - Mainnet: public=0x0488B21E, private=0x0488ADE4
16804 // - Testnet: public=0x043587CF, private=0x04358394
16805 if (this.depth >= 256) {
16806 throw new Error("Depth too large!");
16807 }
16808 return base58check(concat([
16809 ((this.privateKey != null) ? "0x0488ADE4" : "0x0488B21E"),
16810 hexlify(this.depth),
16811 this.parentFingerprint,
16812 hexZeroPad(hexlify(this.index), 4),
16813 this.chainCode,
16814 ((this.privateKey != null) ? concat(["0x00", this.privateKey]) : this.publicKey),
16815 ]));
16816 }
16817 neuter() {
16818 return new HDNode(_constructorGuard$3, null, this.publicKey, this.parentFingerprint, this.chainCode, this.index, this.depth, this.path);
16819 }
16820 _derive(index) {
16821 if (index > 0xffffffff) {
16822 throw new Error("invalid index - " + String(index));
16823 }
16824 // Base path
16825 let path = this.path;
16826 if (path) {
16827 path += "/" + (index & ~HardenedBit);
16828 }
16829 const data = new Uint8Array(37);
16830 if (index & HardenedBit) {
16831 if (!this.privateKey) {
16832 throw new Error("cannot derive child of neutered node");
16833 }
16834 // Data = 0x00 || ser_256(k_par)
16835 data.set(arrayify(this.privateKey), 1);
16836 // Hardened path
16837 if (path) {
16838 path += "'";
16839 }
16840 }
16841 else {
16842 // Data = ser_p(point(k_par))
16843 data.set(arrayify(this.publicKey));
16844 }
16845 // Data += ser_32(i)
16846 for (let i = 24; i >= 0; i -= 8) {
16847 data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff);
16848 }
16849 const I = arrayify(browser_5(browser_1.sha512, this.chainCode, data));
16850 const IL = I.slice(0, 32);
16851 const IR = I.slice(32);
16852 // The private key
16853 let ki = null;
16854 // The public key
16855 let Ki = null;
16856 if (this.privateKey) {
16857 ki = bytes32(BigNumber.from(IL).add(this.privateKey).mod(N));
16858 }
16859 else {
16860 const ek = new SigningKey(hexlify(IL));
16861 Ki = ek._addPoint(this.publicKey);
16862 }
16863 let mnemonicOrPath = path;
16864 const srcMnemonic = this.mnemonic;
16865 if (srcMnemonic) {
16866 mnemonicOrPath = Object.freeze({
16867 phrase: srcMnemonic.phrase,
16868 path: path,
16869 locale: (srcMnemonic.locale || "en")
16870 });
16871 }
16872 return new HDNode(_constructorGuard$3, ki, Ki, this.fingerprint, bytes32(IR), index, this.depth + 1, mnemonicOrPath);
16873 }
16874 derivePath(path) {
16875 const components = path.split("/");
16876 if (components.length === 0 || (components[0] === "m" && this.depth !== 0)) {
16877 throw new Error("invalid path - " + path);
16878 }
16879 if (components[0] === "m") {
16880 components.shift();
16881 }
16882 let result = this;
16883 for (let i = 0; i < components.length; i++) {
16884 const component = components[i];
16885 if (component.match(/^[0-9]+'$/)) {
16886 const index = parseInt(component.substring(0, component.length - 1));
16887 if (index >= HardenedBit) {
16888 throw new Error("invalid path index - " + component);
16889 }
16890 result = result._derive(HardenedBit + index);
16891 }
16892 else if (component.match(/^[0-9]+$/)) {
16893 const index = parseInt(component);
16894 if (index >= HardenedBit) {
16895 throw new Error("invalid path index - " + component);
16896 }
16897 result = result._derive(index);
16898 }
16899 else {
16900 throw new Error("invalid path component - " + component);
16901 }
16902 }
16903 return result;
16904 }
16905 static _fromSeed(seed, mnemonic) {
16906 const seedArray = arrayify(seed);
16907 if (seedArray.length < 16 || seedArray.length > 64) {
16908 throw new Error("invalid seed");
16909 }
16910 const I = arrayify(browser_5(browser_1.sha512, MasterSecret, seedArray));
16911 return new HDNode(_constructorGuard$3, bytes32(I.slice(0, 32)), null, "0x00000000", bytes32(I.slice(32)), 0, 0, mnemonic);
16912 }
16913 static fromMnemonic(mnemonic, password, wordlist) {
16914 // If a locale name was passed in, find the associated wordlist
16915 wordlist = getWordlist(wordlist);
16916 // Normalize the case and spacing in the mnemonic (throws if the mnemonic is invalid)
16917 mnemonic = entropyToMnemonic(mnemonicToEntropy(mnemonic, wordlist), wordlist);
16918 return HDNode._fromSeed(mnemonicToSeed(mnemonic, password), {
16919 phrase: mnemonic,
16920 path: "m",
16921 locale: wordlist.locale
16922 });
16923 }
16924 static fromSeed(seed) {
16925 return HDNode._fromSeed(seed, null);
16926 }
16927 static fromExtendedKey(extendedKey) {
16928 const bytes = Base58.decode(extendedKey);
16929 if (bytes.length !== 82 || base58check(bytes.slice(0, 78)) !== extendedKey) {
16930 logger$j.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]");
16931 }
16932 const depth = bytes[4];
16933 const parentFingerprint = hexlify(bytes.slice(5, 9));
16934 const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16);
16935 const chainCode = hexlify(bytes.slice(13, 45));
16936 const key = bytes.slice(45, 78);
16937 switch (hexlify(bytes.slice(0, 4))) {
16938 // Public Key
16939 case "0x0488b21e":
16940 case "0x043587cf":
16941 return new HDNode(_constructorGuard$3, null, hexlify(key), parentFingerprint, chainCode, index, depth, null);
16942 // Private Key
16943 case "0x0488ade4":
16944 case "0x04358394 ":
16945 if (key[0] !== 0) {
16946 break;
16947 }
16948 return new HDNode(_constructorGuard$3, hexlify(key.slice(1)), null, parentFingerprint, chainCode, index, depth, null);
16949 }
16950 return logger$j.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]");
16951 }
16952}
16953function mnemonicToSeed(mnemonic, password) {
16954 if (!password) {
16955 password = "";
16956 }
16957 const salt = toUtf8Bytes("mnemonic" + password, UnicodeNormalizationForm.NFKD);
16958 return pbkdf2(toUtf8Bytes(mnemonic, UnicodeNormalizationForm.NFKD), salt, 2048, 64, "sha512");
16959}
16960function mnemonicToEntropy(mnemonic, wordlist) {
16961 wordlist = getWordlist(wordlist);
16962 logger$j.checkNormalize();
16963 const words = wordlist.split(mnemonic);
16964 if ((words.length % 3) !== 0) {
16965 throw new Error("invalid mnemonic");
16966 }
16967 const entropy = arrayify(new Uint8Array(Math.ceil(11 * words.length / 8)));
16968 let offset = 0;
16969 for (let i = 0; i < words.length; i++) {
16970 let index = wordlist.getWordIndex(words[i].normalize("NFKD"));
16971 if (index === -1) {
16972 throw new Error("invalid mnemonic");
16973 }
16974 for (let bit = 0; bit < 11; bit++) {
16975 if (index & (1 << (10 - bit))) {
16976 entropy[offset >> 3] |= (1 << (7 - (offset % 8)));
16977 }
16978 offset++;
16979 }
16980 }
16981 const entropyBits = 32 * words.length / 3;
16982 const checksumBits = words.length / 3;
16983 const checksumMask = getUpperMask(checksumBits);
16984 const checksum = arrayify(browser_3(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
16985 if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
16986 throw new Error("invalid checksum");
16987 }
16988 return hexlify(entropy.slice(0, entropyBits / 8));
16989}
16990function entropyToMnemonic(entropy, wordlist) {
16991 wordlist = getWordlist(wordlist);
16992 entropy = arrayify(entropy);
16993 if ((entropy.length % 4) !== 0 || entropy.length < 16 || entropy.length > 32) {
16994 throw new Error("invalid entropy");
16995 }
16996 const indices = [0];
16997 let remainingBits = 11;
16998 for (let i = 0; i < entropy.length; i++) {
16999 // Consume the whole byte (with still more to go)
17000 if (remainingBits > 8) {
17001 indices[indices.length - 1] <<= 8;
17002 indices[indices.length - 1] |= entropy[i];
17003 remainingBits -= 8;
17004 // This byte will complete an 11-bit index
17005 }
17006 else {
17007 indices[indices.length - 1] <<= remainingBits;
17008 indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits);
17009 // Start the next word
17010 indices.push(entropy[i] & getLowerMask(8 - remainingBits));
17011 remainingBits += 3;
17012 }
17013 }
17014 // Compute the checksum bits
17015 const checksumBits = entropy.length / 4;
17016 const checksum = arrayify(browser_3(entropy))[0] & getUpperMask(checksumBits);
17017 // Shift the checksum into the word indices
17018 indices[indices.length - 1] <<= checksumBits;
17019 indices[indices.length - 1] |= (checksum >> (8 - checksumBits));
17020 return wordlist.join(indices.map((index) => wordlist.getWord(index)));
17021}
17022function isValidMnemonic(mnemonic, wordlist) {
17023 try {
17024 mnemonicToEntropy(mnemonic, wordlist);
17025 return true;
17026 }
17027 catch (error) { }
17028 return false;
17029}
17030
17031const version$h = "random/5.0.2";
17032
17033"use strict";
17034function shuffled(array) {
17035 array = array.slice();
17036 for (let i = array.length - 1; i > 0; i--) {
17037 const j = Math.floor(Math.random() * (i + 1));
17038 const tmp = array[i];
17039 array[i] = array[j];
17040 array[j] = tmp;
17041 }
17042 return array;
17043}
17044
17045"use strict";
17046const logger$k = new Logger(version$h);
17047let anyGlobal = null;
17048try {
17049 anyGlobal = window;
17050 if (anyGlobal == null) {
17051 throw new Error("try next");
17052 }
17053}
17054catch (error) {
17055 try {
17056 anyGlobal = global;
17057 if (anyGlobal == null) {
17058 throw new Error("try next");
17059 }
17060 }
17061 catch (error) {
17062 anyGlobal = {};
17063 }
17064}
17065let crypto = anyGlobal.crypto || anyGlobal.msCrypto;
17066if (!crypto || !crypto.getRandomValues) {
17067 logger$k.warn("WARNING: Missing strong random number source");
17068 crypto = {
17069 getRandomValues: function (buffer) {
17070 return logger$k.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
17071 operation: "crypto.getRandomValues"
17072 });
17073 }
17074 };
17075}
17076function randomBytes(length) {
17077 if (length <= 0 || length > 1024 || (length % 1)) {
17078 logger$k.throwArgumentError("invalid length", "length", length);
17079 }
17080 const result = new Uint8Array(length);
17081 crypto.getRandomValues(result);
17082 return arrayify(result);
17083}
17084;
17085
17086var aesJs = createCommonjsModule(function (module, exports) {
17087"use strict";
17088
17089(function(root) {
17090
17091 function checkInt(value) {
17092 return (parseInt(value) === value);
17093 }
17094
17095 function checkInts(arrayish) {
17096 if (!checkInt(arrayish.length)) { return false; }
17097
17098 for (var i = 0; i < arrayish.length; i++) {
17099 if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) {
17100 return false;
17101 }
17102 }
17103
17104 return true;
17105 }
17106
17107 function coerceArray(arg, copy) {
17108
17109 // ArrayBuffer view
17110 if (arg.buffer && ArrayBuffer.isView(arg) && arg.name === 'Uint8Array') {
17111
17112 if (copy) {
17113 if (arg.slice) {
17114 arg = arg.slice();
17115 } else {
17116 arg = Array.prototype.slice.call(arg);
17117 }
17118 }
17119
17120 return arg;
17121 }
17122
17123 // It's an array; check it is a valid representation of a byte
17124 if (Array.isArray(arg)) {
17125 if (!checkInts(arg)) {
17126 throw new Error('Array contains invalid value: ' + arg);
17127 }
17128
17129 return new Uint8Array(arg);
17130 }
17131
17132 // Something else, but behaves like an array (maybe a Buffer? Arguments?)
17133 if (checkInt(arg.length) && checkInts(arg)) {
17134 return new Uint8Array(arg);
17135 }
17136
17137 throw new Error('unsupported array-like object');
17138 }
17139
17140 function createArray(length) {
17141 return new Uint8Array(length);
17142 }
17143
17144 function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) {
17145 if (sourceStart != null || sourceEnd != null) {
17146 if (sourceArray.slice) {
17147 sourceArray = sourceArray.slice(sourceStart, sourceEnd);
17148 } else {
17149 sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd);
17150 }
17151 }
17152 targetArray.set(sourceArray, targetStart);
17153 }
17154
17155
17156
17157 var convertUtf8 = (function() {
17158 function toBytes(text) {
17159 var result = [], i = 0;
17160 text = encodeURI(text);
17161 while (i < text.length) {
17162 var c = text.charCodeAt(i++);
17163
17164 // if it is a % sign, encode the following 2 bytes as a hex value
17165 if (c === 37) {
17166 result.push(parseInt(text.substr(i, 2), 16));
17167 i += 2;
17168
17169 // otherwise, just the actual byte
17170 } else {
17171 result.push(c);
17172 }
17173 }
17174
17175 return coerceArray(result);
17176 }
17177
17178 function fromBytes(bytes) {
17179 var result = [], i = 0;
17180
17181 while (i < bytes.length) {
17182 var c = bytes[i];
17183
17184 if (c < 128) {
17185 result.push(String.fromCharCode(c));
17186 i++;
17187 } else if (c > 191 && c < 224) {
17188 result.push(String.fromCharCode(((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f)));
17189 i += 2;
17190 } else {
17191 result.push(String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f)));
17192 i += 3;
17193 }
17194 }
17195
17196 return result.join('');
17197 }
17198
17199 return {
17200 toBytes: toBytes,
17201 fromBytes: fromBytes,
17202 }
17203 })();
17204
17205 var convertHex = (function() {
17206 function toBytes(text) {
17207 var result = [];
17208 for (var i = 0; i < text.length; i += 2) {
17209 result.push(parseInt(text.substr(i, 2), 16));
17210 }
17211
17212 return result;
17213 }
17214
17215 // http://ixti.net/development/javascript/2011/11/11/base64-encodedecode-of-utf8-in-browser-with-js.html
17216 var Hex = '0123456789abcdef';
17217
17218 function fromBytes(bytes) {
17219 var result = [];
17220 for (var i = 0; i < bytes.length; i++) {
17221 var v = bytes[i];
17222 result.push(Hex[(v & 0xf0) >> 4] + Hex[v & 0x0f]);
17223 }
17224 return result.join('');
17225 }
17226
17227 return {
17228 toBytes: toBytes,
17229 fromBytes: fromBytes,
17230 }
17231 })();
17232
17233
17234 // Number of rounds by keysize
17235 var numberOfRounds = {16: 10, 24: 12, 32: 14};
17236
17237 // Round constant words
17238 var rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91];
17239
17240 // S-box and Inverse S-box (S is for Substitution)
17241 var S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];
17242 var Si =[0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d];
17243
17244 // Transformations for encryption
17245 var T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a];
17246 var T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616];
17247 var T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16];
17248 var T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c];
17249
17250 // Transformations for decryption
17251 var T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742];
17252 var T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857];
17253 var T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8];
17254 var T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0];
17255
17256 // Transformations for decryption key expansion
17257 var U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3];
17258 var U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697];
17259 var U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46];
17260 var U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d];
17261
17262 function convertToInt32(bytes) {
17263 var result = [];
17264 for (var i = 0; i < bytes.length; i += 4) {
17265 result.push(
17266 (bytes[i ] << 24) |
17267 (bytes[i + 1] << 16) |
17268 (bytes[i + 2] << 8) |
17269 bytes[i + 3]
17270 );
17271 }
17272 return result;
17273 }
17274
17275 var AES = function(key) {
17276 if (!(this instanceof AES)) {
17277 throw Error('AES must be instanitated with `new`');
17278 }
17279
17280 Object.defineProperty(this, 'key', {
17281 value: coerceArray(key, true)
17282 });
17283
17284 this._prepare();
17285 };
17286
17287
17288 AES.prototype._prepare = function() {
17289
17290 var rounds = numberOfRounds[this.key.length];
17291 if (rounds == null) {
17292 throw new Error('invalid key size (must be 16, 24 or 32 bytes)');
17293 }
17294
17295 // encryption round keys
17296 this._Ke = [];
17297
17298 // decryption round keys
17299 this._Kd = [];
17300
17301 for (var i = 0; i <= rounds; i++) {
17302 this._Ke.push([0, 0, 0, 0]);
17303 this._Kd.push([0, 0, 0, 0]);
17304 }
17305
17306 var roundKeyCount = (rounds + 1) * 4;
17307 var KC = this.key.length / 4;
17308
17309 // convert the key into ints
17310 var tk = convertToInt32(this.key);
17311
17312 // copy values into round key arrays
17313 var index;
17314 for (var i = 0; i < KC; i++) {
17315 index = i >> 2;
17316 this._Ke[index][i % 4] = tk[i];
17317 this._Kd[rounds - index][i % 4] = tk[i];
17318 }
17319
17320 // key expansion (fips-197 section 5.2)
17321 var rconpointer = 0;
17322 var t = KC, tt;
17323 while (t < roundKeyCount) {
17324 tt = tk[KC - 1];
17325 tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^
17326 (S[(tt >> 8) & 0xFF] << 16) ^
17327 (S[ tt & 0xFF] << 8) ^
17328 S[(tt >> 24) & 0xFF] ^
17329 (rcon[rconpointer] << 24));
17330 rconpointer += 1;
17331
17332 // key expansion (for non-256 bit)
17333 if (KC != 8) {
17334 for (var i = 1; i < KC; i++) {
17335 tk[i] ^= tk[i - 1];
17336 }
17337
17338 // key expansion for 256-bit keys is "slightly different" (fips-197)
17339 } else {
17340 for (var i = 1; i < (KC / 2); i++) {
17341 tk[i] ^= tk[i - 1];
17342 }
17343 tt = tk[(KC / 2) - 1];
17344
17345 tk[KC / 2] ^= (S[ tt & 0xFF] ^
17346 (S[(tt >> 8) & 0xFF] << 8) ^
17347 (S[(tt >> 16) & 0xFF] << 16) ^
17348 (S[(tt >> 24) & 0xFF] << 24));
17349
17350 for (var i = (KC / 2) + 1; i < KC; i++) {
17351 tk[i] ^= tk[i - 1];
17352 }
17353 }
17354
17355 // copy values into round key arrays
17356 var i = 0, r, c;
17357 while (i < KC && t < roundKeyCount) {
17358 r = t >> 2;
17359 c = t % 4;
17360 this._Ke[r][c] = tk[i];
17361 this._Kd[rounds - r][c] = tk[i++];
17362 t++;
17363 }
17364 }
17365
17366 // inverse-cipher-ify the decryption round key (fips-197 section 5.3)
17367 for (var r = 1; r < rounds; r++) {
17368 for (var c = 0; c < 4; c++) {
17369 tt = this._Kd[r][c];
17370 this._Kd[r][c] = (U1[(tt >> 24) & 0xFF] ^
17371 U2[(tt >> 16) & 0xFF] ^
17372 U3[(tt >> 8) & 0xFF] ^
17373 U4[ tt & 0xFF]);
17374 }
17375 }
17376 };
17377
17378 AES.prototype.encrypt = function(plaintext) {
17379 if (plaintext.length != 16) {
17380 throw new Error('invalid plaintext size (must be 16 bytes)');
17381 }
17382
17383 var rounds = this._Ke.length - 1;
17384 var a = [0, 0, 0, 0];
17385
17386 // convert plaintext to (ints ^ key)
17387 var t = convertToInt32(plaintext);
17388 for (var i = 0; i < 4; i++) {
17389 t[i] ^= this._Ke[0][i];
17390 }
17391
17392 // apply round transforms
17393 for (var r = 1; r < rounds; r++) {
17394 for (var i = 0; i < 4; i++) {
17395 a[i] = (T1[(t[ i ] >> 24) & 0xff] ^
17396 T2[(t[(i + 1) % 4] >> 16) & 0xff] ^
17397 T3[(t[(i + 2) % 4] >> 8) & 0xff] ^
17398 T4[ t[(i + 3) % 4] & 0xff] ^
17399 this._Ke[r][i]);
17400 }
17401 t = a.slice();
17402 }
17403
17404 // the last round is special
17405 var result = createArray(16), tt;
17406 for (var i = 0; i < 4; i++) {
17407 tt = this._Ke[rounds][i];
17408 result[4 * i ] = (S[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
17409 result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
17410 result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
17411 result[4 * i + 3] = (S[ t[(i + 3) % 4] & 0xff] ^ tt ) & 0xff;
17412 }
17413
17414 return result;
17415 };
17416
17417 AES.prototype.decrypt = function(ciphertext) {
17418 if (ciphertext.length != 16) {
17419 throw new Error('invalid ciphertext size (must be 16 bytes)');
17420 }
17421
17422 var rounds = this._Kd.length - 1;
17423 var a = [0, 0, 0, 0];
17424
17425 // convert plaintext to (ints ^ key)
17426 var t = convertToInt32(ciphertext);
17427 for (var i = 0; i < 4; i++) {
17428 t[i] ^= this._Kd[0][i];
17429 }
17430
17431 // apply round transforms
17432 for (var r = 1; r < rounds; r++) {
17433 for (var i = 0; i < 4; i++) {
17434 a[i] = (T5[(t[ i ] >> 24) & 0xff] ^
17435 T6[(t[(i + 3) % 4] >> 16) & 0xff] ^
17436 T7[(t[(i + 2) % 4] >> 8) & 0xff] ^
17437 T8[ t[(i + 1) % 4] & 0xff] ^
17438 this._Kd[r][i]);
17439 }
17440 t = a.slice();
17441 }
17442
17443 // the last round is special
17444 var result = createArray(16), tt;
17445 for (var i = 0; i < 4; i++) {
17446 tt = this._Kd[rounds][i];
17447 result[4 * i ] = (Si[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
17448 result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
17449 result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
17450 result[4 * i + 3] = (Si[ t[(i + 1) % 4] & 0xff] ^ tt ) & 0xff;
17451 }
17452
17453 return result;
17454 };
17455
17456
17457 /**
17458 * Mode Of Operation - Electonic Codebook (ECB)
17459 */
17460 var ModeOfOperationECB = function(key) {
17461 if (!(this instanceof ModeOfOperationECB)) {
17462 throw Error('AES must be instanitated with `new`');
17463 }
17464
17465 this.description = "Electronic Code Block";
17466 this.name = "ecb";
17467
17468 this._aes = new AES(key);
17469 };
17470
17471 ModeOfOperationECB.prototype.encrypt = function(plaintext) {
17472 plaintext = coerceArray(plaintext);
17473
17474 if ((plaintext.length % 16) !== 0) {
17475 throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
17476 }
17477
17478 var ciphertext = createArray(plaintext.length);
17479 var block = createArray(16);
17480
17481 for (var i = 0; i < plaintext.length; i += 16) {
17482 copyArray(plaintext, block, 0, i, i + 16);
17483 block = this._aes.encrypt(block);
17484 copyArray(block, ciphertext, i);
17485 }
17486
17487 return ciphertext;
17488 };
17489
17490 ModeOfOperationECB.prototype.decrypt = function(ciphertext) {
17491 ciphertext = coerceArray(ciphertext);
17492
17493 if ((ciphertext.length % 16) !== 0) {
17494 throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
17495 }
17496
17497 var plaintext = createArray(ciphertext.length);
17498 var block = createArray(16);
17499
17500 for (var i = 0; i < ciphertext.length; i += 16) {
17501 copyArray(ciphertext, block, 0, i, i + 16);
17502 block = this._aes.decrypt(block);
17503 copyArray(block, plaintext, i);
17504 }
17505
17506 return plaintext;
17507 };
17508
17509
17510 /**
17511 * Mode Of Operation - Cipher Block Chaining (CBC)
17512 */
17513 var ModeOfOperationCBC = function(key, iv) {
17514 if (!(this instanceof ModeOfOperationCBC)) {
17515 throw Error('AES must be instanitated with `new`');
17516 }
17517
17518 this.description = "Cipher Block Chaining";
17519 this.name = "cbc";
17520
17521 if (!iv) {
17522 iv = createArray(16);
17523
17524 } else if (iv.length != 16) {
17525 throw new Error('invalid initialation vector size (must be 16 bytes)');
17526 }
17527
17528 this._lastCipherblock = coerceArray(iv, true);
17529
17530 this._aes = new AES(key);
17531 };
17532
17533 ModeOfOperationCBC.prototype.encrypt = function(plaintext) {
17534 plaintext = coerceArray(plaintext);
17535
17536 if ((plaintext.length % 16) !== 0) {
17537 throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
17538 }
17539
17540 var ciphertext = createArray(plaintext.length);
17541 var block = createArray(16);
17542
17543 for (var i = 0; i < plaintext.length; i += 16) {
17544 copyArray(plaintext, block, 0, i, i + 16);
17545
17546 for (var j = 0; j < 16; j++) {
17547 block[j] ^= this._lastCipherblock[j];
17548 }
17549
17550 this._lastCipherblock = this._aes.encrypt(block);
17551 copyArray(this._lastCipherblock, ciphertext, i);
17552 }
17553
17554 return ciphertext;
17555 };
17556
17557 ModeOfOperationCBC.prototype.decrypt = function(ciphertext) {
17558 ciphertext = coerceArray(ciphertext);
17559
17560 if ((ciphertext.length % 16) !== 0) {
17561 throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
17562 }
17563
17564 var plaintext = createArray(ciphertext.length);
17565 var block = createArray(16);
17566
17567 for (var i = 0; i < ciphertext.length; i += 16) {
17568 copyArray(ciphertext, block, 0, i, i + 16);
17569 block = this._aes.decrypt(block);
17570
17571 for (var j = 0; j < 16; j++) {
17572 plaintext[i + j] = block[j] ^ this._lastCipherblock[j];
17573 }
17574
17575 copyArray(ciphertext, this._lastCipherblock, 0, i, i + 16);
17576 }
17577
17578 return plaintext;
17579 };
17580
17581
17582 /**
17583 * Mode Of Operation - Cipher Feedback (CFB)
17584 */
17585 var ModeOfOperationCFB = function(key, iv, segmentSize) {
17586 if (!(this instanceof ModeOfOperationCFB)) {
17587 throw Error('AES must be instanitated with `new`');
17588 }
17589
17590 this.description = "Cipher Feedback";
17591 this.name = "cfb";
17592
17593 if (!iv) {
17594 iv = createArray(16);
17595
17596 } else if (iv.length != 16) {
17597 throw new Error('invalid initialation vector size (must be 16 size)');
17598 }
17599
17600 if (!segmentSize) { segmentSize = 1; }
17601
17602 this.segmentSize = segmentSize;
17603
17604 this._shiftRegister = coerceArray(iv, true);
17605
17606 this._aes = new AES(key);
17607 };
17608
17609 ModeOfOperationCFB.prototype.encrypt = function(plaintext) {
17610 if ((plaintext.length % this.segmentSize) != 0) {
17611 throw new Error('invalid plaintext size (must be segmentSize bytes)');
17612 }
17613
17614 var encrypted = coerceArray(plaintext, true);
17615
17616 var xorSegment;
17617 for (var i = 0; i < encrypted.length; i += this.segmentSize) {
17618 xorSegment = this._aes.encrypt(this._shiftRegister);
17619 for (var j = 0; j < this.segmentSize; j++) {
17620 encrypted[i + j] ^= xorSegment[j];
17621 }
17622
17623 // Shift the register
17624 copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
17625 copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
17626 }
17627
17628 return encrypted;
17629 };
17630
17631 ModeOfOperationCFB.prototype.decrypt = function(ciphertext) {
17632 if ((ciphertext.length % this.segmentSize) != 0) {
17633 throw new Error('invalid ciphertext size (must be segmentSize bytes)');
17634 }
17635
17636 var plaintext = coerceArray(ciphertext, true);
17637
17638 var xorSegment;
17639 for (var i = 0; i < plaintext.length; i += this.segmentSize) {
17640 xorSegment = this._aes.encrypt(this._shiftRegister);
17641
17642 for (var j = 0; j < this.segmentSize; j++) {
17643 plaintext[i + j] ^= xorSegment[j];
17644 }
17645
17646 // Shift the register
17647 copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
17648 copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
17649 }
17650
17651 return plaintext;
17652 };
17653
17654 /**
17655 * Mode Of Operation - Output Feedback (OFB)
17656 */
17657 var ModeOfOperationOFB = function(key, iv) {
17658 if (!(this instanceof ModeOfOperationOFB)) {
17659 throw Error('AES must be instanitated with `new`');
17660 }
17661
17662 this.description = "Output Feedback";
17663 this.name = "ofb";
17664
17665 if (!iv) {
17666 iv = createArray(16);
17667
17668 } else if (iv.length != 16) {
17669 throw new Error('invalid initialation vector size (must be 16 bytes)');
17670 }
17671
17672 this._lastPrecipher = coerceArray(iv, true);
17673 this._lastPrecipherIndex = 16;
17674
17675 this._aes = new AES(key);
17676 };
17677
17678 ModeOfOperationOFB.prototype.encrypt = function(plaintext) {
17679 var encrypted = coerceArray(plaintext, true);
17680
17681 for (var i = 0; i < encrypted.length; i++) {
17682 if (this._lastPrecipherIndex === 16) {
17683 this._lastPrecipher = this._aes.encrypt(this._lastPrecipher);
17684 this._lastPrecipherIndex = 0;
17685 }
17686 encrypted[i] ^= this._lastPrecipher[this._lastPrecipherIndex++];
17687 }
17688
17689 return encrypted;
17690 };
17691
17692 // Decryption is symetric
17693 ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt;
17694
17695
17696 /**
17697 * Counter object for CTR common mode of operation
17698 */
17699 var Counter = function(initialValue) {
17700 if (!(this instanceof Counter)) {
17701 throw Error('Counter must be instanitated with `new`');
17702 }
17703
17704 // We allow 0, but anything false-ish uses the default 1
17705 if (initialValue !== 0 && !initialValue) { initialValue = 1; }
17706
17707 if (typeof(initialValue) === 'number') {
17708 this._counter = createArray(16);
17709 this.setValue(initialValue);
17710
17711 } else {
17712 this.setBytes(initialValue);
17713 }
17714 };
17715
17716 Counter.prototype.setValue = function(value) {
17717 if (typeof(value) !== 'number' || parseInt(value) != value) {
17718 throw new Error('invalid counter value (must be an integer)');
17719 }
17720
17721 for (var index = 15; index >= 0; --index) {
17722 this._counter[index] = value % 256;
17723 value = value >> 8;
17724 }
17725 };
17726
17727 Counter.prototype.setBytes = function(bytes) {
17728 bytes = coerceArray(bytes, true);
17729
17730 if (bytes.length != 16) {
17731 throw new Error('invalid counter bytes size (must be 16 bytes)');
17732 }
17733
17734 this._counter = bytes;
17735 };
17736
17737 Counter.prototype.increment = function() {
17738 for (var i = 15; i >= 0; i--) {
17739 if (this._counter[i] === 255) {
17740 this._counter[i] = 0;
17741 } else {
17742 this._counter[i]++;
17743 break;
17744 }
17745 }
17746 };
17747
17748
17749 /**
17750 * Mode Of Operation - Counter (CTR)
17751 */
17752 var ModeOfOperationCTR = function(key, counter) {
17753 if (!(this instanceof ModeOfOperationCTR)) {
17754 throw Error('AES must be instanitated with `new`');
17755 }
17756
17757 this.description = "Counter";
17758 this.name = "ctr";
17759
17760 if (!(counter instanceof Counter)) {
17761 counter = new Counter(counter);
17762 }
17763
17764 this._counter = counter;
17765
17766 this._remainingCounter = null;
17767 this._remainingCounterIndex = 16;
17768
17769 this._aes = new AES(key);
17770 };
17771
17772 ModeOfOperationCTR.prototype.encrypt = function(plaintext) {
17773 var encrypted = coerceArray(plaintext, true);
17774
17775 for (var i = 0; i < encrypted.length; i++) {
17776 if (this._remainingCounterIndex === 16) {
17777 this._remainingCounter = this._aes.encrypt(this._counter._counter);
17778 this._remainingCounterIndex = 0;
17779 this._counter.increment();
17780 }
17781 encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];
17782 }
17783
17784 return encrypted;
17785 };
17786
17787 // Decryption is symetric
17788 ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt;
17789
17790
17791 ///////////////////////
17792 // Padding
17793
17794 // See:https://tools.ietf.org/html/rfc2315
17795 function pkcs7pad(data) {
17796 data = coerceArray(data, true);
17797 var padder = 16 - (data.length % 16);
17798 var result = createArray(data.length + padder);
17799 copyArray(data, result);
17800 for (var i = data.length; i < result.length; i++) {
17801 result[i] = padder;
17802 }
17803 return result;
17804 }
17805
17806 function pkcs7strip(data) {
17807 data = coerceArray(data, true);
17808 if (data.length < 16) { throw new Error('PKCS#7 invalid length'); }
17809
17810 var padder = data[data.length - 1];
17811 if (padder > 16) { throw new Error('PKCS#7 padding byte out of range'); }
17812
17813 var length = data.length - padder;
17814 for (var i = 0; i < padder; i++) {
17815 if (data[length + i] !== padder) {
17816 throw new Error('PKCS#7 invalid padding byte');
17817 }
17818 }
17819
17820 var result = createArray(length);
17821 copyArray(data, result, 0, 0, length);
17822 return result;
17823 }
17824
17825 ///////////////////////
17826 // Exporting
17827
17828
17829 // The block cipher
17830 var aesjs = {
17831 AES: AES,
17832 Counter: Counter,
17833
17834 ModeOfOperation: {
17835 ecb: ModeOfOperationECB,
17836 cbc: ModeOfOperationCBC,
17837 cfb: ModeOfOperationCFB,
17838 ofb: ModeOfOperationOFB,
17839 ctr: ModeOfOperationCTR
17840 },
17841
17842 utils: {
17843 hex: convertHex,
17844 utf8: convertUtf8
17845 },
17846
17847 padding: {
17848 pkcs7: {
17849 pad: pkcs7pad,
17850 strip: pkcs7strip
17851 }
17852 },
17853
17854 _arrayTest: {
17855 coerceArray: coerceArray,
17856 createArray: createArray,
17857 copyArray: copyArray,
17858 }
17859 };
17860
17861
17862 // node.js
17863 if ('object' !== 'undefined') {
17864 module.exports = aesjs;
17865
17866 // RequireJS/AMD
17867 // http://www.requirejs.org/docs/api.html
17868 // https://github.com/amdjs/amdjs-api/wiki/AMD
17869 } else if (typeof(undefined) === 'function' && undefined.amd) {
17870 undefined(aesjs);
17871
17872 // Web Browsers
17873 } else {
17874
17875 // If there was an existing library at "aesjs" make sure it's still available
17876 if (root.aesjs) {
17877 aesjs._aesjs = root.aesjs;
17878 }
17879
17880 root.aesjs = aesjs;
17881 }
17882
17883
17884})(commonjsGlobal);
17885});
17886
17887const version$i = "json-wallets/5.0.4";
17888
17889"use strict";
17890function looseArrayify(hexString) {
17891 if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') {
17892 hexString = '0x' + hexString;
17893 }
17894 return arrayify(hexString);
17895}
17896function zpad(value, length) {
17897 value = String(value);
17898 while (value.length < length) {
17899 value = '0' + value;
17900 }
17901 return value;
17902}
17903function getPassword(password) {
17904 if (typeof (password) === 'string') {
17905 return toUtf8Bytes(password, UnicodeNormalizationForm.NFKC);
17906 }
17907 return arrayify(password);
17908}
17909function searchPath(object, path) {
17910 let currentChild = object;
17911 const comps = path.toLowerCase().split('/');
17912 for (let i = 0; i < comps.length; i++) {
17913 // Search for a child object with a case-insensitive matching key
17914 let matchingChild = null;
17915 for (const key in currentChild) {
17916 if (key.toLowerCase() === comps[i]) {
17917 matchingChild = currentChild[key];
17918 break;
17919 }
17920 }
17921 // Didn't find one. :'(
17922 if (matchingChild === null) {
17923 return null;
17924 }
17925 // Now check this child...
17926 currentChild = matchingChild;
17927 }
17928 return currentChild;
17929}
17930// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
17931function uuidV4(randomBytes) {
17932 const bytes = arrayify(randomBytes);
17933 // Section: 4.1.3:
17934 // - time_hi_and_version[12:16] = 0b0100
17935 bytes[6] = (bytes[6] & 0x0f) | 0x40;
17936 // Section 4.4
17937 // - clock_seq_hi_and_reserved[6] = 0b0
17938 // - clock_seq_hi_and_reserved[7] = 0b1
17939 bytes[8] = (bytes[8] & 0x3f) | 0x80;
17940 const value = hexlify(bytes);
17941 return [
17942 value.substring(2, 10),
17943 value.substring(10, 14),
17944 value.substring(14, 18),
17945 value.substring(18, 22),
17946 value.substring(22, 34),
17947 ].join("-");
17948}
17949
17950"use strict";
17951const logger$l = new Logger(version$i);
17952class CrowdsaleAccount extends Description {
17953 isCrowdsaleAccount(value) {
17954 return !!(value && value._isCrowdsaleAccount);
17955 }
17956}
17957// See: https://github.com/ethereum/pyethsaletool
17958function decrypt(json, password) {
17959 const data = JSON.parse(json);
17960 password = getPassword(password);
17961 // Ethereum Address
17962 const ethaddr = getAddress(searchPath(data, "ethaddr"));
17963 // Encrypted Seed
17964 const encseed = looseArrayify(searchPath(data, "encseed"));
17965 if (!encseed || (encseed.length % 16) !== 0) {
17966 logger$l.throwArgumentError("invalid encseed", "json", json);
17967 }
17968 const key = arrayify(pbkdf2(password, password, 2000, 32, "sha256")).slice(0, 16);
17969 const iv = encseed.slice(0, 16);
17970 const encryptedSeed = encseed.slice(16);
17971 // Decrypt the seed
17972 const aesCbc = new aesJs.ModeOfOperation.cbc(key, iv);
17973 const seed = aesJs.padding.pkcs7.strip(arrayify(aesCbc.decrypt(encryptedSeed)));
17974 // This wallet format is weird... Convert the binary encoded hex to a string.
17975 let seedHex = "";
17976 for (let i = 0; i < seed.length; i++) {
17977 seedHex += String.fromCharCode(seed[i]);
17978 }
17979 const seedHexBytes = toUtf8Bytes(seedHex);
17980 const privateKey = keccak256(seedHexBytes);
17981 return new CrowdsaleAccount({
17982 _isCrowdsaleAccount: true,
17983 address: ethaddr,
17984 privateKey: privateKey
17985 });
17986}
17987
17988"use strict";
17989function isCrowdsaleWallet(json) {
17990 let data = null;
17991 try {
17992 data = JSON.parse(json);
17993 }
17994 catch (error) {
17995 return false;
17996 }
17997 return (data.encseed && data.ethaddr);
17998}
17999function isKeystoreWallet(json) {
18000 let data = null;
18001 try {
18002 data = JSON.parse(json);
18003 }
18004 catch (error) {
18005 return false;
18006 }
18007 if (!data.version || parseInt(data.version) !== data.version || parseInt(data.version) !== 3) {
18008 return false;
18009 }
18010 // @TODO: Put more checks to make sure it has kdf, iv and all that good stuff
18011 return true;
18012}
18013//export function isJsonWallet(json: string): boolean {
18014// return (isSecretStorageWallet(json) || isCrowdsaleWallet(json));
18015//}
18016function getJsonWalletAddress(json) {
18017 if (isCrowdsaleWallet(json)) {
18018 try {
18019 return getAddress(JSON.parse(json).ethaddr);
18020 }
18021 catch (error) {
18022 return null;
18023 }
18024 }
18025 if (isKeystoreWallet(json)) {
18026 try {
18027 return getAddress(JSON.parse(json).address);
18028 }
18029 catch (error) {
18030 return null;
18031 }
18032 }
18033 return null;
18034}
18035
18036var scrypt = createCommonjsModule(function (module, exports) {
18037"use strict";
18038
18039(function(root) {
18040 const MAX_VALUE = 0x7fffffff;
18041
18042 // The SHA256 and PBKDF2 implementation are from scrypt-async-js:
18043 // See: https://github.com/dchest/scrypt-async-js
18044 function SHA256(m) {
18045 const K = new Uint32Array([
18046 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
18047 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
18048 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
18049 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
18050 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
18051 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
18052 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
18053 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
18054 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
18055 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
18056 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
18057 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
18058 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
18059 ]);
18060
18061 let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
18062 let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
18063 const w = new Uint32Array(64);
18064
18065 function blocks(p) {
18066 let off = 0, len = p.length;
18067 while (len >= 64) {
18068 let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7, u, i, j, t1, t2;
18069
18070 for (i = 0; i < 16; i++) {
18071 j = off + i*4;
18072 w[i] = ((p[j] & 0xff)<<24) | ((p[j+1] & 0xff)<<16) |
18073 ((p[j+2] & 0xff)<<8) | (p[j+3] & 0xff);
18074 }
18075
18076 for (i = 16; i < 64; i++) {
18077 u = w[i-2];
18078 t1 = ((u>>>17) | (u<<(32-17))) ^ ((u>>>19) | (u<<(32-19))) ^ (u>>>10);
18079
18080 u = w[i-15];
18081 t2 = ((u>>>7) | (u<<(32-7))) ^ ((u>>>18) | (u<<(32-18))) ^ (u>>>3);
18082
18083 w[i] = (((t1 + w[i-7]) | 0) + ((t2 + w[i-16]) | 0)) | 0;
18084 }
18085
18086 for (i = 0; i < 64; i++) {
18087 t1 = ((((((e>>>6) | (e<<(32-6))) ^ ((e>>>11) | (e<<(32-11))) ^
18088 ((e>>>25) | (e<<(32-25)))) + ((e & f) ^ (~e & g))) | 0) +
18089 ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;
18090
18091 t2 = ((((a>>>2) | (a<<(32-2))) ^ ((a>>>13) | (a<<(32-13))) ^
18092 ((a>>>22) | (a<<(32-22)))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
18093
18094 h = g;
18095 g = f;
18096 f = e;
18097 e = (d + t1) | 0;
18098 d = c;
18099 c = b;
18100 b = a;
18101 a = (t1 + t2) | 0;
18102 }
18103
18104 h0 = (h0 + a) | 0;
18105 h1 = (h1 + b) | 0;
18106 h2 = (h2 + c) | 0;
18107 h3 = (h3 + d) | 0;
18108 h4 = (h4 + e) | 0;
18109 h5 = (h5 + f) | 0;
18110 h6 = (h6 + g) | 0;
18111 h7 = (h7 + h) | 0;
18112
18113 off += 64;
18114 len -= 64;
18115 }
18116 }
18117
18118 blocks(m);
18119
18120 let i, bytesLeft = m.length % 64,
18121 bitLenHi = (m.length / 0x20000000) | 0,
18122 bitLenLo = m.length << 3,
18123 numZeros = (bytesLeft < 56) ? 56 : 120,
18124 p = m.slice(m.length - bytesLeft, m.length);
18125
18126 p.push(0x80);
18127 for (i = bytesLeft + 1; i < numZeros; i++) { p.push(0); }
18128 p.push((bitLenHi >>> 24) & 0xff);
18129 p.push((bitLenHi >>> 16) & 0xff);
18130 p.push((bitLenHi >>> 8) & 0xff);
18131 p.push((bitLenHi >>> 0) & 0xff);
18132 p.push((bitLenLo >>> 24) & 0xff);
18133 p.push((bitLenLo >>> 16) & 0xff);
18134 p.push((bitLenLo >>> 8) & 0xff);
18135 p.push((bitLenLo >>> 0) & 0xff);
18136
18137 blocks(p);
18138
18139 return [
18140 (h0 >>> 24) & 0xff, (h0 >>> 16) & 0xff, (h0 >>> 8) & 0xff, (h0 >>> 0) & 0xff,
18141 (h1 >>> 24) & 0xff, (h1 >>> 16) & 0xff, (h1 >>> 8) & 0xff, (h1 >>> 0) & 0xff,
18142 (h2 >>> 24) & 0xff, (h2 >>> 16) & 0xff, (h2 >>> 8) & 0xff, (h2 >>> 0) & 0xff,
18143 (h3 >>> 24) & 0xff, (h3 >>> 16) & 0xff, (h3 >>> 8) & 0xff, (h3 >>> 0) & 0xff,
18144 (h4 >>> 24) & 0xff, (h4 >>> 16) & 0xff, (h4 >>> 8) & 0xff, (h4 >>> 0) & 0xff,
18145 (h5 >>> 24) & 0xff, (h5 >>> 16) & 0xff, (h5 >>> 8) & 0xff, (h5 >>> 0) & 0xff,
18146 (h6 >>> 24) & 0xff, (h6 >>> 16) & 0xff, (h6 >>> 8) & 0xff, (h6 >>> 0) & 0xff,
18147 (h7 >>> 24) & 0xff, (h7 >>> 16) & 0xff, (h7 >>> 8) & 0xff, (h7 >>> 0) & 0xff
18148 ];
18149 }
18150
18151 function PBKDF2_HMAC_SHA256_OneIter(password, salt, dkLen) {
18152 // compress password if it's longer than hash block length
18153 password = (password.length <= 64) ? password : SHA256(password);
18154
18155 const innerLen = 64 + salt.length + 4;
18156 const inner = new Array(innerLen);
18157 const outerKey = new Array(64);
18158
18159 let i;
18160 let dk = [];
18161
18162 // inner = (password ^ ipad) || salt || counter
18163 for (i = 0; i < 64; i++) { inner[i] = 0x36; }
18164 for (i = 0; i < password.length; i++) { inner[i] ^= password[i]; }
18165 for (i = 0; i < salt.length; i++) { inner[64 + i] = salt[i]; }
18166 for (i = innerLen - 4; i < innerLen; i++) { inner[i] = 0; }
18167
18168 // outerKey = password ^ opad
18169 for (i = 0; i < 64; i++) outerKey[i] = 0x5c;
18170 for (i = 0; i < password.length; i++) outerKey[i] ^= password[i];
18171
18172 // increments counter inside inner
18173 function incrementCounter() {
18174 for (let i = innerLen - 1; i >= innerLen - 4; i--) {
18175 inner[i]++;
18176 if (inner[i] <= 0xff) return;
18177 inner[i] = 0;
18178 }
18179 }
18180
18181 // output blocks = SHA256(outerKey || SHA256(inner)) ...
18182 while (dkLen >= 32) {
18183 incrementCounter();
18184 dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))));
18185 dkLen -= 32;
18186 }
18187 if (dkLen > 0) {
18188 incrementCounter();
18189 dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))).slice(0, dkLen));
18190 }
18191
18192 return dk;
18193 }
18194
18195 // The following is an adaptation of scryptsy
18196 // See: https://www.npmjs.com/package/scryptsy
18197 function blockmix_salsa8(BY, Yi, r, x, _X) {
18198 let i;
18199
18200 arraycopy(BY, (2 * r - 1) * 16, _X, 0, 16);
18201 for (i = 0; i < 2 * r; i++) {
18202 blockxor(BY, i * 16, _X, 16);
18203 salsa20_8(_X, x);
18204 arraycopy(_X, 0, BY, Yi + (i * 16), 16);
18205 }
18206
18207 for (i = 0; i < r; i++) {
18208 arraycopy(BY, Yi + (i * 2) * 16, BY, (i * 16), 16);
18209 }
18210
18211 for (i = 0; i < r; i++) {
18212 arraycopy(BY, Yi + (i * 2 + 1) * 16, BY, (i + r) * 16, 16);
18213 }
18214 }
18215
18216 function R(a, b) {
18217 return (a << b) | (a >>> (32 - b));
18218 }
18219
18220 function salsa20_8(B, x) {
18221 arraycopy(B, 0, x, 0, 16);
18222
18223 for (let i = 8; i > 0; i -= 2) {
18224 x[ 4] ^= R(x[ 0] + x[12], 7);
18225 x[ 8] ^= R(x[ 4] + x[ 0], 9);
18226 x[12] ^= R(x[ 8] + x[ 4], 13);
18227 x[ 0] ^= R(x[12] + x[ 8], 18);
18228 x[ 9] ^= R(x[ 5] + x[ 1], 7);
18229 x[13] ^= R(x[ 9] + x[ 5], 9);
18230 x[ 1] ^= R(x[13] + x[ 9], 13);
18231 x[ 5] ^= R(x[ 1] + x[13], 18);
18232 x[14] ^= R(x[10] + x[ 6], 7);
18233 x[ 2] ^= R(x[14] + x[10], 9);
18234 x[ 6] ^= R(x[ 2] + x[14], 13);
18235 x[10] ^= R(x[ 6] + x[ 2], 18);
18236 x[ 3] ^= R(x[15] + x[11], 7);
18237 x[ 7] ^= R(x[ 3] + x[15], 9);
18238 x[11] ^= R(x[ 7] + x[ 3], 13);
18239 x[15] ^= R(x[11] + x[ 7], 18);
18240 x[ 1] ^= R(x[ 0] + x[ 3], 7);
18241 x[ 2] ^= R(x[ 1] + x[ 0], 9);
18242 x[ 3] ^= R(x[ 2] + x[ 1], 13);
18243 x[ 0] ^= R(x[ 3] + x[ 2], 18);
18244 x[ 6] ^= R(x[ 5] + x[ 4], 7);
18245 x[ 7] ^= R(x[ 6] + x[ 5], 9);
18246 x[ 4] ^= R(x[ 7] + x[ 6], 13);
18247 x[ 5] ^= R(x[ 4] + x[ 7], 18);
18248 x[11] ^= R(x[10] + x[ 9], 7);
18249 x[ 8] ^= R(x[11] + x[10], 9);
18250 x[ 9] ^= R(x[ 8] + x[11], 13);
18251 x[10] ^= R(x[ 9] + x[ 8], 18);
18252 x[12] ^= R(x[15] + x[14], 7);
18253 x[13] ^= R(x[12] + x[15], 9);
18254 x[14] ^= R(x[13] + x[12], 13);
18255 x[15] ^= R(x[14] + x[13], 18);
18256 }
18257
18258 for (let i = 0; i < 16; ++i) {
18259 B[i] += x[i];
18260 }
18261 }
18262
18263 // naive approach... going back to loop unrolling may yield additional performance
18264 function blockxor(S, Si, D, len) {
18265 for (let i = 0; i < len; i++) {
18266 D[i] ^= S[Si + i];
18267 }
18268 }
18269
18270 function arraycopy(src, srcPos, dest, destPos, length) {
18271 while (length--) {
18272 dest[destPos++] = src[srcPos++];
18273 }
18274 }
18275
18276 function checkBufferish(o) {
18277 if (!o || typeof(o.length) !== 'number') { return false; }
18278
18279 for (let i = 0; i < o.length; i++) {
18280 const v = o[i];
18281 if (typeof(v) !== 'number' || v % 1 || v < 0 || v >= 256) {
18282 return false;
18283 }
18284 }
18285
18286 return true;
18287 }
18288
18289 function ensureInteger(value, name) {
18290 if (typeof(value) !== "number" || (value % 1)) { throw new Error('invalid ' + name); }
18291 return value;
18292 }
18293
18294 // N = Cpu cost, r = Memory cost, p = parallelization cost
18295 // callback(error, progress, key)
18296 function _scrypt(password, salt, N, r, p, dkLen, callback) {
18297
18298 N = ensureInteger(N, 'N');
18299 r = ensureInteger(r, 'r');
18300 p = ensureInteger(p, 'p');
18301
18302 dkLen = ensureInteger(dkLen, 'dkLen');
18303
18304 if (N === 0 || (N & (N - 1)) !== 0) { throw new Error('N must be power of 2'); }
18305
18306 if (N > MAX_VALUE / 128 / r) { throw new Error('N too large'); }
18307 if (r > MAX_VALUE / 128 / p) { throw new Error('r too large'); }
18308
18309 if (!checkBufferish(password)) {
18310 throw new Error('password must be an array or buffer');
18311 }
18312 password = Array.prototype.slice.call(password);
18313
18314 if (!checkBufferish(salt)) {
18315 throw new Error('salt must be an array or buffer');
18316 }
18317 salt = Array.prototype.slice.call(salt);
18318
18319 let b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r);
18320 const B = new Uint32Array(p * 32 * r);
18321 for (let i = 0; i < B.length; i++) {
18322 const j = i * 4;
18323 B[i] = ((b[j + 3] & 0xff) << 24) |
18324 ((b[j + 2] & 0xff) << 16) |
18325 ((b[j + 1] & 0xff) << 8) |
18326 ((b[j + 0] & 0xff) << 0);
18327 }
18328
18329 const XY = new Uint32Array(64 * r);
18330 const V = new Uint32Array(32 * r * N);
18331
18332 const Yi = 32 * r;
18333
18334 // scratch space
18335 const x = new Uint32Array(16); // salsa20_8
18336 const _X = new Uint32Array(16); // blockmix_salsa8
18337
18338 const totalOps = p * N * 2;
18339 let currentOp = 0;
18340 let lastPercent10 = null;
18341
18342 // Set this to true to abandon the scrypt on the next step
18343 let stop = false;
18344
18345 // State information
18346 let state = 0;
18347 let i0 = 0, i1;
18348 let Bi;
18349
18350 // How many blockmix_salsa8 can we do per step?
18351 const limit = callback ? parseInt(1000 / r): 0xffffffff;
18352
18353 // Trick from scrypt-async; if there is a setImmediate shim in place, use it
18354 const nextTick = (typeof(setImmediate) !== 'undefined') ? setImmediate : setTimeout;
18355
18356 // This is really all I changed; making scryptsy a state machine so we occasionally
18357 // stop and give other evnts on the evnt loop a chance to run. ~RicMoo
18358 const incrementalSMix = function() {
18359 if (stop) {
18360 return callback(new Error('cancelled'), currentOp / totalOps);
18361 }
18362
18363 let steps;
18364
18365 switch (state) {
18366 case 0:
18367 // for (var i = 0; i < p; i++)...
18368 Bi = i0 * 32 * r;
18369
18370 arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1
18371
18372 state = 1; // Move to ROMix 2
18373 i1 = 0;
18374
18375 // Fall through
18376
18377 case 1:
18378
18379 // Run up to 1000 steps of the first inner smix loop
18380 steps = N - i1;
18381 if (steps > limit) { steps = limit; }
18382 for (let i = 0; i < steps; i++) { // ROMix - 2
18383 arraycopy(XY, 0, V, (i1 + i) * Yi, Yi); // ROMix - 3
18384 blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4
18385 }
18386
18387 // for (var i = 0; i < N; i++)
18388 i1 += steps;
18389 currentOp += steps;
18390
18391 if (callback) {
18392 // Call the callback with the progress (optionally stopping us)
18393 const percent10 = parseInt(1000 * currentOp / totalOps);
18394 if (percent10 !== lastPercent10) {
18395 stop = callback(null, currentOp / totalOps);
18396 if (stop) { break; }
18397 lastPercent10 = percent10;
18398 }
18399 }
18400
18401 if (i1 < N) { break; }
18402
18403 i1 = 0; // Move to ROMix 6
18404 state = 2;
18405
18406 // Fall through
18407
18408 case 2:
18409
18410 // Run up to 1000 steps of the second inner smix loop
18411 steps = N - i1;
18412 if (steps > limit) { steps = limit; }
18413 for (let i = 0; i < steps; i++) { // ROMix - 6
18414 const offset = (2 * r - 1) * 16; // ROMix - 7
18415 const j = XY[offset] & (N - 1);
18416 blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner)
18417 blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer)
18418 }
18419
18420 // for (var i = 0; i < N; i++)...
18421 i1 += steps;
18422 currentOp += steps;
18423
18424 // Call the callback with the progress (optionally stopping us)
18425 if (callback) {
18426 const percent10 = parseInt(1000 * currentOp / totalOps);
18427 if (percent10 !== lastPercent10) {
18428 stop = callback(null, currentOp / totalOps);
18429 if (stop) { break; }
18430 lastPercent10 = percent10;
18431 }
18432 }
18433
18434 if (i1 < N) { break; }
18435
18436 arraycopy(XY, 0, B, Bi, Yi); // ROMix - 10
18437
18438 // for (var i = 0; i < p; i++)...
18439 i0++;
18440 if (i0 < p) {
18441 state = 0;
18442 break;
18443 }
18444
18445 b = [];
18446 for (let i = 0; i < B.length; i++) {
18447 b.push((B[i] >> 0) & 0xff);
18448 b.push((B[i] >> 8) & 0xff);
18449 b.push((B[i] >> 16) & 0xff);
18450 b.push((B[i] >> 24) & 0xff);
18451 }
18452
18453 const derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);
18454
18455 // Send the result to the callback
18456 if (callback) { callback(null, 1.0, derivedKey); }
18457
18458 // Done; don't break (which would reschedule)
18459 return derivedKey;
18460 }
18461
18462 // Schedule the next steps
18463 if (callback) { nextTick(incrementalSMix); }
18464 };
18465
18466 // Run the smix state machine until completion
18467 if (!callback) {
18468 while (true) {
18469 const derivedKey = incrementalSMix();
18470 if (derivedKey != undefined) { return derivedKey; }
18471 }
18472 }
18473
18474 // Bootstrap the async incremental smix
18475 incrementalSMix();
18476 }
18477
18478 const lib = {
18479 scrypt: function(password, salt, N, r, p, dkLen, progressCallback) {
18480 return new Promise(function(resolve, reject) {
18481 let lastProgress = 0;
18482 if (progressCallback) { progressCallback(0); }
18483 _scrypt(password, salt, N, r, p, dkLen, function(error, progress, key) {
18484 if (error) {
18485 reject(error);
18486 } else if (key) {
18487 if (progressCallback && lastProgress !== 1) {
18488 progressCallback(1);
18489 }
18490 resolve(new Uint8Array(key));
18491 } else if (progressCallback && progress !== lastProgress) {
18492 lastProgress = progress;
18493 return progressCallback(progress);
18494 }
18495 });
18496 });
18497 },
18498 syncScrypt: function(password, salt, N, r, p, dkLen) {
18499 return new Uint8Array(_scrypt(password, salt, N, r, p, dkLen));
18500 }
18501 };
18502
18503 // node.js
18504 if ('object' !== 'undefined') {
18505 module.exports = lib;
18506
18507 // RequireJS/AMD
18508 // http://www.requirejs.org/docs/api.html
18509 // https://github.com/amdjs/amdjs-api/wiki/AMD
18510 } else if (typeof(undefined) === 'function' && undefined.amd) {
18511 undefined(lib);
18512
18513 // Web Browsers
18514 } else if (root) {
18515
18516 // If there was an existing library "scrypt", make sure it is still available
18517 if (root.scrypt) {
18518 root._scrypt = root.scrypt;
18519 }
18520
18521 root.scrypt = lib;
18522 }
18523
18524})(commonjsGlobal);
18525});
18526var scrypt_1 = scrypt.scrypt;
18527var scrypt_2 = scrypt.syncScrypt;
18528
18529"use strict";
18530var __awaiter$3 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
18531 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18532 return new (P || (P = Promise))(function (resolve, reject) {
18533 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18534 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18535 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18536 step((generator = generator.apply(thisArg, _arguments || [])).next());
18537 });
18538};
18539const logger$m = new Logger(version$i);
18540// Exported Types
18541function hasMnemonic(value) {
18542 return (value != null && value.mnemonic && value.mnemonic.phrase);
18543}
18544class KeystoreAccount extends Description {
18545 isKeystoreAccount(value) {
18546 return !!(value && value._isKeystoreAccount);
18547 }
18548}
18549function _decrypt(data, key, ciphertext) {
18550 const cipher = searchPath(data, "crypto/cipher");
18551 if (cipher === "aes-128-ctr") {
18552 const iv = looseArrayify(searchPath(data, "crypto/cipherparams/iv"));
18553 const counter = new aesJs.Counter(iv);
18554 const aesCtr = new aesJs.ModeOfOperation.ctr(key, counter);
18555 return arrayify(aesCtr.decrypt(ciphertext));
18556 }
18557 return null;
18558}
18559function _getAccount(data, key) {
18560 const ciphertext = looseArrayify(searchPath(data, "crypto/ciphertext"));
18561 const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2);
18562 if (computedMAC !== searchPath(data, "crypto/mac").toLowerCase()) {
18563 throw new Error("invalid password");
18564 }
18565 const privateKey = _decrypt(data, key.slice(0, 16), ciphertext);
18566 if (!privateKey) {
18567 logger$m.throwError("unsupported cipher", Logger.errors.UNSUPPORTED_OPERATION, {
18568 operation: "decrypt"
18569 });
18570 }
18571 const mnemonicKey = key.slice(32, 64);
18572 const address = computeAddress(privateKey);
18573 if (data.address) {
18574 let check = data.address.toLowerCase();
18575 if (check.substring(0, 2) !== "0x") {
18576 check = "0x" + check;
18577 }
18578 if (getAddress(check) !== address) {
18579 throw new Error("address mismatch");
18580 }
18581 }
18582 const account = {
18583 _isKeystoreAccount: true,
18584 address: address,
18585 privateKey: hexlify(privateKey)
18586 };
18587 // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase
18588 if (searchPath(data, "x-ethers/version") === "0.1") {
18589 const mnemonicCiphertext = looseArrayify(searchPath(data, "x-ethers/mnemonicCiphertext"));
18590 const mnemonicIv = looseArrayify(searchPath(data, "x-ethers/mnemonicCounter"));
18591 const mnemonicCounter = new aesJs.Counter(mnemonicIv);
18592 const mnemonicAesCtr = new aesJs.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
18593 const path = searchPath(data, "x-ethers/path") || defaultPath;
18594 const locale = searchPath(data, "x-ethers/locale") || "en";
18595 const entropy = arrayify(mnemonicAesCtr.decrypt(mnemonicCiphertext));
18596 try {
18597 const mnemonic = entropyToMnemonic(entropy, locale);
18598 const node = HDNode.fromMnemonic(mnemonic, null, locale).derivePath(path);
18599 if (node.privateKey != account.privateKey) {
18600 throw new Error("mnemonic mismatch");
18601 }
18602 account.mnemonic = node.mnemonic;
18603 }
18604 catch (error) {
18605 // If we don't have the locale wordlist installed to
18606 // read this mnemonic, just bail and don't set the
18607 // mnemonic
18608 if (error.code !== Logger.errors.INVALID_ARGUMENT || error.argument !== "wordlist") {
18609 throw error;
18610 }
18611 }
18612 }
18613 return new KeystoreAccount(account);
18614}
18615function pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc) {
18616 return arrayify(pbkdf2(passwordBytes, salt, count, dkLen, prfFunc));
18617}
18618function pbkdf2$1(passwordBytes, salt, count, dkLen, prfFunc) {
18619 return Promise.resolve(pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc));
18620}
18621function _computeKdfKey(data, password, pbkdf2Func, scryptFunc, progressCallback) {
18622 const passwordBytes = getPassword(password);
18623 const kdf = searchPath(data, "crypto/kdf");
18624 if (kdf && typeof (kdf) === "string") {
18625 const throwError = function (name, value) {
18626 return logger$m.throwArgumentError("invalid key-derivation function parameters", name, value);
18627 };
18628 if (kdf.toLowerCase() === "scrypt") {
18629 const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt"));
18630 const N = parseInt(searchPath(data, "crypto/kdfparams/n"));
18631 const r = parseInt(searchPath(data, "crypto/kdfparams/r"));
18632 const p = parseInt(searchPath(data, "crypto/kdfparams/p"));
18633 // Check for all required parameters
18634 if (!N || !r || !p) {
18635 throwError("kdf", kdf);
18636 }
18637 // Make sure N is a power of 2
18638 if ((N & (N - 1)) !== 0) {
18639 throwError("N", N);
18640 }
18641 const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen"));
18642 if (dkLen !== 32) {
18643 throwError("dklen", dkLen);
18644 }
18645 return scryptFunc(passwordBytes, salt, N, r, p, 64, progressCallback);
18646 }
18647 else if (kdf.toLowerCase() === "pbkdf2") {
18648 const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt"));
18649 let prfFunc = null;
18650 const prf = searchPath(data, "crypto/kdfparams/prf");
18651 if (prf === "hmac-sha256") {
18652 prfFunc = "sha256";
18653 }
18654 else if (prf === "hmac-sha512") {
18655 prfFunc = "sha512";
18656 }
18657 else {
18658 throwError("prf", prf);
18659 }
18660 const count = parseInt(searchPath(data, "crypto/kdfparams/c"));
18661 const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen"));
18662 if (dkLen !== 32) {
18663 throwError("dklen", dkLen);
18664 }
18665 return pbkdf2Func(passwordBytes, salt, count, dkLen, prfFunc);
18666 }
18667 }
18668 return logger$m.throwArgumentError("unsupported key-derivation function", "kdf", kdf);
18669}
18670function decryptSync(json, password) {
18671 const data = JSON.parse(json);
18672 const key = _computeKdfKey(data, password, pbkdf2Sync, scrypt_2);
18673 return _getAccount(data, key);
18674}
18675function decrypt$1(json, password, progressCallback) {
18676 return __awaiter$3(this, void 0, void 0, function* () {
18677 const data = JSON.parse(json);
18678 const key = yield _computeKdfKey(data, password, pbkdf2$1, scrypt_1, progressCallback);
18679 return _getAccount(data, key);
18680 });
18681}
18682function encrypt(account, password, options, progressCallback) {
18683 try {
18684 // Check the address matches the private key
18685 if (getAddress(account.address) !== computeAddress(account.privateKey)) {
18686 throw new Error("address/privateKey mismatch");
18687 }
18688 // Check the mnemonic (if any) matches the private key
18689 if (hasMnemonic(account)) {
18690 const mnemonic = account.mnemonic;
18691 const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath);
18692 if (node.privateKey != account.privateKey) {
18693 throw new Error("mnemonic mismatch");
18694 }
18695 }
18696 }
18697 catch (e) {
18698 return Promise.reject(e);
18699 }
18700 // The options are optional, so adjust the call as needed
18701 if (typeof (options) === "function" && !progressCallback) {
18702 progressCallback = options;
18703 options = {};
18704 }
18705 if (!options) {
18706 options = {};
18707 }
18708 const privateKey = arrayify(account.privateKey);
18709 const passwordBytes = getPassword(password);
18710 let entropy = null;
18711 let path = null;
18712 let locale = null;
18713 if (hasMnemonic(account)) {
18714 const srcMnemonic = account.mnemonic;
18715 entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en"));
18716 path = srcMnemonic.path || defaultPath;
18717 locale = srcMnemonic.locale || "en";
18718 }
18719 let client = options.client;
18720 if (!client) {
18721 client = "ethers.js";
18722 }
18723 // Check/generate the salt
18724 let salt = null;
18725 if (options.salt) {
18726 salt = arrayify(options.salt);
18727 }
18728 else {
18729 salt = randomBytes(32);
18730 ;
18731 }
18732 // Override initialization vector
18733 let iv = null;
18734 if (options.iv) {
18735 iv = arrayify(options.iv);
18736 if (iv.length !== 16) {
18737 throw new Error("invalid iv");
18738 }
18739 }
18740 else {
18741 iv = randomBytes(16);
18742 }
18743 // Override the uuid
18744 let uuidRandom = null;
18745 if (options.uuid) {
18746 uuidRandom = arrayify(options.uuid);
18747 if (uuidRandom.length !== 16) {
18748 throw new Error("invalid uuid");
18749 }
18750 }
18751 else {
18752 uuidRandom = randomBytes(16);
18753 }
18754 // Override the scrypt password-based key derivation function parameters
18755 let N = (1 << 17), r = 8, p = 1;
18756 if (options.scrypt) {
18757 if (options.scrypt.N) {
18758 N = options.scrypt.N;
18759 }
18760 if (options.scrypt.r) {
18761 r = options.scrypt.r;
18762 }
18763 if (options.scrypt.p) {
18764 p = options.scrypt.p;
18765 }
18766 }
18767 // We take 64 bytes:
18768 // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix)
18769 // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet)
18770 return scrypt_1(passwordBytes, salt, N, r, p, 64, progressCallback).then((key) => {
18771 key = arrayify(key);
18772 // This will be used to encrypt the wallet (as per Web3 secret storage)
18773 const derivedKey = key.slice(0, 16);
18774 const macPrefix = key.slice(16, 32);
18775 // This will be used to encrypt the mnemonic phrase (if any)
18776 const mnemonicKey = key.slice(32, 64);
18777 // Encrypt the private key
18778 const counter = new aesJs.Counter(iv);
18779 const aesCtr = new aesJs.ModeOfOperation.ctr(derivedKey, counter);
18780 const ciphertext = arrayify(aesCtr.encrypt(privateKey));
18781 // Compute the message authentication code, used to check the password
18782 const mac = keccak256(concat([macPrefix, ciphertext]));
18783 // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
18784 const data = {
18785 address: account.address.substring(2).toLowerCase(),
18786 id: uuidV4(uuidRandom),
18787 version: 3,
18788 Crypto: {
18789 cipher: "aes-128-ctr",
18790 cipherparams: {
18791 iv: hexlify(iv).substring(2),
18792 },
18793 ciphertext: hexlify(ciphertext).substring(2),
18794 kdf: "scrypt",
18795 kdfparams: {
18796 salt: hexlify(salt).substring(2),
18797 n: N,
18798 dklen: 32,
18799 p: p,
18800 r: r
18801 },
18802 mac: mac.substring(2)
18803 }
18804 };
18805 // If we have a mnemonic, encrypt it into the JSON wallet
18806 if (entropy) {
18807 const mnemonicIv = randomBytes(16);
18808 const mnemonicCounter = new aesJs.Counter(mnemonicIv);
18809 const mnemonicAesCtr = new aesJs.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
18810 const mnemonicCiphertext = arrayify(mnemonicAesCtr.encrypt(entropy));
18811 const now = new Date();
18812 const timestamp = (now.getUTCFullYear() + "-" +
18813 zpad(now.getUTCMonth() + 1, 2) + "-" +
18814 zpad(now.getUTCDate(), 2) + "T" +
18815 zpad(now.getUTCHours(), 2) + "-" +
18816 zpad(now.getUTCMinutes(), 2) + "-" +
18817 zpad(now.getUTCSeconds(), 2) + ".0Z");
18818 data["x-ethers"] = {
18819 client: client,
18820 gethFilename: ("UTC--" + timestamp + "--" + data.address),
18821 mnemonicCounter: hexlify(mnemonicIv).substring(2),
18822 mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2),
18823 path: path,
18824 locale: locale,
18825 version: "0.1"
18826 };
18827 }
18828 return JSON.stringify(data);
18829 });
18830}
18831
18832"use strict";
18833function decryptJsonWallet(json, password, progressCallback) {
18834 if (isCrowdsaleWallet(json)) {
18835 if (progressCallback) {
18836 progressCallback(0);
18837 }
18838 const account = decrypt(json, password);
18839 if (progressCallback) {
18840 progressCallback(1);
18841 }
18842 return Promise.resolve(account);
18843 }
18844 if (isKeystoreWallet(json)) {
18845 return decrypt$1(json, password, progressCallback);
18846 }
18847 return Promise.reject(new Error("invalid JSON wallet"));
18848}
18849function decryptJsonWalletSync(json, password) {
18850 if (isCrowdsaleWallet(json)) {
18851 return decrypt(json, password);
18852 }
18853 if (isKeystoreWallet(json)) {
18854 return decryptSync(json, password);
18855 }
18856 throw new Error("invalid JSON wallet");
18857}
18858
18859const version$j = "wallet/5.0.2";
18860
18861"use strict";
18862const logger$n = new Logger(version$j);
18863function isAccount(value) {
18864 return (value != null && isHexString(value.privateKey, 32) && value.address != null);
18865}
18866function hasMnemonic$1(value) {
18867 const mnemonic = value.mnemonic;
18868 return (mnemonic && mnemonic.phrase);
18869}
18870class Wallet extends Signer {
18871 constructor(privateKey, provider) {
18872 logger$n.checkNew(new.target, Wallet);
18873 super();
18874 if (isAccount(privateKey)) {
18875 const signingKey = new SigningKey(privateKey.privateKey);
18876 defineReadOnly(this, "_signingKey", () => signingKey);
18877 defineReadOnly(this, "address", computeAddress(this.publicKey));
18878 if (this.address !== getAddress(privateKey.address)) {
18879 logger$n.throwArgumentError("privateKey/address mismatch", "privateKey", "[REDACTED]");
18880 }
18881 if (hasMnemonic$1(privateKey)) {
18882 const srcMnemonic = privateKey.mnemonic;
18883 defineReadOnly(this, "_mnemonic", () => ({
18884 phrase: srcMnemonic.phrase,
18885 path: srcMnemonic.path || defaultPath,
18886 locale: srcMnemonic.locale || "en"
18887 }));
18888 const mnemonic = this.mnemonic;
18889 const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path);
18890 if (computeAddress(node.privateKey) !== this.address) {
18891 logger$n.throwArgumentError("mnemonic/address mismatch", "privateKey", "[REDACTED]");
18892 }
18893 }
18894 else {
18895 defineReadOnly(this, "_mnemonic", () => null);
18896 }
18897 }
18898 else {
18899 if (SigningKey.isSigningKey(privateKey)) {
18900 /* istanbul ignore if */
18901 if (privateKey.curve !== "secp256k1") {
18902 logger$n.throwArgumentError("unsupported curve; must be secp256k1", "privateKey", "[REDACTED]");
18903 }
18904 defineReadOnly(this, "_signingKey", () => privateKey);
18905 }
18906 else {
18907 const signingKey = new SigningKey(privateKey);
18908 defineReadOnly(this, "_signingKey", () => signingKey);
18909 }
18910 defineReadOnly(this, "_mnemonic", () => null);
18911 defineReadOnly(this, "address", computeAddress(this.publicKey));
18912 }
18913 /* istanbul ignore if */
18914 if (provider && !Provider.isProvider(provider)) {
18915 logger$n.throwArgumentError("invalid provider", "provider", provider);
18916 }
18917 defineReadOnly(this, "provider", provider || null);
18918 }
18919 get mnemonic() { return this._mnemonic(); }
18920 get privateKey() { return this._signingKey().privateKey; }
18921 get publicKey() { return this._signingKey().publicKey; }
18922 getAddress() {
18923 return Promise.resolve(this.address);
18924 }
18925 connect(provider) {
18926 return new Wallet(this, provider);
18927 }
18928 signTransaction(transaction) {
18929 return resolveProperties(transaction).then((tx) => {
18930 if (tx.from != null) {
18931 if (getAddress(tx.from) !== this.address) {
18932 logger$n.throwArgumentError("transaction from address mismatch", "transaction.from", transaction.from);
18933 }
18934 delete tx.from;
18935 }
18936 const signature = this._signingKey().signDigest(keccak256(serialize(tx)));
18937 return serialize(tx, signature);
18938 });
18939 }
18940 signMessage(message) {
18941 return Promise.resolve(joinSignature(this._signingKey().signDigest(hashMessage(message))));
18942 }
18943 encrypt(password, options, progressCallback) {
18944 if (typeof (options) === "function" && !progressCallback) {
18945 progressCallback = options;
18946 options = {};
18947 }
18948 if (progressCallback && typeof (progressCallback) !== "function") {
18949 throw new Error("invalid callback");
18950 }
18951 if (!options) {
18952 options = {};
18953 }
18954 return encrypt(this, password, options, progressCallback);
18955 }
18956 /**
18957 * Static methods to create Wallet instances.
18958 */
18959 static createRandom(options) {
18960 let entropy = randomBytes(16);
18961 if (!options) {
18962 options = {};
18963 }
18964 if (options.extraEntropy) {
18965 entropy = arrayify(hexDataSlice(keccak256(concat([entropy, options.extraEntropy])), 0, 16));
18966 }
18967 const mnemonic = entropyToMnemonic(entropy, options.locale);
18968 return Wallet.fromMnemonic(mnemonic, options.path, options.locale);
18969 }
18970 static fromEncryptedJson(json, password, progressCallback) {
18971 return decryptJsonWallet(json, password, progressCallback).then((account) => {
18972 return new Wallet(account);
18973 });
18974 }
18975 static fromEncryptedJsonSync(json, password) {
18976 return new Wallet(decryptJsonWalletSync(json, password));
18977 }
18978 static fromMnemonic(mnemonic, path, wordlist) {
18979 if (!path) {
18980 path = defaultPath;
18981 }
18982 return new Wallet(HDNode.fromMnemonic(mnemonic, null, wordlist).derivePath(path));
18983 }
18984}
18985function verifyMessage(message, signature) {
18986 return recoverAddress(hashMessage(message), signature);
18987}
18988
18989const version$k = "networks/5.0.2";
18990
18991"use strict";
18992const logger$o = new Logger(version$k);
18993;
18994function isRenetworkable(value) {
18995 return (value && typeof (value.renetwork) === "function");
18996}
18997function ethDefaultProvider(network) {
18998 const func = function (providers, options) {
18999 if (options == null) {
19000 options = {};
19001 }
19002 const providerList = [];
19003 if (providers.InfuraProvider) {
19004 try {
19005 providerList.push(new providers.InfuraProvider(network, options.infura));
19006 }
19007 catch (error) { }
19008 }
19009 if (providers.EtherscanProvider) {
19010 try {
19011 providerList.push(new providers.EtherscanProvider(network, options.etherscan));
19012 }
19013 catch (error) { }
19014 }
19015 if (providers.AlchemyProvider) {
19016 try {
19017 providerList.push(new providers.AlchemyProvider(network, options.alchemy));
19018 }
19019 catch (error) { }
19020 }
19021 if (providers.CloudflareProvider) {
19022 try {
19023 providerList.push(new providers.CloudflareProvider(network));
19024 }
19025 catch (error) { }
19026 }
19027 if (providerList.length === 0) {
19028 return null;
19029 }
19030 if (providers.FallbackProvider) {
19031 let quorum = 1;
19032 if (options.quorum != null) {
19033 quorum = options.quorum;
19034 }
19035 else if (network === "homestead") {
19036 quorum = 2;
19037 }
19038 return new providers.FallbackProvider(providerList, quorum);
19039 }
19040 return providerList[0];
19041 };
19042 func.renetwork = function (network) {
19043 return ethDefaultProvider(network);
19044 };
19045 return func;
19046}
19047function etcDefaultProvider(url, network) {
19048 const func = function (providers, options) {
19049 if (providers.JsonRpcProvider) {
19050 return new providers.JsonRpcProvider(url, network);
19051 }
19052 return null;
19053 };
19054 func.renetwork = function (network) {
19055 return etcDefaultProvider(url, network);
19056 };
19057 return func;
19058}
19059const homestead = {
19060 chainId: 1,
19061 ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
19062 name: "homestead",
19063 _defaultProvider: ethDefaultProvider("homestead")
19064};
19065const ropsten = {
19066 chainId: 3,
19067 ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
19068 name: "ropsten",
19069 _defaultProvider: ethDefaultProvider("ropsten")
19070};
19071const classicMordor = {
19072 chainId: 63,
19073 name: "classicMordor",
19074 _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/mordor", "classicMordor")
19075};
19076const networks = {
19077 unspecified: {
19078 chainId: 0,
19079 name: "unspecified"
19080 },
19081 homestead: homestead,
19082 mainnet: homestead,
19083 morden: {
19084 chainId: 2,
19085 name: "morden"
19086 },
19087 ropsten: ropsten,
19088 testnet: ropsten,
19089 rinkeby: {
19090 chainId: 4,
19091 ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
19092 name: "rinkeby",
19093 _defaultProvider: ethDefaultProvider("rinkeby")
19094 },
19095 kovan: {
19096 chainId: 42,
19097 name: "kovan",
19098 _defaultProvider: ethDefaultProvider("kovan")
19099 },
19100 goerli: {
19101 chainId: 5,
19102 ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
19103 name: "goerli",
19104 _defaultProvider: ethDefaultProvider("goerli")
19105 },
19106 // ETC (See: #351)
19107 classic: {
19108 chainId: 61,
19109 name: "classic",
19110 _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/etc", "classic")
19111 },
19112 classicMorden: {
19113 chainId: 62,
19114 name: "classicMorden",
19115 },
19116 classicMordor: classicMordor,
19117 classicTestnet: classicMordor,
19118 classicKotti: {
19119 chainId: 6,
19120 name: "classicKotti",
19121 _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/kotti", "classicKotti")
19122 },
19123};
19124/**
19125 * getNetwork
19126 *
19127 * Converts a named common networks or chain ID (network ID) to a Network
19128 * and verifies a network is a valid Network..
19129 */
19130function getNetwork(network) {
19131 // No network (null)
19132 if (network == null) {
19133 return null;
19134 }
19135 if (typeof (network) === "number") {
19136 for (const name in networks) {
19137 const standard = networks[name];
19138 if (standard.chainId === network) {
19139 return {
19140 name: standard.name,
19141 chainId: standard.chainId,
19142 ensAddress: (standard.ensAddress || null),
19143 _defaultProvider: (standard._defaultProvider || null)
19144 };
19145 }
19146 }
19147 return {
19148 chainId: network,
19149 name: "unknown"
19150 };
19151 }
19152 if (typeof (network) === "string") {
19153 const standard = networks[network];
19154 if (standard == null) {
19155 return null;
19156 }
19157 return {
19158 name: standard.name,
19159 chainId: standard.chainId,
19160 ensAddress: standard.ensAddress,
19161 _defaultProvider: (standard._defaultProvider || null)
19162 };
19163 }
19164 const standard = networks[network.name];
19165 // Not a standard network; check that it is a valid network in general
19166 if (!standard) {
19167 if (typeof (network.chainId) !== "number") {
19168 logger$o.throwArgumentError("invalid network chainId", "network", network);
19169 }
19170 return network;
19171 }
19172 // Make sure the chainId matches the expected network chainId (or is 0; disable EIP-155)
19173 if (network.chainId !== 0 && network.chainId !== standard.chainId) {
19174 logger$o.throwArgumentError("network chainId mismatch", "network", network);
19175 }
19176 // @TODO: In the next major version add an attach function to a defaultProvider
19177 // class and move the _defaultProvider internal to this file (extend Network)
19178 let defaultProvider = network._defaultProvider || null;
19179 if (defaultProvider == null && standard._defaultProvider) {
19180 if (isRenetworkable(standard._defaultProvider)) {
19181 defaultProvider = standard._defaultProvider.renetwork(network);
19182 }
19183 else {
19184 defaultProvider = standard._defaultProvider;
19185 }
19186 }
19187 // Standard Network (allow overriding the ENS address)
19188 return {
19189 name: network.name,
19190 chainId: standard.chainId,
19191 ensAddress: (network.ensAddress || standard.ensAddress || null),
19192 _defaultProvider: defaultProvider
19193 };
19194}
19195
19196"use strict";
19197function decode$1(textData) {
19198 textData = atob(textData);
19199 const data = [];
19200 for (let i = 0; i < textData.length; i++) {
19201 data.push(textData.charCodeAt(i));
19202 }
19203 return arrayify(data);
19204}
19205function encode$1(data) {
19206 data = arrayify(data);
19207 let textData = "";
19208 for (let i = 0; i < data.length; i++) {
19209 textData += String.fromCharCode(data[i]);
19210 }
19211 return btoa(textData);
19212}
19213
19214var browser$2 = /*#__PURE__*/Object.freeze({
19215 decode: decode$1,
19216 encode: encode$1
19217});
19218
19219const version$l = "web/5.0.3";
19220
19221"use strict";
19222var __awaiter$4 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
19223 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19224 return new (P || (P = Promise))(function (resolve, reject) {
19225 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
19226 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19227 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19228 step((generator = generator.apply(thisArg, _arguments || [])).next());
19229 });
19230};
19231function getUrl(href, options) {
19232 return __awaiter$4(this, void 0, void 0, function* () {
19233 if (options == null) {
19234 options = {};
19235 }
19236 const request = {
19237 method: (options.method || "GET"),
19238 headers: (options.headers || {}),
19239 body: (options.body || undefined),
19240 mode: "cors",
19241 cache: "no-cache",
19242 credentials: "same-origin",
19243 redirect: "follow",
19244 referrer: "client",
19245 };
19246 const response = yield fetch(href, request);
19247 const body = yield response.arrayBuffer();
19248 const headers = {};
19249 if (response.headers.forEach) {
19250 response.headers.forEach((value, key) => {
19251 headers[key.toLowerCase()] = value;
19252 });
19253 }
19254 else {
19255 ((response.headers).keys)().forEach((key) => {
19256 headers[key.toLowerCase()] = response.headers.get(key);
19257 });
19258 }
19259 return {
19260 headers: headers,
19261 statusCode: response.status,
19262 statusMessage: response.statusText,
19263 body: arrayify(new Uint8Array(body)),
19264 };
19265 });
19266}
19267
19268"use strict";
19269var __awaiter$5 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
19270 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19271 return new (P || (P = Promise))(function (resolve, reject) {
19272 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
19273 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19274 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19275 step((generator = generator.apply(thisArg, _arguments || [])).next());
19276 });
19277};
19278const logger$p = new Logger(version$l);
19279function staller(duration) {
19280 return new Promise((resolve) => {
19281 setTimeout(resolve, duration);
19282 });
19283}
19284// This API is still a work in progress; the future changes will likely be:
19285// - ConnectionInfo => FetchDataRequest<T = any>
19286// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }
19287// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)
19288// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T
19289// For this reason, it should be considered internal until the API is finalized
19290function _fetchData(connection, body, processFunc) {
19291 // How many times to retry in the event of a throttle
19292 const attemptLimit = (typeof (connection) === "object" && connection.throttleLimit != null) ? connection.throttleLimit : 12;
19293 logger$p.assertArgument((attemptLimit > 0 && (attemptLimit % 1) === 0), "invalid connection throttle limit", "connection.throttleLimit", attemptLimit);
19294 const throttleCallback = ((typeof (connection) === "object") ? connection.throttleCallback : null);
19295 const throttleSlotInterval = ((typeof (connection) === "object" && typeof (connection.throttleSlotInterval) === "number") ? connection.throttleSlotInterval : 100);
19296 logger$p.assertArgument((throttleSlotInterval > 0 && (throttleSlotInterval % 1) === 0), "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval);
19297 const headers = {};
19298 let url = null;
19299 // @TODO: Allow ConnectionInfo to override some of these values
19300 const options = {
19301 method: "GET",
19302 };
19303 let allow304 = false;
19304 let timeout = 2 * 60 * 1000;
19305 if (typeof (connection) === "string") {
19306 url = connection;
19307 }
19308 else if (typeof (connection) === "object") {
19309 if (connection == null || connection.url == null) {
19310 logger$p.throwArgumentError("missing URL", "connection.url", connection);
19311 }
19312 url = connection.url;
19313 if (typeof (connection.timeout) === "number" && connection.timeout > 0) {
19314 timeout = connection.timeout;
19315 }
19316 if (connection.headers) {
19317 for (const key in connection.headers) {
19318 headers[key.toLowerCase()] = { key: key, value: String(connection.headers[key]) };
19319 if (["if-none-match", "if-modified-since"].indexOf(key.toLowerCase()) >= 0) {
19320 allow304 = true;
19321 }
19322 }
19323 }
19324 if (connection.user != null && connection.password != null) {
19325 if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) {
19326 logger$p.throwError("basic authentication requires a secure https url", Logger.errors.INVALID_ARGUMENT, { argument: "url", url: url, user: connection.user, password: "[REDACTED]" });
19327 }
19328 const authorization = connection.user + ":" + connection.password;
19329 headers["authorization"] = {
19330 key: "Authorization",
19331 value: "Basic " + encode$1(toUtf8Bytes(authorization))
19332 };
19333 }
19334 }
19335 if (body) {
19336 options.method = "POST";
19337 options.body = body;
19338 if (headers["content-type"] == null) {
19339 headers["content-type"] = { key: "Content-Type", value: "application/octet-stream" };
19340 }
19341 }
19342 const flatHeaders = {};
19343 Object.keys(headers).forEach((key) => {
19344 const header = headers[key];
19345 flatHeaders[header.key] = header.value;
19346 });
19347 options.headers = flatHeaders;
19348 const runningTimeout = (function () {
19349 let timer = null;
19350 const promise = new Promise(function (resolve, reject) {
19351 if (timeout) {
19352 timer = setTimeout(() => {
19353 if (timer == null) {
19354 return;
19355 }
19356 timer = null;
19357 reject(logger$p.makeError("timeout", Logger.errors.TIMEOUT, {
19358 requestBody: (options.body || null),
19359 requestMethod: options.method,
19360 timeout: timeout,
19361 url: url
19362 }));
19363 }, timeout);
19364 }
19365 });
19366 const cancel = function () {
19367 if (timer == null) {
19368 return;
19369 }
19370 clearTimeout(timer);
19371 timer = null;
19372 };
19373 return { promise, cancel };
19374 })();
19375 const runningFetch = (function () {
19376 return __awaiter$5(this, void 0, void 0, function* () {
19377 for (let attempt = 0; attempt < attemptLimit; attempt++) {
19378 let response = null;
19379 try {
19380 response = yield getUrl(url, options);
19381 // Exponential back-off throttling
19382 if (response.statusCode === 429 && attempt < attemptLimit) {
19383 let tryAgain = true;
19384 if (throttleCallback) {
19385 tryAgain = yield throttleCallback(attempt, url);
19386 }
19387 if (tryAgain) {
19388 let stall = 0;
19389 const retryAfter = response.headers["retry-after"];
19390 if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
19391 stall = parseInt(retryAfter) * 1000;
19392 }
19393 else {
19394 stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
19395 }
19396 //console.log("Stalling 429");
19397 yield staller(stall);
19398 continue;
19399 }
19400 }
19401 }
19402 catch (error) {
19403 response = error.response;
19404 if (response == null) {
19405 runningTimeout.cancel();
19406 logger$p.throwError("missing response", Logger.errors.SERVER_ERROR, {
19407 requestBody: (options.body || null),
19408 requestMethod: options.method,
19409 serverError: error,
19410 url: url
19411 });
19412 }
19413 }
19414 let body = response.body;
19415 if (allow304 && response.statusCode === 304) {
19416 body = null;
19417 }
19418 else if (response.statusCode < 200 || response.statusCode >= 300) {
19419 runningTimeout.cancel();
19420 logger$p.throwError("bad response", Logger.errors.SERVER_ERROR, {
19421 status: response.statusCode,
19422 headers: response.headers,
19423 body: body,
19424 requestBody: (options.body || null),
19425 requestMethod: options.method,
19426 url: url
19427 });
19428 }
19429 if (processFunc) {
19430 try {
19431 const result = yield processFunc(body, response);
19432 runningTimeout.cancel();
19433 return result;
19434 }
19435 catch (error) {
19436 // Allow the processFunc to trigger a throttle
19437 if (error.throttleRetry && attempt < attemptLimit) {
19438 let tryAgain = true;
19439 if (throttleCallback) {
19440 tryAgain = yield throttleCallback(attempt, url);
19441 }
19442 if (tryAgain) {
19443 const timeout = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
19444 //console.log("Stalling callback");
19445 yield staller(timeout);
19446 continue;
19447 }
19448 }
19449 runningTimeout.cancel();
19450 logger$p.throwError("processing response error", Logger.errors.SERVER_ERROR, {
19451 body: body,
19452 error: error,
19453 requestBody: (options.body || null),
19454 requestMethod: options.method,
19455 url: url
19456 });
19457 }
19458 }
19459 runningTimeout.cancel();
19460 // If we had a processFunc, it eitehr returned a T or threw above.
19461 // The "body" is now a Uint8Array.
19462 return body;
19463 }
19464 return logger$p.throwError("failed response", Logger.errors.SERVER_ERROR, {
19465 requestBody: (options.body || null),
19466 requestMethod: options.method,
19467 url: url
19468 });
19469 });
19470 })();
19471 return Promise.race([runningTimeout.promise, runningFetch]);
19472}
19473function fetchJson(connection, json, processFunc) {
19474 let processJsonFunc = (value, response) => {
19475 let result = null;
19476 if (value != null) {
19477 try {
19478 result = JSON.parse(toUtf8String(value));
19479 }
19480 catch (error) {
19481 logger$p.throwError("invalid JSON", Logger.errors.SERVER_ERROR, {
19482 body: value,
19483 error: error
19484 });
19485 }
19486 }
19487 if (processFunc) {
19488 result = processFunc(result, response);
19489 }
19490 return result;
19491 };
19492 // If we have json to send, we must
19493 // - add content-type of application/json (unless already overridden)
19494 // - convert the json to bytes
19495 let body = null;
19496 if (json != null) {
19497 body = toUtf8Bytes(json);
19498 // Create a connection with the content-type set for JSON
19499 const updated = (typeof (connection) === "string") ? ({ url: connection }) : shallowCopy(connection);
19500 if (updated.headers) {
19501 const hasContentType = (Object.keys(updated.headers).filter((k) => (k.toLowerCase() === "content-type")).length) !== 0;
19502 if (!hasContentType) {
19503 updated.headers = shallowCopy(updated.headers);
19504 updated.headers["content-type"] = "application/json";
19505 }
19506 }
19507 else {
19508 updated.headers = { "content-type": "application/json" };
19509 }
19510 connection = updated;
19511 }
19512 return _fetchData(connection, body, processJsonFunc);
19513}
19514function poll(func, options) {
19515 if (!options) {
19516 options = {};
19517 }
19518 options = shallowCopy(options);
19519 if (options.floor == null) {
19520 options.floor = 0;
19521 }
19522 if (options.ceiling == null) {
19523 options.ceiling = 10000;
19524 }
19525 if (options.interval == null) {
19526 options.interval = 250;
19527 }
19528 return new Promise(function (resolve, reject) {
19529 let timer = null;
19530 let done = false;
19531 // Returns true if cancel was successful. Unsuccessful cancel means we're already done.
19532 const cancel = () => {
19533 if (done) {
19534 return false;
19535 }
19536 done = true;
19537 if (timer) {
19538 clearTimeout(timer);
19539 }
19540 return true;
19541 };
19542 if (options.timeout) {
19543 timer = setTimeout(() => {
19544 if (cancel()) {
19545 reject(new Error("timeout"));
19546 }
19547 }, options.timeout);
19548 }
19549 const retryLimit = options.retryLimit;
19550 let attempt = 0;
19551 function check() {
19552 return func().then(function (result) {
19553 // If we have a result, or are allowed null then we're done
19554 if (result !== undefined) {
19555 if (cancel()) {
19556 resolve(result);
19557 }
19558 }
19559 else if (options.oncePoll) {
19560 options.oncePoll.once("poll", check);
19561 }
19562 else if (options.onceBlock) {
19563 options.onceBlock.once("block", check);
19564 // Otherwise, exponential back-off (up to 10s) our next request
19565 }
19566 else if (!done) {
19567 attempt++;
19568 if (attempt > retryLimit) {
19569 if (cancel()) {
19570 reject(new Error("retry limit reached"));
19571 }
19572 return;
19573 }
19574 let timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt)));
19575 if (timeout < options.floor) {
19576 timeout = options.floor;
19577 }
19578 if (timeout > options.ceiling) {
19579 timeout = options.ceiling;
19580 }
19581 setTimeout(check, timeout);
19582 }
19583 return null;
19584 }, function (error) {
19585 if (cancel()) {
19586 reject(error);
19587 }
19588 });
19589 }
19590 check();
19591 });
19592}
19593
19594const version$m = "providers/5.0.5";
19595
19596"use strict";
19597const logger$q = new Logger(version$m);
19598class Formatter {
19599 constructor() {
19600 logger$q.checkNew(new.target, Formatter);
19601 this.formats = this.getDefaultFormats();
19602 }
19603 getDefaultFormats() {
19604 const formats = ({});
19605 const address = this.address.bind(this);
19606 const bigNumber = this.bigNumber.bind(this);
19607 const blockTag = this.blockTag.bind(this);
19608 const data = this.data.bind(this);
19609 const hash = this.hash.bind(this);
19610 const hex = this.hex.bind(this);
19611 const number = this.number.bind(this);
19612 const strictData = (v) => { return this.data(v, true); };
19613 formats.transaction = {
19614 hash: hash,
19615 blockHash: Formatter.allowNull(hash, null),
19616 blockNumber: Formatter.allowNull(number, null),
19617 transactionIndex: Formatter.allowNull(number, null),
19618 confirmations: Formatter.allowNull(number, null),
19619 from: address,
19620 gasPrice: bigNumber,
19621 gasLimit: bigNumber,
19622 to: Formatter.allowNull(address, null),
19623 value: bigNumber,
19624 nonce: number,
19625 data: data,
19626 r: Formatter.allowNull(this.uint256),
19627 s: Formatter.allowNull(this.uint256),
19628 v: Formatter.allowNull(number),
19629 creates: Formatter.allowNull(address, null),
19630 raw: Formatter.allowNull(data),
19631 };
19632 formats.transactionRequest = {
19633 from: Formatter.allowNull(address),
19634 nonce: Formatter.allowNull(number),
19635 gasLimit: Formatter.allowNull(bigNumber),
19636 gasPrice: Formatter.allowNull(bigNumber),
19637 to: Formatter.allowNull(address),
19638 value: Formatter.allowNull(bigNumber),
19639 data: Formatter.allowNull(strictData),
19640 };
19641 formats.receiptLog = {
19642 transactionIndex: number,
19643 blockNumber: number,
19644 transactionHash: hash,
19645 address: address,
19646 topics: Formatter.arrayOf(hash),
19647 data: data,
19648 logIndex: number,
19649 blockHash: hash,
19650 };
19651 formats.receipt = {
19652 to: Formatter.allowNull(this.address, null),
19653 from: Formatter.allowNull(this.address, null),
19654 contractAddress: Formatter.allowNull(address, null),
19655 transactionIndex: number,
19656 root: Formatter.allowNull(hash),
19657 gasUsed: bigNumber,
19658 logsBloom: Formatter.allowNull(data),
19659 blockHash: hash,
19660 transactionHash: hash,
19661 logs: Formatter.arrayOf(this.receiptLog.bind(this)),
19662 blockNumber: number,
19663 confirmations: Formatter.allowNull(number, null),
19664 cumulativeGasUsed: bigNumber,
19665 status: Formatter.allowNull(number)
19666 };
19667 formats.block = {
19668 hash: hash,
19669 parentHash: hash,
19670 number: number,
19671 timestamp: number,
19672 nonce: Formatter.allowNull(hex),
19673 difficulty: this.difficulty.bind(this),
19674 gasLimit: bigNumber,
19675 gasUsed: bigNumber,
19676 miner: address,
19677 extraData: data,
19678 transactions: Formatter.allowNull(Formatter.arrayOf(hash)),
19679 };
19680 formats.blockWithTransactions = shallowCopy(formats.block);
19681 formats.blockWithTransactions.transactions = Formatter.allowNull(Formatter.arrayOf(this.transactionResponse.bind(this)));
19682 formats.filter = {
19683 fromBlock: Formatter.allowNull(blockTag, undefined),
19684 toBlock: Formatter.allowNull(blockTag, undefined),
19685 blockHash: Formatter.allowNull(hash, undefined),
19686 address: Formatter.allowNull(address, undefined),
19687 topics: Formatter.allowNull(this.topics.bind(this), undefined),
19688 };
19689 formats.filterLog = {
19690 blockNumber: Formatter.allowNull(number),
19691 blockHash: Formatter.allowNull(hash),
19692 transactionIndex: number,
19693 removed: Formatter.allowNull(this.boolean.bind(this)),
19694 address: address,
19695 data: Formatter.allowFalsish(data, "0x"),
19696 topics: Formatter.arrayOf(hash),
19697 transactionHash: hash,
19698 logIndex: number,
19699 };
19700 return formats;
19701 }
19702 // Requires a BigNumberish that is within the IEEE754 safe integer range; returns a number
19703 // Strict! Used on input.
19704 number(number) {
19705 return BigNumber.from(number).toNumber();
19706 }
19707 // Strict! Used on input.
19708 bigNumber(value) {
19709 return BigNumber.from(value);
19710 }
19711 // Requires a boolean, "true" or "false"; returns a boolean
19712 boolean(value) {
19713 if (typeof (value) === "boolean") {
19714 return value;
19715 }
19716 if (typeof (value) === "string") {
19717 value = value.toLowerCase();
19718 if (value === "true") {
19719 return true;
19720 }
19721 if (value === "false") {
19722 return false;
19723 }
19724 }
19725 throw new Error("invalid boolean - " + value);
19726 }
19727 hex(value, strict) {
19728 if (typeof (value) === "string") {
19729 if (!strict && value.substring(0, 2) !== "0x") {
19730 value = "0x" + value;
19731 }
19732 if (isHexString(value)) {
19733 return value.toLowerCase();
19734 }
19735 }
19736 return logger$q.throwArgumentError("invalid hash", "value", value);
19737 }
19738 data(value, strict) {
19739 const result = this.hex(value, strict);
19740 if ((result.length % 2) !== 0) {
19741 throw new Error("invalid data; odd-length - " + value);
19742 }
19743 return result;
19744 }
19745 // Requires an address
19746 // Strict! Used on input.
19747 address(value) {
19748 return getAddress(value);
19749 }
19750 callAddress(value) {
19751 if (!isHexString(value, 32)) {
19752 return null;
19753 }
19754 const address = getAddress(hexDataSlice(value, 12));
19755 return (address === AddressZero) ? null : address;
19756 }
19757 contractAddress(value) {
19758 return getContractAddress(value);
19759 }
19760 // Strict! Used on input.
19761 blockTag(blockTag) {
19762 if (blockTag == null) {
19763 return "latest";
19764 }
19765 if (blockTag === "earliest") {
19766 return "0x0";
19767 }
19768 if (blockTag === "latest" || blockTag === "pending") {
19769 return blockTag;
19770 }
19771 if (typeof (blockTag) === "number" || isHexString(blockTag)) {
19772 return hexValue(blockTag);
19773 }
19774 throw new Error("invalid blockTag");
19775 }
19776 // Requires a hash, optionally requires 0x prefix; returns prefixed lowercase hash.
19777 hash(value, strict) {
19778 const result = this.hex(value, strict);
19779 if (hexDataLength(result) !== 32) {
19780 return logger$q.throwArgumentError("invalid hash", "value", value);
19781 }
19782 return result;
19783 }
19784 // Returns the difficulty as a number, or if too large (i.e. PoA network) null
19785 difficulty(value) {
19786 if (value == null) {
19787 return null;
19788 }
19789 const v = BigNumber.from(value);
19790 try {
19791 return v.toNumber();
19792 }
19793 catch (error) { }
19794 return null;
19795 }
19796 uint256(value) {
19797 if (!isHexString(value)) {
19798 throw new Error("invalid uint256");
19799 }
19800 return hexZeroPad(value, 32);
19801 }
19802 _block(value, format) {
19803 if (value.author != null && value.miner == null) {
19804 value.miner = value.author;
19805 }
19806 return Formatter.check(format, value);
19807 }
19808 block(value) {
19809 return this._block(value, this.formats.block);
19810 }
19811 blockWithTransactions(value) {
19812 return this._block(value, this.formats.blockWithTransactions);
19813 }
19814 // Strict! Used on input.
19815 transactionRequest(value) {
19816 return Formatter.check(this.formats.transactionRequest, value);
19817 }
19818 transactionResponse(transaction) {
19819 // Rename gas to gasLimit
19820 if (transaction.gas != null && transaction.gasLimit == null) {
19821 transaction.gasLimit = transaction.gas;
19822 }
19823 // Some clients (TestRPC) do strange things like return 0x0 for the
19824 // 0 address; correct this to be a real address
19825 if (transaction.to && BigNumber.from(transaction.to).isZero()) {
19826 transaction.to = "0x0000000000000000000000000000000000000000";
19827 }
19828 // Rename input to data
19829 if (transaction.input != null && transaction.data == null) {
19830 transaction.data = transaction.input;
19831 }
19832 // If to and creates are empty, populate the creates from the transaction
19833 if (transaction.to == null && transaction.creates == null) {
19834 transaction.creates = this.contractAddress(transaction);
19835 }
19836 // @TODO: use transaction.serialize? Have to add support for including v, r, and s...
19837 /*
19838 if (!transaction.raw) {
19839
19840 // Very loose providers (e.g. TestRPC) do not provide a signature or raw
19841 if (transaction.v && transaction.r && transaction.s) {
19842 let raw = [
19843 stripZeros(hexlify(transaction.nonce)),
19844 stripZeros(hexlify(transaction.gasPrice)),
19845 stripZeros(hexlify(transaction.gasLimit)),
19846 (transaction.to || "0x"),
19847 stripZeros(hexlify(transaction.value || "0x")),
19848 hexlify(transaction.data || "0x"),
19849 stripZeros(hexlify(transaction.v || "0x")),
19850 stripZeros(hexlify(transaction.r)),
19851 stripZeros(hexlify(transaction.s)),
19852 ];
19853
19854 transaction.raw = rlpEncode(raw);
19855 }
19856 }
19857 */
19858 const result = Formatter.check(this.formats.transaction, transaction);
19859 if (transaction.chainId != null) {
19860 let chainId = transaction.chainId;
19861 if (isHexString(chainId)) {
19862 chainId = BigNumber.from(chainId).toNumber();
19863 }
19864 result.chainId = chainId;
19865 }
19866 else {
19867 let chainId = transaction.networkId;
19868 // geth-etc returns chainId
19869 if (chainId == null && result.v == null) {
19870 chainId = transaction.chainId;
19871 }
19872 if (isHexString(chainId)) {
19873 chainId = BigNumber.from(chainId).toNumber();
19874 }
19875 if (typeof (chainId) !== "number" && result.v != null) {
19876 chainId = (result.v - 35) / 2;
19877 if (chainId < 0) {
19878 chainId = 0;
19879 }
19880 chainId = parseInt(chainId);
19881 }
19882 if (typeof (chainId) !== "number") {
19883 chainId = 0;
19884 }
19885 result.chainId = chainId;
19886 }
19887 // 0x0000... should actually be null
19888 if (result.blockHash && result.blockHash.replace(/0/g, "") === "x") {
19889 result.blockHash = null;
19890 }
19891 return result;
19892 }
19893 transaction(value) {
19894 return parse(value);
19895 }
19896 receiptLog(value) {
19897 return Formatter.check(this.formats.receiptLog, value);
19898 }
19899 receipt(value) {
19900 const result = Formatter.check(this.formats.receipt, value);
19901 if (value.status != null) {
19902 result.byzantium = true;
19903 }
19904 return result;
19905 }
19906 topics(value) {
19907 if (Array.isArray(value)) {
19908 return value.map((v) => this.topics(v));
19909 }
19910 else if (value != null) {
19911 return this.hash(value, true);
19912 }
19913 return null;
19914 }
19915 filter(value) {
19916 return Formatter.check(this.formats.filter, value);
19917 }
19918 filterLog(value) {
19919 return Formatter.check(this.formats.filterLog, value);
19920 }
19921 static check(format, object) {
19922 const result = {};
19923 for (const key in format) {
19924 try {
19925 const value = format[key](object[key]);
19926 if (value !== undefined) {
19927 result[key] = value;
19928 }
19929 }
19930 catch (error) {
19931 error.checkKey = key;
19932 error.checkValue = object[key];
19933 throw error;
19934 }
19935 }
19936 return result;
19937 }
19938 // if value is null-ish, nullValue is returned
19939 static allowNull(format, nullValue) {
19940 return (function (value) {
19941 if (value == null) {
19942 return nullValue;
19943 }
19944 return format(value);
19945 });
19946 }
19947 // If value is false-ish, replaceValue is returned
19948 static allowFalsish(format, replaceValue) {
19949 return (function (value) {
19950 if (!value) {
19951 return replaceValue;
19952 }
19953 return format(value);
19954 });
19955 }
19956 // Requires an Array satisfying check
19957 static arrayOf(format) {
19958 return (function (array) {
19959 if (!Array.isArray(array)) {
19960 throw new Error("not an array");
19961 }
19962 const result = [];
19963 array.forEach(function (value) {
19964 result.push(format(value));
19965 });
19966 return result;
19967 });
19968 }
19969}
19970// Show the throttle message only once
19971let throttleMessage = false;
19972function showThrottleMessage() {
19973 if (throttleMessage) {
19974 return;
19975 }
19976 throttleMessage = true;
19977 console.log("========= NOTICE =========");
19978 console.log("Request-Rate Exceeded (this message will not be repeated)");
19979 console.log("");
19980 console.log("The default API keys for each service are provided as a highly-throttled,");
19981 console.log("community resource for low-traffic projects and early prototyping.");
19982 console.log("");
19983 console.log("While your application will continue to function, we highly recommended");
19984 console.log("signing up for your own API keys to improve performance, increase your");
19985 console.log("request rate/limit and enable other perks, such as metrics and advanced APIs.");
19986 console.log("");
19987 console.log("For more details: https:/\/docs.ethers.io/api-keys/");
19988 console.log("==========================");
19989}
19990
19991"use strict";
19992var __awaiter$6 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
19993 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19994 return new (P || (P = Promise))(function (resolve, reject) {
19995 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
19996 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19997 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19998 step((generator = generator.apply(thisArg, _arguments || [])).next());
19999 });
20000};
20001const logger$r = new Logger(version$m);
20002//////////////////////////////
20003// Event Serializeing
20004function checkTopic(topic) {
20005 if (topic == null) {
20006 return "null";
20007 }
20008 if (hexDataLength(topic) !== 32) {
20009 logger$r.throwArgumentError("invalid topic", "topic", topic);
20010 }
20011 return topic.toLowerCase();
20012}
20013function serializeTopics(topics) {
20014 // Remove trailing null AND-topics; they are redundant
20015 topics = topics.slice();
20016 while (topics.length > 0 && topics[topics.length - 1] == null) {
20017 topics.pop();
20018 }
20019 return topics.map((topic) => {
20020 if (Array.isArray(topic)) {
20021 // Only track unique OR-topics
20022 const unique = {};
20023 topic.forEach((topic) => {
20024 unique[checkTopic(topic)] = true;
20025 });
20026 // The order of OR-topics does not matter
20027 const sorted = Object.keys(unique);
20028 sorted.sort();
20029 return sorted.join("|");
20030 }
20031 else {
20032 return checkTopic(topic);
20033 }
20034 }).join("&");
20035}
20036function deserializeTopics(data) {
20037 if (data === "") {
20038 return [];
20039 }
20040 return data.split(/&/g).map((topic) => {
20041 if (topic === "") {
20042 return [];
20043 }
20044 const comps = topic.split("|").map((topic) => {
20045 return ((topic === "null") ? null : topic);
20046 });
20047 return ((comps.length === 1) ? comps[0] : comps);
20048 });
20049}
20050function getEventTag$1(eventName) {
20051 if (typeof (eventName) === "string") {
20052 eventName = eventName.toLowerCase();
20053 if (hexDataLength(eventName) === 32) {
20054 return "tx:" + eventName;
20055 }
20056 if (eventName.indexOf(":") === -1) {
20057 return eventName;
20058 }
20059 }
20060 else if (Array.isArray(eventName)) {
20061 return "filter:*:" + serializeTopics(eventName);
20062 }
20063 else if (ForkEvent.isForkEvent(eventName)) {
20064 logger$r.warn("not implemented");
20065 throw new Error("not implemented");
20066 }
20067 else if (eventName && typeof (eventName) === "object") {
20068 return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []);
20069 }
20070 throw new Error("invalid event - " + eventName);
20071}
20072//////////////////////////////
20073// Helper Object
20074function getTime() {
20075 return (new Date()).getTime();
20076}
20077function stall(duration) {
20078 return new Promise((resolve) => {
20079 setTimeout(resolve, duration);
20080 });
20081}
20082//////////////////////////////
20083// Provider Object
20084/**
20085 * EventType
20086 * - "block"
20087 * - "poll"
20088 * - "didPoll"
20089 * - "pending"
20090 * - "error"
20091 * - "network"
20092 * - filter
20093 * - topics array
20094 * - transaction hash
20095 */
20096const PollableEvents = ["block", "network", "pending", "poll"];
20097class Event {
20098 constructor(tag, listener, once) {
20099 defineReadOnly(this, "tag", tag);
20100 defineReadOnly(this, "listener", listener);
20101 defineReadOnly(this, "once", once);
20102 }
20103 get event() {
20104 switch (this.type) {
20105 case "tx":
20106 return this.hash;
20107 case "filter":
20108 return this.filter;
20109 }
20110 return this.tag;
20111 }
20112 get type() {
20113 return this.tag.split(":")[0];
20114 }
20115 get hash() {
20116 const comps = this.tag.split(":");
20117 if (comps[0] !== "tx") {
20118 return null;
20119 }
20120 return comps[1];
20121 }
20122 get filter() {
20123 const comps = this.tag.split(":");
20124 if (comps[0] !== "filter") {
20125 return null;
20126 }
20127 const address = comps[1];
20128 const topics = deserializeTopics(comps[2]);
20129 const filter = {};
20130 if (topics.length > 0) {
20131 filter.topics = topics;
20132 }
20133 if (address && address !== "*") {
20134 filter.address = address;
20135 }
20136 return filter;
20137 }
20138 pollable() {
20139 return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0);
20140 }
20141}
20142let defaultFormatter = null;
20143let nextPollId = 1;
20144class BaseProvider extends Provider {
20145 /**
20146 * ready
20147 *
20148 * A Promise<Network> that resolves only once the provider is ready.
20149 *
20150 * Sub-classes that call the super with a network without a chainId
20151 * MUST set this. Standard named networks have a known chainId.
20152 *
20153 */
20154 constructor(network) {
20155 logger$r.checkNew(new.target, Provider);
20156 super();
20157 // Events being listened to
20158 this._events = [];
20159 this._emitted = { block: -2 };
20160 this.formatter = new.target.getFormatter();
20161 // If network is any, this Provider allows the underlying
20162 // network to change dynamically, and we auto-detect the
20163 // current network
20164 defineReadOnly(this, "anyNetwork", (network === "any"));
20165 if (this.anyNetwork) {
20166 network = this.detectNetwork();
20167 }
20168 if (network instanceof Promise) {
20169 this._networkPromise = network;
20170 // Squash any "unhandled promise" errors; that do not need to be handled
20171 network.catch((error) => { });
20172 // Trigger initial network setting (async)
20173 this._ready().catch((error) => { });
20174 }
20175 else {
20176 const knownNetwork = getStatic((new.target), "getNetwork")(network);
20177 if (knownNetwork) {
20178 defineReadOnly(this, "_network", knownNetwork);
20179 this.emit("network", knownNetwork, null);
20180 }
20181 else {
20182 logger$r.throwArgumentError("invalid network", "network", network);
20183 }
20184 }
20185 this._maxInternalBlockNumber = -1024;
20186 this._lastBlockNumber = -2;
20187 this._pollingInterval = 4000;
20188 this._fastQueryDate = 0;
20189 }
20190 _ready() {
20191 return __awaiter$6(this, void 0, void 0, function* () {
20192 if (this._network == null) {
20193 let network = null;
20194 if (this._networkPromise) {
20195 try {
20196 network = yield this._networkPromise;
20197 }
20198 catch (error) { }
20199 }
20200 // Try the Provider's network detection (this MUST throw if it cannot)
20201 if (network == null) {
20202 network = yield this.detectNetwork();
20203 }
20204 // This should never happen; every Provider sub-class should have
20205 // suggested a network by here (or have thrown).
20206 if (!network) {
20207 logger$r.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, {});
20208 }
20209 // Possible this call stacked so do not call defineReadOnly again
20210 if (this._network == null) {
20211 if (this.anyNetwork) {
20212 this._network = network;
20213 }
20214 else {
20215 defineReadOnly(this, "_network", network);
20216 }
20217 this.emit("network", network, null);
20218 }
20219 }
20220 return this._network;
20221 });
20222 }
20223 // This will always return the most recently established network.
20224 // For "any", this can change (a "network" event is emitted before
20225 // any change is refelcted); otherwise this cannot change
20226 get ready() {
20227 return poll(() => {
20228 return this._ready().then((network) => {
20229 return network;
20230 }, (error) => {
20231 // If the network isn't running yet, we will wait
20232 if (error.code === Logger.errors.NETWORK_ERROR && error.event === "noNetwork") {
20233 return undefined;
20234 }
20235 throw error;
20236 });
20237 });
20238 }
20239 // @TODO: Remove this and just create a singleton formatter
20240 static getFormatter() {
20241 if (defaultFormatter == null) {
20242 defaultFormatter = new Formatter();
20243 }
20244 return defaultFormatter;
20245 }
20246 // @TODO: Remove this and just use getNetwork
20247 static getNetwork(network) {
20248 return getNetwork((network == null) ? "homestead" : network);
20249 }
20250 // Fetches the blockNumber, but will reuse any result that is less
20251 // than maxAge old or has been requested since the last request
20252 _getInternalBlockNumber(maxAge) {
20253 return __awaiter$6(this, void 0, void 0, function* () {
20254 yield this._ready();
20255 const internalBlockNumber = this._internalBlockNumber;
20256 if (maxAge > 0 && this._internalBlockNumber) {
20257 const result = yield internalBlockNumber;
20258 if ((getTime() - result.respTime) <= maxAge) {
20259 return result.blockNumber;
20260 }
20261 }
20262 const reqTime = getTime();
20263 const checkInternalBlockNumber = resolveProperties({
20264 blockNumber: this.perform("getBlockNumber", {}),
20265 networkError: this.getNetwork().then((network) => (null), (error) => (error))
20266 }).then(({ blockNumber, networkError }) => {
20267 if (networkError) {
20268 // Unremember this bad internal block number
20269 if (this._internalBlockNumber === checkInternalBlockNumber) {
20270 this._internalBlockNumber = null;
20271 }
20272 throw networkError;
20273 }
20274 const respTime = getTime();
20275 blockNumber = BigNumber.from(blockNumber).toNumber();
20276 if (blockNumber < this._maxInternalBlockNumber) {
20277 blockNumber = this._maxInternalBlockNumber;
20278 }
20279 this._maxInternalBlockNumber = blockNumber;
20280 this._setFastBlockNumber(blockNumber); // @TODO: Still need this?
20281 return { blockNumber, reqTime, respTime };
20282 });
20283 this._internalBlockNumber = checkInternalBlockNumber;
20284 return (yield checkInternalBlockNumber).blockNumber;
20285 });
20286 }
20287 poll() {
20288 return __awaiter$6(this, void 0, void 0, function* () {
20289 const pollId = nextPollId++;
20290 // Track all running promises, so we can trigger a post-poll once they are complete
20291 const runners = [];
20292 const blockNumber = yield this._getInternalBlockNumber(100 + this.pollingInterval / 2);
20293 this._setFastBlockNumber(blockNumber);
20294 // Emit a poll event after we have the latest (fast) block number
20295 this.emit("poll", pollId, blockNumber);
20296 // If the block has not changed, meh.
20297 if (blockNumber === this._lastBlockNumber) {
20298 this.emit("didPoll", pollId);
20299 return;
20300 }
20301 // First polling cycle, trigger a "block" events
20302 if (this._emitted.block === -2) {
20303 this._emitted.block = blockNumber - 1;
20304 }
20305 if (Math.abs((this._emitted.block) - blockNumber) > 1000) {
20306 logger$r.warn("network block skew detected; skipping block events");
20307 this.emit("error", logger$r.makeError("network block skew detected", Logger.errors.NETWORK_ERROR, {
20308 blockNumber: blockNumber,
20309 event: "blockSkew",
20310 previousBlockNumber: this._emitted.block
20311 }));
20312 this.emit("block", blockNumber);
20313 }
20314 else {
20315 // Notify all listener for each block that has passed
20316 for (let i = this._emitted.block + 1; i <= blockNumber; i++) {
20317 this.emit("block", i);
20318 }
20319 }
20320 // The emitted block was updated, check for obsolete events
20321 if (this._emitted.block !== blockNumber) {
20322 this._emitted.block = blockNumber;
20323 Object.keys(this._emitted).forEach((key) => {
20324 // The block event does not expire
20325 if (key === "block") {
20326 return;
20327 }
20328 // The block we were at when we emitted this event
20329 const eventBlockNumber = this._emitted[key];
20330 // We cannot garbage collect pending transactions or blocks here
20331 // They should be garbage collected by the Provider when setting
20332 // "pending" events
20333 if (eventBlockNumber === "pending") {
20334 return;
20335 }
20336 // Evict any transaction hashes or block hashes over 12 blocks
20337 // old, since they should not return null anyways
20338 if (blockNumber - eventBlockNumber > 12) {
20339 delete this._emitted[key];
20340 }
20341 });
20342 }
20343 // First polling cycle
20344 if (this._lastBlockNumber === -2) {
20345 this._lastBlockNumber = blockNumber - 1;
20346 }
20347 // Find all transaction hashes we are waiting on
20348 this._events.forEach((event) => {
20349 switch (event.type) {
20350 case "tx": {
20351 const hash = event.hash;
20352 let runner = this.getTransactionReceipt(hash).then((receipt) => {
20353 if (!receipt || receipt.blockNumber == null) {
20354 return null;
20355 }
20356 this._emitted["t:" + hash] = receipt.blockNumber;
20357 this.emit(hash, receipt);
20358 return null;
20359 }).catch((error) => { this.emit("error", error); });
20360 runners.push(runner);
20361 break;
20362 }
20363 case "filter": {
20364 const filter = event.filter;
20365 filter.fromBlock = this._lastBlockNumber + 1;
20366 filter.toBlock = blockNumber;
20367 const runner = this.getLogs(filter).then((logs) => {
20368 if (logs.length === 0) {
20369 return;
20370 }
20371 logs.forEach((log) => {
20372 this._emitted["b:" + log.blockHash] = log.blockNumber;
20373 this._emitted["t:" + log.transactionHash] = log.blockNumber;
20374 this.emit(filter, log);
20375 });
20376 }).catch((error) => { this.emit("error", error); });
20377 runners.push(runner);
20378 break;
20379 }
20380 }
20381 });
20382 this._lastBlockNumber = blockNumber;
20383 // Once all events for this loop have been processed, emit "didPoll"
20384 Promise.all(runners).then(() => {
20385 this.emit("didPoll", pollId);
20386 });
20387 return null;
20388 });
20389 }
20390 // Deprecated; do not use this
20391 resetEventsBlock(blockNumber) {
20392 this._lastBlockNumber = blockNumber - 1;
20393 if (this.polling) {
20394 this.poll();
20395 }
20396 }
20397 get network() {
20398 return this._network;
20399 }
20400 // This method should query the network if the underlying network
20401 // can change, such as when connected to a JSON-RPC backend
20402 detectNetwork() {
20403 return __awaiter$6(this, void 0, void 0, function* () {
20404 return logger$r.throwError("provider does not support network detection", Logger.errors.UNSUPPORTED_OPERATION, {
20405 operation: "provider.detectNetwork"
20406 });
20407 });
20408 }
20409 getNetwork() {
20410 return __awaiter$6(this, void 0, void 0, function* () {
20411 const network = yield this._ready();
20412 // Make sure we are still connected to the same network; this is
20413 // only an external call for backends which can have the underlying
20414 // network change spontaneously
20415 const currentNetwork = yield this.detectNetwork();
20416 if (network.chainId !== currentNetwork.chainId) {
20417 // We are allowing network changes, things can get complex fast;
20418 // make sure you know what you are doing if you use "any"
20419 if (this.anyNetwork) {
20420 this._network = currentNetwork;
20421 // Reset all internal block number guards and caches
20422 this._lastBlockNumber = -2;
20423 this._fastBlockNumber = null;
20424 this._fastBlockNumberPromise = null;
20425 this._fastQueryDate = 0;
20426 this._emitted.block = -2;
20427 this._maxInternalBlockNumber = -1024;
20428 this._internalBlockNumber = null;
20429 // The "network" event MUST happen before this method resolves
20430 // so any events have a chance to unregister, so we stall an
20431 // additional event loop before returning from /this/ call
20432 this.emit("network", currentNetwork, network);
20433 yield stall(0);
20434 return this._network;
20435 }
20436 const error = logger$r.makeError("underlying network changed", Logger.errors.NETWORK_ERROR, {
20437 event: "changed",
20438 network: network,
20439 detectedNetwork: currentNetwork
20440 });
20441 this.emit("error", error);
20442 throw error;
20443 }
20444 return network;
20445 });
20446 }
20447 get blockNumber() {
20448 this._getInternalBlockNumber(100 + this.pollingInterval / 2).then((blockNumber) => {
20449 this._setFastBlockNumber(blockNumber);
20450 });
20451 return (this._fastBlockNumber != null) ? this._fastBlockNumber : -1;
20452 }
20453 get polling() {
20454 return (this._poller != null);
20455 }
20456 set polling(value) {
20457 if (value && !this._poller) {
20458 this._poller = setInterval(this.poll.bind(this), this.pollingInterval);
20459 if (!this._bootstrapPoll) {
20460 this._bootstrapPoll = setTimeout(() => {
20461 this.poll();
20462 // We block additional polls until the polling interval
20463 // is done, to prevent overwhelming the poll function
20464 this._bootstrapPoll = setTimeout(() => {
20465 // If polling was disabled, something may require a poke
20466 // since starting the bootstrap poll and it was disabled
20467 if (!this._poller) {
20468 this.poll();
20469 }
20470 // Clear out the bootstrap so we can do another
20471 this._bootstrapPoll = null;
20472 }, this.pollingInterval);
20473 }, 0);
20474 }
20475 }
20476 else if (!value && this._poller) {
20477 clearInterval(this._poller);
20478 this._poller = null;
20479 }
20480 }
20481 get pollingInterval() {
20482 return this._pollingInterval;
20483 }
20484 set pollingInterval(value) {
20485 if (typeof (value) !== "number" || value <= 0 || parseInt(String(value)) != value) {
20486 throw new Error("invalid polling interval");
20487 }
20488 this._pollingInterval = value;
20489 if (this._poller) {
20490 clearInterval(this._poller);
20491 this._poller = setInterval(() => { this.poll(); }, this._pollingInterval);
20492 }
20493 }
20494 _getFastBlockNumber() {
20495 const now = getTime();
20496 // Stale block number, request a newer value
20497 if ((now - this._fastQueryDate) > 2 * this._pollingInterval) {
20498 this._fastQueryDate = now;
20499 this._fastBlockNumberPromise = this.getBlockNumber().then((blockNumber) => {
20500 if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
20501 this._fastBlockNumber = blockNumber;
20502 }
20503 return this._fastBlockNumber;
20504 });
20505 }
20506 return this._fastBlockNumberPromise;
20507 }
20508 _setFastBlockNumber(blockNumber) {
20509 // Older block, maybe a stale request
20510 if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) {
20511 return;
20512 }
20513 // Update the time we updated the blocknumber
20514 this._fastQueryDate = getTime();
20515 // Newer block number, use it
20516 if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
20517 this._fastBlockNumber = blockNumber;
20518 this._fastBlockNumberPromise = Promise.resolve(blockNumber);
20519 }
20520 }
20521 waitForTransaction(transactionHash, confirmations, timeout) {
20522 return __awaiter$6(this, void 0, void 0, function* () {
20523 if (confirmations == null) {
20524 confirmations = 1;
20525 }
20526 const receipt = yield this.getTransactionReceipt(transactionHash);
20527 // Receipt is already good
20528 if ((receipt ? receipt.confirmations : 0) >= confirmations) {
20529 return receipt;
20530 }
20531 // Poll until the receipt is good...
20532 return new Promise((resolve, reject) => {
20533 let timer = null;
20534 let done = false;
20535 const handler = (receipt) => {
20536 if (receipt.confirmations < confirmations) {
20537 return;
20538 }
20539 if (timer) {
20540 clearTimeout(timer);
20541 }
20542 if (done) {
20543 return;
20544 }
20545 done = true;
20546 this.removeListener(transactionHash, handler);
20547 resolve(receipt);
20548 };
20549 this.on(transactionHash, handler);
20550 if (typeof (timeout) === "number" && timeout > 0) {
20551 timer = setTimeout(() => {
20552 if (done) {
20553 return;
20554 }
20555 timer = null;
20556 done = true;
20557 this.removeListener(transactionHash, handler);
20558 reject(logger$r.makeError("timeout exceeded", Logger.errors.TIMEOUT, { timeout: timeout }));
20559 }, timeout);
20560 if (timer.unref) {
20561 timer.unref();
20562 }
20563 }
20564 });
20565 });
20566 }
20567 getBlockNumber() {
20568 return __awaiter$6(this, void 0, void 0, function* () {
20569 return this._getInternalBlockNumber(0);
20570 });
20571 }
20572 getGasPrice() {
20573 return __awaiter$6(this, void 0, void 0, function* () {
20574 yield this.getNetwork();
20575 return BigNumber.from(yield this.perform("getGasPrice", {}));
20576 });
20577 }
20578 getBalance(addressOrName, blockTag) {
20579 return __awaiter$6(this, void 0, void 0, function* () {
20580 yield this.getNetwork();
20581 const params = yield resolveProperties({
20582 address: this._getAddress(addressOrName),
20583 blockTag: this._getBlockTag(blockTag)
20584 });
20585 return BigNumber.from(yield this.perform("getBalance", params));
20586 });
20587 }
20588 getTransactionCount(addressOrName, blockTag) {
20589 return __awaiter$6(this, void 0, void 0, function* () {
20590 yield this.getNetwork();
20591 const params = yield resolveProperties({
20592 address: this._getAddress(addressOrName),
20593 blockTag: this._getBlockTag(blockTag)
20594 });
20595 return BigNumber.from(yield this.perform("getTransactionCount", params)).toNumber();
20596 });
20597 }
20598 getCode(addressOrName, blockTag) {
20599 return __awaiter$6(this, void 0, void 0, function* () {
20600 yield this.getNetwork();
20601 const params = yield resolveProperties({
20602 address: this._getAddress(addressOrName),
20603 blockTag: this._getBlockTag(blockTag)
20604 });
20605 return hexlify(yield this.perform("getCode", params));
20606 });
20607 }
20608 getStorageAt(addressOrName, position, blockTag) {
20609 return __awaiter$6(this, void 0, void 0, function* () {
20610 yield this.getNetwork();
20611 const params = yield resolveProperties({
20612 address: this._getAddress(addressOrName),
20613 blockTag: this._getBlockTag(blockTag),
20614 position: Promise.resolve(position).then((p) => hexValue(p))
20615 });
20616 return hexlify(yield this.perform("getStorageAt", params));
20617 });
20618 }
20619 // This should be called by any subclass wrapping a TransactionResponse
20620 _wrapTransaction(tx, hash) {
20621 if (hash != null && hexDataLength(hash) !== 32) {
20622 throw new Error("invalid response - sendTransaction");
20623 }
20624 const result = tx;
20625 // Check the hash we expect is the same as the hash the server reported
20626 if (hash != null && tx.hash !== hash) {
20627 logger$r.throwError("Transaction hash mismatch from Provider.sendTransaction.", Logger.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash });
20628 }
20629 // @TODO: (confirmations? number, timeout? number)
20630 result.wait = (confirmations) => __awaiter$6(this, void 0, void 0, function* () {
20631 // We know this transaction *must* exist (whether it gets mined is
20632 // another story), so setting an emitted value forces us to
20633 // wait even if the node returns null for the receipt
20634 if (confirmations !== 0) {
20635 this._emitted["t:" + tx.hash] = "pending";
20636 }
20637 const receipt = yield this.waitForTransaction(tx.hash, confirmations);
20638 if (receipt == null && confirmations === 0) {
20639 return null;
20640 }
20641 // No longer pending, allow the polling loop to garbage collect this
20642 this._emitted["t:" + tx.hash] = receipt.blockNumber;
20643 if (receipt.status === 0) {
20644 logger$r.throwError("transaction failed", Logger.errors.CALL_EXCEPTION, {
20645 transactionHash: tx.hash,
20646 transaction: tx,
20647 receipt: receipt
20648 });
20649 }
20650 return receipt;
20651 });
20652 return result;
20653 }
20654 sendTransaction(signedTransaction) {
20655 return __awaiter$6(this, void 0, void 0, function* () {
20656 yield this.getNetwork();
20657 const hexTx = yield Promise.resolve(signedTransaction).then(t => hexlify(t));
20658 const tx = this.formatter.transaction(signedTransaction);
20659 try {
20660 const hash = yield this.perform("sendTransaction", { signedTransaction: hexTx });
20661 return this._wrapTransaction(tx, hash);
20662 }
20663 catch (error) {
20664 error.transaction = tx;
20665 error.transactionHash = tx.hash;
20666 throw error;
20667 }
20668 });
20669 }
20670 _getTransactionRequest(transaction) {
20671 return __awaiter$6(this, void 0, void 0, function* () {
20672 const values = yield transaction;
20673 const tx = {};
20674 ["from", "to"].forEach((key) => {
20675 if (values[key] == null) {
20676 return;
20677 }
20678 tx[key] = Promise.resolve(values[key]).then((v) => (v ? this._getAddress(v) : null));
20679 });
20680 ["gasLimit", "gasPrice", "value"].forEach((key) => {
20681 if (values[key] == null) {
20682 return;
20683 }
20684 tx[key] = Promise.resolve(values[key]).then((v) => (v ? BigNumber.from(v) : null));
20685 });
20686 ["data"].forEach((key) => {
20687 if (values[key] == null) {
20688 return;
20689 }
20690 tx[key] = Promise.resolve(values[key]).then((v) => (v ? hexlify(v) : null));
20691 });
20692 return this.formatter.transactionRequest(yield resolveProperties(tx));
20693 });
20694 }
20695 _getFilter(filter) {
20696 return __awaiter$6(this, void 0, void 0, function* () {
20697 filter = yield filter;
20698 const result = {};
20699 if (filter.address != null) {
20700 result.address = this._getAddress(filter.address);
20701 }
20702 ["blockHash", "topics"].forEach((key) => {
20703 if (filter[key] == null) {
20704 return;
20705 }
20706 result[key] = filter[key];
20707 });
20708 ["fromBlock", "toBlock"].forEach((key) => {
20709 if (filter[key] == null) {
20710 return;
20711 }
20712 result[key] = this._getBlockTag(filter[key]);
20713 });
20714 return this.formatter.filter(yield resolveProperties(result));
20715 });
20716 }
20717 call(transaction, blockTag) {
20718 return __awaiter$6(this, void 0, void 0, function* () {
20719 yield this.getNetwork();
20720 const params = yield resolveProperties({
20721 transaction: this._getTransactionRequest(transaction),
20722 blockTag: this._getBlockTag(blockTag)
20723 });
20724 return hexlify(yield this.perform("call", params));
20725 });
20726 }
20727 estimateGas(transaction) {
20728 return __awaiter$6(this, void 0, void 0, function* () {
20729 yield this.getNetwork();
20730 const params = yield resolveProperties({
20731 transaction: this._getTransactionRequest(transaction)
20732 });
20733 return BigNumber.from(yield this.perform("estimateGas", params));
20734 });
20735 }
20736 _getAddress(addressOrName) {
20737 return __awaiter$6(this, void 0, void 0, function* () {
20738 const address = yield this.resolveName(addressOrName);
20739 if (address == null) {
20740 logger$r.throwError("ENS name not configured", Logger.errors.UNSUPPORTED_OPERATION, {
20741 operation: `resolveName(${JSON.stringify(addressOrName)})`
20742 });
20743 }
20744 return address;
20745 });
20746 }
20747 _getBlock(blockHashOrBlockTag, includeTransactions) {
20748 return __awaiter$6(this, void 0, void 0, function* () {
20749 yield this.getNetwork();
20750 blockHashOrBlockTag = yield blockHashOrBlockTag;
20751 // If blockTag is a number (not "latest", etc), this is the block number
20752 let blockNumber = -128;
20753 const params = {
20754 includeTransactions: !!includeTransactions
20755 };
20756 if (isHexString(blockHashOrBlockTag, 32)) {
20757 params.blockHash = blockHashOrBlockTag;
20758 }
20759 else {
20760 try {
20761 params.blockTag = this.formatter.blockTag(yield this._getBlockTag(blockHashOrBlockTag));
20762 if (isHexString(params.blockTag)) {
20763 blockNumber = parseInt(params.blockTag.substring(2), 16);
20764 }
20765 }
20766 catch (error) {
20767 logger$r.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag);
20768 }
20769 }
20770 return poll(() => __awaiter$6(this, void 0, void 0, function* () {
20771 const block = yield this.perform("getBlock", params);
20772 // Block was not found
20773 if (block == null) {
20774 // For blockhashes, if we didn't say it existed, that blockhash may
20775 // not exist. If we did see it though, perhaps from a log, we know
20776 // it exists, and this node is just not caught up yet.
20777 if (params.blockHash != null) {
20778 if (this._emitted["b:" + params.blockHash] == null) {
20779 return null;
20780 }
20781 }
20782 // For block tags, if we are asking for a future block, we return null
20783 if (params.blockTag != null) {
20784 if (blockNumber > this._emitted.block) {
20785 return null;
20786 }
20787 }
20788 // Retry on the next block
20789 return undefined;
20790 }
20791 // Add transactions
20792 if (includeTransactions) {
20793 let blockNumber = null;
20794 for (let i = 0; i < block.transactions.length; i++) {
20795 const tx = block.transactions[i];
20796 if (tx.blockNumber == null) {
20797 tx.confirmations = 0;
20798 }
20799 else if (tx.confirmations == null) {
20800 if (blockNumber == null) {
20801 blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
20802 }
20803 // Add the confirmations using the fast block number (pessimistic)
20804 let confirmations = (blockNumber - tx.blockNumber) + 1;
20805 if (confirmations <= 0) {
20806 confirmations = 1;
20807 }
20808 tx.confirmations = confirmations;
20809 }
20810 }
20811 return this.formatter.blockWithTransactions(block);
20812 }
20813 return this.formatter.block(block);
20814 }), { oncePoll: this });
20815 });
20816 }
20817 getBlock(blockHashOrBlockTag) {
20818 return (this._getBlock(blockHashOrBlockTag, false));
20819 }
20820 getBlockWithTransactions(blockHashOrBlockTag) {
20821 return (this._getBlock(blockHashOrBlockTag, true));
20822 }
20823 getTransaction(transactionHash) {
20824 return __awaiter$6(this, void 0, void 0, function* () {
20825 yield this.getNetwork();
20826 transactionHash = yield transactionHash;
20827 const params = { transactionHash: this.formatter.hash(transactionHash, true) };
20828 return poll(() => __awaiter$6(this, void 0, void 0, function* () {
20829 const result = yield this.perform("getTransaction", params);
20830 if (result == null) {
20831 if (this._emitted["t:" + transactionHash] == null) {
20832 return null;
20833 }
20834 return undefined;
20835 }
20836 const tx = this.formatter.transactionResponse(result);
20837 if (tx.blockNumber == null) {
20838 tx.confirmations = 0;
20839 }
20840 else if (tx.confirmations == null) {
20841 const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
20842 // Add the confirmations using the fast block number (pessimistic)
20843 let confirmations = (blockNumber - tx.blockNumber) + 1;
20844 if (confirmations <= 0) {
20845 confirmations = 1;
20846 }
20847 tx.confirmations = confirmations;
20848 }
20849 return this._wrapTransaction(tx);
20850 }), { oncePoll: this });
20851 });
20852 }
20853 getTransactionReceipt(transactionHash) {
20854 return __awaiter$6(this, void 0, void 0, function* () {
20855 yield this.getNetwork();
20856 transactionHash = yield transactionHash;
20857 const params = { transactionHash: this.formatter.hash(transactionHash, true) };
20858 return poll(() => __awaiter$6(this, void 0, void 0, function* () {
20859 const result = yield this.perform("getTransactionReceipt", params);
20860 if (result == null) {
20861 if (this._emitted["t:" + transactionHash] == null) {
20862 return null;
20863 }
20864 return undefined;
20865 }
20866 // "geth-etc" returns receipts before they are ready
20867 if (result.blockHash == null) {
20868 return undefined;
20869 }
20870 const receipt = this.formatter.receipt(result);
20871 if (receipt.blockNumber == null) {
20872 receipt.confirmations = 0;
20873 }
20874 else if (receipt.confirmations == null) {
20875 const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
20876 // Add the confirmations using the fast block number (pessimistic)
20877 let confirmations = (blockNumber - receipt.blockNumber) + 1;
20878 if (confirmations <= 0) {
20879 confirmations = 1;
20880 }
20881 receipt.confirmations = confirmations;
20882 }
20883 return receipt;
20884 }), { oncePoll: this });
20885 });
20886 }
20887 getLogs(filter) {
20888 return __awaiter$6(this, void 0, void 0, function* () {
20889 yield this.getNetwork();
20890 const params = yield resolveProperties({ filter: this._getFilter(filter) });
20891 const logs = yield this.perform("getLogs", params);
20892 logs.forEach((log) => {
20893 if (log.removed == null) {
20894 log.removed = false;
20895 }
20896 });
20897 return Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs);
20898 });
20899 }
20900 getEtherPrice() {
20901 return __awaiter$6(this, void 0, void 0, function* () {
20902 yield this.getNetwork();
20903 return this.perform("getEtherPrice", {});
20904 });
20905 }
20906 _getBlockTag(blockTag) {
20907 return __awaiter$6(this, void 0, void 0, function* () {
20908 blockTag = yield blockTag;
20909 if (typeof (blockTag) === "number" && blockTag < 0) {
20910 if (blockTag % 1) {
20911 logger$r.throwArgumentError("invalid BlockTag", "blockTag", blockTag);
20912 }
20913 let blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval);
20914 blockNumber += blockTag;
20915 if (blockNumber < 0) {
20916 blockNumber = 0;
20917 }
20918 return this.formatter.blockTag(blockNumber);
20919 }
20920 return this.formatter.blockTag(blockTag);
20921 });
20922 }
20923 _getResolver(name) {
20924 return __awaiter$6(this, void 0, void 0, function* () {
20925 // Get the resolver from the blockchain
20926 const network = yield this.getNetwork();
20927 // No ENS...
20928 if (!network.ensAddress) {
20929 logger$r.throwError("network does not support ENS", Logger.errors.UNSUPPORTED_OPERATION, { operation: "ENS", network: network.name });
20930 }
20931 // keccak256("resolver(bytes32)")
20932 const transaction = {
20933 to: network.ensAddress,
20934 data: ("0x0178b8bf" + namehash(name).substring(2))
20935 };
20936 return this.formatter.callAddress(yield this.call(transaction));
20937 });
20938 }
20939 resolveName(name) {
20940 return __awaiter$6(this, void 0, void 0, function* () {
20941 name = yield name;
20942 // If it is already an address, nothing to resolve
20943 try {
20944 return Promise.resolve(this.formatter.address(name));
20945 }
20946 catch (error) {
20947 // If is is a hexstring, the address is bad (See #694)
20948 if (isHexString(name)) {
20949 throw error;
20950 }
20951 }
20952 if (typeof (name) !== "string") {
20953 logger$r.throwArgumentError("invalid ENS name", "name", name);
20954 }
20955 // Get the addr from the resovler
20956 const resolverAddress = yield this._getResolver(name);
20957 if (!resolverAddress) {
20958 return null;
20959 }
20960 // keccak256("addr(bytes32)")
20961 const transaction = {
20962 to: resolverAddress,
20963 data: ("0x3b3b57de" + namehash(name).substring(2))
20964 };
20965 return this.formatter.callAddress(yield this.call(transaction));
20966 });
20967 }
20968 lookupAddress(address) {
20969 return __awaiter$6(this, void 0, void 0, function* () {
20970 address = yield address;
20971 address = this.formatter.address(address);
20972 const reverseName = address.substring(2).toLowerCase() + ".addr.reverse";
20973 const resolverAddress = yield this._getResolver(reverseName);
20974 if (!resolverAddress) {
20975 return null;
20976 }
20977 // keccak("name(bytes32)")
20978 let bytes = arrayify(yield this.call({
20979 to: resolverAddress,
20980 data: ("0x691f3431" + namehash(reverseName).substring(2))
20981 }));
20982 // Strip off the dynamic string pointer (0x20)
20983 if (bytes.length < 32 || !BigNumber.from(bytes.slice(0, 32)).eq(32)) {
20984 return null;
20985 }
20986 bytes = bytes.slice(32);
20987 // Not a length-prefixed string
20988 if (bytes.length < 32) {
20989 return null;
20990 }
20991 // Get the length of the string (from the length-prefix)
20992 const length = BigNumber.from(bytes.slice(0, 32)).toNumber();
20993 bytes = bytes.slice(32);
20994 // Length longer than available data
20995 if (length > bytes.length) {
20996 return null;
20997 }
20998 const name = toUtf8String(bytes.slice(0, length));
20999 // Make sure the reverse record matches the foward record
21000 const addr = yield this.resolveName(name);
21001 if (addr != address) {
21002 return null;
21003 }
21004 return name;
21005 });
21006 }
21007 perform(method, params) {
21008 return logger$r.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
21009 }
21010 _startEvent(event) {
21011 this.polling = (this._events.filter((e) => e.pollable()).length > 0);
21012 }
21013 _stopEvent(event) {
21014 this.polling = (this._events.filter((e) => e.pollable()).length > 0);
21015 }
21016 _addEventListener(eventName, listener, once) {
21017 const event = new Event(getEventTag$1(eventName), listener, once);
21018 this._events.push(event);
21019 this._startEvent(event);
21020 return this;
21021 }
21022 on(eventName, listener) {
21023 return this._addEventListener(eventName, listener, false);
21024 }
21025 once(eventName, listener) {
21026 return this._addEventListener(eventName, listener, true);
21027 }
21028 emit(eventName, ...args) {
21029 let result = false;
21030 let stopped = [];
21031 let eventTag = getEventTag$1(eventName);
21032 this._events = this._events.filter((event) => {
21033 if (event.tag !== eventTag) {
21034 return true;
21035 }
21036 setTimeout(() => {
21037 event.listener.apply(this, args);
21038 }, 0);
21039 result = true;
21040 if (event.once) {
21041 stopped.push(event);
21042 return false;
21043 }
21044 return true;
21045 });
21046 stopped.forEach((event) => { this._stopEvent(event); });
21047 return result;
21048 }
21049 listenerCount(eventName) {
21050 if (!eventName) {
21051 return this._events.length;
21052 }
21053 let eventTag = getEventTag$1(eventName);
21054 return this._events.filter((event) => {
21055 return (event.tag === eventTag);
21056 }).length;
21057 }
21058 listeners(eventName) {
21059 if (eventName == null) {
21060 return this._events.map((event) => event.listener);
21061 }
21062 let eventTag = getEventTag$1(eventName);
21063 return this._events
21064 .filter((event) => (event.tag === eventTag))
21065 .map((event) => event.listener);
21066 }
21067 off(eventName, listener) {
21068 if (listener == null) {
21069 return this.removeAllListeners(eventName);
21070 }
21071 const stopped = [];
21072 let found = false;
21073 let eventTag = getEventTag$1(eventName);
21074 this._events = this._events.filter((event) => {
21075 if (event.tag !== eventTag || event.listener != listener) {
21076 return true;
21077 }
21078 if (found) {
21079 return true;
21080 }
21081 found = true;
21082 stopped.push(event);
21083 return false;
21084 });
21085 stopped.forEach((event) => { this._stopEvent(event); });
21086 return this;
21087 }
21088 removeAllListeners(eventName) {
21089 let stopped = [];
21090 if (eventName == null) {
21091 stopped = this._events;
21092 this._events = [];
21093 }
21094 else {
21095 const eventTag = getEventTag$1(eventName);
21096 this._events = this._events.filter((event) => {
21097 if (event.tag !== eventTag) {
21098 return true;
21099 }
21100 stopped.push(event);
21101 return false;
21102 });
21103 }
21104 stopped.forEach((event) => { this._stopEvent(event); });
21105 return this;
21106 }
21107}
21108
21109var _version$2 = createCommonjsModule(function (module, exports) {
21110"use strict";
21111Object.defineProperty(exports, "__esModule", { value: true });
21112exports.version = "providers/5.0.5";
21113
21114});
21115
21116var _version$3 = unwrapExports(_version$2);
21117var _version_1$1 = _version$2.version;
21118
21119var browserWs = createCommonjsModule(function (module, exports) {
21120"use strict";
21121Object.defineProperty(exports, "__esModule", { value: true });
21122
21123
21124var WS = null;
21125try {
21126 WS = WebSocket;
21127 if (WS == null) {
21128 throw new Error("inject please");
21129 }
21130}
21131catch (error) {
21132 var logger_2 = new lib_esm.Logger(_version$2.version);
21133 WS = function () {
21134 logger_2.throwError("WebSockets not supported in this environment", lib_esm.Logger.errors.UNSUPPORTED_OPERATION, {
21135 operation: "new WebSocket()"
21136 });
21137 };
21138}
21139module.exports = WS;
21140
21141});
21142
21143var WebSocket$1 = unwrapExports(browserWs);
21144
21145"use strict";
21146var __awaiter$7 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
21147 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
21148 return new (P || (P = Promise))(function (resolve, reject) {
21149 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21150 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21151 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
21152 step((generator = generator.apply(thisArg, _arguments || [])).next());
21153 });
21154};
21155const logger$s = new Logger(version$m);
21156function timer(timeout) {
21157 return new Promise(function (resolve) {
21158 setTimeout(resolve, timeout);
21159 });
21160}
21161function getResult(payload) {
21162 if (payload.error) {
21163 // @TODO: not any
21164 const error = new Error(payload.error.message);
21165 error.code = payload.error.code;
21166 error.data = payload.error.data;
21167 throw error;
21168 }
21169 return payload.result;
21170}
21171function getLowerCase(value) {
21172 if (value) {
21173 return value.toLowerCase();
21174 }
21175 return value;
21176}
21177const _constructorGuard$4 = {};
21178class JsonRpcSigner extends Signer {
21179 constructor(constructorGuard, provider, addressOrIndex) {
21180 logger$s.checkNew(new.target, JsonRpcSigner);
21181 super();
21182 if (constructorGuard !== _constructorGuard$4) {
21183 throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");
21184 }
21185 defineReadOnly(this, "provider", provider);
21186 if (addressOrIndex == null) {
21187 addressOrIndex = 0;
21188 }
21189 if (typeof (addressOrIndex) === "string") {
21190 defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex));
21191 defineReadOnly(this, "_index", null);
21192 }
21193 else if (typeof (addressOrIndex) === "number") {
21194 defineReadOnly(this, "_index", addressOrIndex);
21195 defineReadOnly(this, "_address", null);
21196 }
21197 else {
21198 logger$s.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex);
21199 }
21200 }
21201 connect(provider) {
21202 return logger$s.throwError("cannot alter JSON-RPC Signer connection", Logger.errors.UNSUPPORTED_OPERATION, {
21203 operation: "connect"
21204 });
21205 }
21206 connectUnchecked() {
21207 return new UncheckedJsonRpcSigner(_constructorGuard$4, this.provider, this._address || this._index);
21208 }
21209 getAddress() {
21210 if (this._address) {
21211 return Promise.resolve(this._address);
21212 }
21213 return this.provider.send("eth_accounts", []).then((accounts) => {
21214 if (accounts.length <= this._index) {
21215 logger$s.throwError("unknown account #" + this._index, Logger.errors.UNSUPPORTED_OPERATION, {
21216 operation: "getAddress"
21217 });
21218 }
21219 return this.provider.formatter.address(accounts[this._index]);
21220 });
21221 }
21222 sendUncheckedTransaction(transaction) {
21223 transaction = shallowCopy(transaction);
21224 const fromAddress = this.getAddress().then((address) => {
21225 if (address) {
21226 address = address.toLowerCase();
21227 }
21228 return address;
21229 });
21230 // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
21231 // wishes to use this, it is easy to specify explicitly, otherwise
21232 // we look it up for them.
21233 if (transaction.gasLimit == null) {
21234 const estimate = shallowCopy(transaction);
21235 estimate.from = fromAddress;
21236 transaction.gasLimit = this.provider.estimateGas(estimate);
21237 }
21238 return resolveProperties({
21239 tx: resolveProperties(transaction),
21240 sender: fromAddress
21241 }).then(({ tx, sender }) => {
21242 if (tx.from != null) {
21243 if (tx.from.toLowerCase() !== sender) {
21244 logger$s.throwArgumentError("from address mismatch", "transaction", transaction);
21245 }
21246 }
21247 else {
21248 tx.from = sender;
21249 }
21250 const hexTx = this.provider.constructor.hexlifyTransaction(tx, { from: true });
21251 return this.provider.send("eth_sendTransaction", [hexTx]).then((hash) => {
21252 return hash;
21253 }, (error) => {
21254 if (error.responseText) {
21255 // See: JsonRpcProvider.sendTransaction (@TODO: Expose a ._throwError??)
21256 if (error.responseText.indexOf("insufficient funds") >= 0) {
21257 logger$s.throwError("insufficient funds", Logger.errors.INSUFFICIENT_FUNDS, {
21258 transaction: tx
21259 });
21260 }
21261 if (error.responseText.indexOf("nonce too low") >= 0) {
21262 logger$s.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, {
21263 transaction: tx
21264 });
21265 }
21266 if (error.responseText.indexOf("replacement transaction underpriced") >= 0) {
21267 logger$s.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, {
21268 transaction: tx
21269 });
21270 }
21271 }
21272 throw error;
21273 });
21274 });
21275 }
21276 signTransaction(transaction) {
21277 return logger$s.throwError("signing transactions is unsupported", Logger.errors.UNSUPPORTED_OPERATION, {
21278 operation: "signTransaction"
21279 });
21280 }
21281 sendTransaction(transaction) {
21282 return this.sendUncheckedTransaction(transaction).then((hash) => {
21283 return poll(() => {
21284 return this.provider.getTransaction(hash).then((tx) => {
21285 if (tx === null) {
21286 return undefined;
21287 }
21288 return this.provider._wrapTransaction(tx, hash);
21289 });
21290 }, { onceBlock: this.provider }).catch((error) => {
21291 error.transactionHash = hash;
21292 throw error;
21293 });
21294 });
21295 }
21296 signMessage(message) {
21297 const data = ((typeof (message) === "string") ? toUtf8Bytes(message) : message);
21298 return this.getAddress().then((address) => {
21299 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
21300 return this.provider.send("eth_sign", [address.toLowerCase(), hexlify(data)]);
21301 });
21302 }
21303 unlock(password) {
21304 const provider = this.provider;
21305 return this.getAddress().then(function (address) {
21306 return provider.send("personal_unlockAccount", [address.toLowerCase(), password, null]);
21307 });
21308 }
21309}
21310class UncheckedJsonRpcSigner extends JsonRpcSigner {
21311 sendTransaction(transaction) {
21312 return this.sendUncheckedTransaction(transaction).then((hash) => {
21313 return {
21314 hash: hash,
21315 nonce: null,
21316 gasLimit: null,
21317 gasPrice: null,
21318 data: null,
21319 value: null,
21320 chainId: null,
21321 confirmations: 0,
21322 from: null,
21323 wait: (confirmations) => { return this.provider.waitForTransaction(hash, confirmations); }
21324 };
21325 });
21326 }
21327}
21328const allowedTransactionKeys$3 = {
21329 chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true
21330};
21331class JsonRpcProvider extends BaseProvider {
21332 constructor(url, network) {
21333 logger$s.checkNew(new.target, JsonRpcProvider);
21334 let networkOrReady = network;
21335 // The network is unknown, query the JSON-RPC for it
21336 if (networkOrReady == null) {
21337 networkOrReady = new Promise((resolve, reject) => {
21338 setTimeout(() => {
21339 this.detectNetwork().then((network) => {
21340 resolve(network);
21341 }, (error) => {
21342 reject(error);
21343 });
21344 }, 0);
21345 });
21346 }
21347 super(networkOrReady);
21348 // Default URL
21349 if (!url) {
21350 url = getStatic(this.constructor, "defaultUrl")();
21351 }
21352 if (typeof (url) === "string") {
21353 defineReadOnly(this, "connection", Object.freeze({
21354 url: url
21355 }));
21356 }
21357 else {
21358 defineReadOnly(this, "connection", Object.freeze(shallowCopy(url)));
21359 }
21360 this._nextId = 42;
21361 }
21362 static defaultUrl() {
21363 return "http:/\/localhost:8545";
21364 }
21365 detectNetwork() {
21366 return __awaiter$7(this, void 0, void 0, function* () {
21367 yield timer(0);
21368 let chainId = null;
21369 try {
21370 chainId = yield this.send("eth_chainId", []);
21371 }
21372 catch (error) {
21373 try {
21374 chainId = yield this.send("net_version", []);
21375 }
21376 catch (error) { }
21377 }
21378 if (chainId != null) {
21379 const getNetwork = getStatic(this.constructor, "getNetwork");
21380 try {
21381 return getNetwork(BigNumber.from(chainId).toNumber());
21382 }
21383 catch (error) {
21384 return logger$s.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
21385 chainId: chainId,
21386 event: "invalidNetwork",
21387 serverError: error
21388 });
21389 }
21390 }
21391 return logger$s.throwError("could not detect network", Logger.errors.NETWORK_ERROR, {
21392 event: "noNetwork"
21393 });
21394 });
21395 }
21396 getSigner(addressOrIndex) {
21397 return new JsonRpcSigner(_constructorGuard$4, this, addressOrIndex);
21398 }
21399 getUncheckedSigner(addressOrIndex) {
21400 return this.getSigner(addressOrIndex).connectUnchecked();
21401 }
21402 listAccounts() {
21403 return this.send("eth_accounts", []).then((accounts) => {
21404 return accounts.map((a) => this.formatter.address(a));
21405 });
21406 }
21407 send(method, params) {
21408 const request = {
21409 method: method,
21410 params: params,
21411 id: (this._nextId++),
21412 jsonrpc: "2.0"
21413 };
21414 this.emit("debug", {
21415 action: "request",
21416 request: deepCopy(request),
21417 provider: this
21418 });
21419 return fetchJson(this.connection, JSON.stringify(request), getResult).then((result) => {
21420 this.emit("debug", {
21421 action: "response",
21422 request: request,
21423 response: result,
21424 provider: this
21425 });
21426 return result;
21427 }, (error) => {
21428 this.emit("debug", {
21429 action: "response",
21430 error: error,
21431 request: request,
21432 provider: this
21433 });
21434 throw error;
21435 });
21436 }
21437 prepareRequest(method, params) {
21438 switch (method) {
21439 case "getBlockNumber":
21440 return ["eth_blockNumber", []];
21441 case "getGasPrice":
21442 return ["eth_gasPrice", []];
21443 case "getBalance":
21444 return ["eth_getBalance", [getLowerCase(params.address), params.blockTag]];
21445 case "getTransactionCount":
21446 return ["eth_getTransactionCount", [getLowerCase(params.address), params.blockTag]];
21447 case "getCode":
21448 return ["eth_getCode", [getLowerCase(params.address), params.blockTag]];
21449 case "getStorageAt":
21450 return ["eth_getStorageAt", [getLowerCase(params.address), params.position, params.blockTag]];
21451 case "sendTransaction":
21452 return ["eth_sendRawTransaction", [params.signedTransaction]];
21453 case "getBlock":
21454 if (params.blockTag) {
21455 return ["eth_getBlockByNumber", [params.blockTag, !!params.includeTransactions]];
21456 }
21457 else if (params.blockHash) {
21458 return ["eth_getBlockByHash", [params.blockHash, !!params.includeTransactions]];
21459 }
21460 return null;
21461 case "getTransaction":
21462 return ["eth_getTransactionByHash", [params.transactionHash]];
21463 case "getTransactionReceipt":
21464 return ["eth_getTransactionReceipt", [params.transactionHash]];
21465 case "call": {
21466 const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
21467 return ["eth_call", [hexlifyTransaction(params.transaction, { from: true }), params.blockTag]];
21468 }
21469 case "estimateGas": {
21470 const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction");
21471 return ["eth_estimateGas", [hexlifyTransaction(params.transaction, { from: true })]];
21472 }
21473 case "getLogs":
21474 if (params.filter && params.filter.address != null) {
21475 params.filter.address = getLowerCase(params.filter.address);
21476 }
21477 return ["eth_getLogs", [params.filter]];
21478 default:
21479 break;
21480 }
21481 return null;
21482 }
21483 perform(method, params) {
21484 const args = this.prepareRequest(method, params);
21485 if (args == null) {
21486 logger$s.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { operation: method });
21487 }
21488 // We need a little extra logic to process errors from sendTransaction
21489 if (method === "sendTransaction") {
21490 return this.send(args[0], args[1]).catch((error) => {
21491 if (error.responseText) {
21492 // "insufficient funds for gas * price + value"
21493 if (error.responseText.indexOf("insufficient funds") > 0) {
21494 logger$s.throwError("insufficient funds", Logger.errors.INSUFFICIENT_FUNDS, {});
21495 }
21496 // "nonce too low"
21497 if (error.responseText.indexOf("nonce too low") > 0) {
21498 logger$s.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, {});
21499 }
21500 // "replacement transaction underpriced"
21501 if (error.responseText.indexOf("replacement transaction underpriced") > 0) {
21502 logger$s.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, {});
21503 }
21504 }
21505 throw error;
21506 });
21507 }
21508 return this.send(args[0], args[1]);
21509 }
21510 _startEvent(event) {
21511 if (event.tag === "pending") {
21512 this._startPending();
21513 }
21514 super._startEvent(event);
21515 }
21516 _startPending() {
21517 if (this._pendingFilter != null) {
21518 return;
21519 }
21520 const self = this;
21521 const pendingFilter = this.send("eth_newPendingTransactionFilter", []);
21522 this._pendingFilter = pendingFilter;
21523 pendingFilter.then(function (filterId) {
21524 function poll() {
21525 self.send("eth_getFilterChanges", [filterId]).then(function (hashes) {
21526 if (self._pendingFilter != pendingFilter) {
21527 return null;
21528 }
21529 let seq = Promise.resolve();
21530 hashes.forEach(function (hash) {
21531 // @TODO: This should be garbage collected at some point... How? When?
21532 self._emitted["t:" + hash.toLowerCase()] = "pending";
21533 seq = seq.then(function () {
21534 return self.getTransaction(hash).then(function (tx) {
21535 self.emit("pending", tx);
21536 return null;
21537 });
21538 });
21539 });
21540 return seq.then(function () {
21541 return timer(1000);
21542 });
21543 }).then(function () {
21544 if (self._pendingFilter != pendingFilter) {
21545 self.send("eth_uninstallFilter", [filterId]);
21546 return;
21547 }
21548 setTimeout(function () { poll(); }, 0);
21549 return null;
21550 }).catch((error) => { });
21551 }
21552 poll();
21553 return filterId;
21554 }).catch((error) => { });
21555 }
21556 _stopEvent(event) {
21557 if (event.tag === "pending" && this.listenerCount("pending") === 0) {
21558 this._pendingFilter = null;
21559 }
21560 super._stopEvent(event);
21561 }
21562 // Convert an ethers.js transaction into a JSON-RPC transaction
21563 // - gasLimit => gas
21564 // - All values hexlified
21565 // - All numeric values zero-striped
21566 // - All addresses are lowercased
21567 // NOTE: This allows a TransactionRequest, but all values should be resolved
21568 // before this is called
21569 // @TODO: This will likely be removed in future versions and prepareRequest
21570 // will be the preferred method for this.
21571 static hexlifyTransaction(transaction, allowExtra) {
21572 // Check only allowed properties are given
21573 const allowed = shallowCopy(allowedTransactionKeys$3);
21574 if (allowExtra) {
21575 for (const key in allowExtra) {
21576 if (allowExtra[key]) {
21577 allowed[key] = true;
21578 }
21579 }
21580 }
21581 checkProperties(transaction, allowed);
21582 const result = {};
21583 // Some nodes (INFURA ropsten; INFURA mainnet is fine) do not like leading zeros.
21584 ["gasLimit", "gasPrice", "nonce", "value"].forEach(function (key) {
21585 if (transaction[key] == null) {
21586 return;
21587 }
21588 const value = hexValue(transaction[key]);
21589 if (key === "gasLimit") {
21590 key = "gas";
21591 }
21592 result[key] = value;
21593 });
21594 ["from", "to", "data"].forEach(function (key) {
21595 if (transaction[key] == null) {
21596 return;
21597 }
21598 result[key] = hexlify(transaction[key]);
21599 });
21600 return result;
21601 }
21602}
21603
21604"use strict";
21605var __awaiter$8 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
21606 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
21607 return new (P || (P = Promise))(function (resolve, reject) {
21608 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21609 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21610 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
21611 step((generator = generator.apply(thisArg, _arguments || [])).next());
21612 });
21613};
21614const logger$t = new Logger(version$m);
21615/**
21616 * Notes:
21617 *
21618 * This provider differs a bit from the polling providers. One main
21619 * difference is how it handles consistency. The polling providers
21620 * will stall responses to ensure a consistent state, while this
21621 * WebSocket provider assumes the connected backend will manage this.
21622 *
21623 * For example, if a polling provider emits an event which indicats
21624 * the event occurred in blockhash XXX, a call to fetch that block by
21625 * its hash XXX, if not present will retry until it is present. This
21626 * can occur when querying a pool of nodes that are mildly out of sync
21627 * with each other.
21628 */
21629let NextId = 1;
21630// For more info about the Real-time Event API see:
21631// https://geth.ethereum.org/docs/rpc/pubsub
21632class WebSocketProvider extends JsonRpcProvider {
21633 constructor(url, network) {
21634 // This will be added in the future; please open an issue to expedite
21635 if (network === "any") {
21636 logger$t.throwError("WebSocketProvider does not support 'any' network yet", Logger.errors.UNSUPPORTED_OPERATION, {
21637 operation: "network:any"
21638 });
21639 }
21640 super(url, network);
21641 this._pollingInterval = -1;
21642 defineReadOnly(this, "_websocket", new WebSocket$1(this.connection.url));
21643 defineReadOnly(this, "_requests", {});
21644 defineReadOnly(this, "_subs", {});
21645 defineReadOnly(this, "_subIds", {});
21646 // Stall sending requests until the socket is open...
21647 this._wsReady = false;
21648 this._websocket.onopen = () => {
21649 this._wsReady = true;
21650 Object.keys(this._requests).forEach((id) => {
21651 this._websocket.send(this._requests[id].payload);
21652 });
21653 };
21654 this._websocket.onmessage = (messageEvent) => {
21655 const data = messageEvent.data;
21656 const result = JSON.parse(data);
21657 if (result.id != null) {
21658 const id = String(result.id);
21659 const request = this._requests[id];
21660 delete this._requests[id];
21661 if (result.result !== undefined) {
21662 request.callback(null, result.result);
21663 }
21664 else {
21665 if (result.error) {
21666 const error = new Error(result.error.message || "unknown error");
21667 defineReadOnly(error, "code", result.error.code || null);
21668 defineReadOnly(error, "response", data);
21669 request.callback(error, undefined);
21670 }
21671 else {
21672 request.callback(new Error("unknown error"), undefined);
21673 }
21674 }
21675 }
21676 else if (result.method === "eth_subscription") {
21677 // Subscription...
21678 const sub = this._subs[result.params.subscription];
21679 if (sub) {
21680 //this.emit.apply(this, );
21681 sub.processFunc(result.params.result);
21682 }
21683 }
21684 else {
21685 console.warn("this should not happen");
21686 }
21687 };
21688 // This Provider does not actually poll, but we want to trigger
21689 // poll events for things that depend on them (like stalling for
21690 // block and transaction lookups)
21691 const fauxPoll = setInterval(() => {
21692 this.emit("poll");
21693 }, 1000);
21694 if (fauxPoll.unref) {
21695 fauxPoll.unref();
21696 }
21697 }
21698 get pollingInterval() {
21699 return 0;
21700 }
21701 resetEventsBlock(blockNumber) {
21702 logger$t.throwError("cannot reset events block on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, {
21703 operation: "resetEventBlock"
21704 });
21705 }
21706 set pollingInterval(value) {
21707 logger$t.throwError("cannot set polling interval on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, {
21708 operation: "setPollingInterval"
21709 });
21710 }
21711 poll() {
21712 return __awaiter$8(this, void 0, void 0, function* () {
21713 return null;
21714 });
21715 }
21716 set polling(value) {
21717 if (!value) {
21718 return;
21719 }
21720 logger$t.throwError("cannot set polling on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, {
21721 operation: "setPolling"
21722 });
21723 }
21724 send(method, params) {
21725 const rid = NextId++;
21726 return new Promise((resolve, reject) => {
21727 function callback(error, result) {
21728 if (error) {
21729 return reject(error);
21730 }
21731 return resolve(result);
21732 }
21733 const payload = JSON.stringify({
21734 method: method,
21735 params: params,
21736 id: rid,
21737 jsonrpc: "2.0"
21738 });
21739 this._requests[String(rid)] = { callback, payload };
21740 if (this._wsReady) {
21741 this._websocket.send(payload);
21742 }
21743 });
21744 }
21745 static defaultUrl() {
21746 return "ws:/\/localhost:8546";
21747 }
21748 _subscribe(tag, param, processFunc) {
21749 return __awaiter$8(this, void 0, void 0, function* () {
21750 let subIdPromise = this._subIds[tag];
21751 if (subIdPromise == null) {
21752 subIdPromise = Promise.all(param).then((param) => {
21753 return this.send("eth_subscribe", param);
21754 });
21755 this._subIds[tag] = subIdPromise;
21756 }
21757 const subId = yield subIdPromise;
21758 this._subs[subId] = { tag, processFunc };
21759 });
21760 }
21761 _startEvent(event) {
21762 switch (event.type) {
21763 case "block":
21764 this._subscribe("block", ["newHeads"], (result) => {
21765 const blockNumber = BigNumber.from(result.number).toNumber();
21766 this._emitted.block = blockNumber;
21767 this.emit("block", blockNumber);
21768 });
21769 break;
21770 case "pending":
21771 this._subscribe("pending", ["newPendingTransactions"], (result) => {
21772 this.emit("pending", result);
21773 });
21774 break;
21775 case "filter":
21776 this._subscribe(event.tag, ["logs", this._getFilter(event.filter)], (result) => {
21777 if (result.removed == null) {
21778 result.removed = false;
21779 }
21780 this.emit(event.filter, this.formatter.filterLog(result));
21781 });
21782 break;
21783 case "tx": {
21784 const emitReceipt = (event) => {
21785 const hash = event.hash;
21786 this.getTransactionReceipt(hash).then((receipt) => {
21787 if (!receipt) {
21788 return;
21789 }
21790 this.emit(hash, receipt);
21791 });
21792 };
21793 // In case it is already mined
21794 emitReceipt(event);
21795 // To keep things simple, we start up a single newHeads subscription
21796 // to keep an eye out for transactions we are watching for.
21797 // Starting a subscription for an event (i.e. "tx") that is already
21798 // running is (basically) a nop.
21799 this._subscribe("tx", ["newHeads"], (result) => {
21800 this._events.filter((e) => (e.type === "tx")).forEach(emitReceipt);
21801 });
21802 break;
21803 }
21804 // Nothing is needed
21805 case "debug":
21806 case "poll":
21807 case "willPoll":
21808 case "didPoll":
21809 case "error":
21810 break;
21811 default:
21812 console.log("unhandled:", event);
21813 break;
21814 }
21815 }
21816 _stopEvent(event) {
21817 let tag = event.tag;
21818 if (event.type === "tx") {
21819 // There are remaining transaction event listeners
21820 if (this._events.filter((e) => (e.type === "tx")).length) {
21821 return;
21822 }
21823 tag = "tx";
21824 }
21825 else if (this.listenerCount(event.event)) {
21826 // There are remaining event listeners
21827 return;
21828 }
21829 const subId = this._subIds[tag];
21830 if (!subId) {
21831 return;
21832 }
21833 delete this._subIds[tag];
21834 subId.then((subId) => {
21835 if (!this._subs[subId]) {
21836 return;
21837 }
21838 delete this._subs[subId];
21839 this.send("eth_unsubscribe", [subId]);
21840 });
21841 }
21842 destroy() {
21843 return __awaiter$8(this, void 0, void 0, function* () {
21844 // Wait until we have connected before trying to disconnect
21845 if (this._websocket.readyState === WebSocket$1.CONNECTING) {
21846 yield (new Promise((resolve) => {
21847 this._websocket.onopen = function () {
21848 resolve(true);
21849 };
21850 this._websocket.onerror = function () {
21851 resolve(false);
21852 };
21853 }));
21854 }
21855 // Hangup
21856 // See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
21857 this._websocket.close(1000);
21858 });
21859 }
21860}
21861
21862"use strict";
21863var __awaiter$9 = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
21864 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
21865 return new (P || (P = Promise))(function (resolve, reject) {
21866 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21867 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21868 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
21869 step((generator = generator.apply(thisArg, _arguments || [])).next());
21870 });
21871};
21872const logger$u = new Logger(version$m);
21873// A StaticJsonRpcProvider is useful when you *know* for certain that
21874// the backend will never change, as it never calls eth_chainId to
21875// verify its backend. However, if the backend does change, the effects
21876// are undefined and may include:
21877// - inconsistent results
21878// - locking up the UI
21879// - block skew warnings
21880// - wrong results
21881// If the network is not explicit (i.e. auto-detection is expected), the
21882// node MUST be running and available to respond to requests BEFORE this
21883// is instantiated.
21884class StaticJsonRpcProvider extends JsonRpcProvider {
21885 detectNetwork() {
21886 const _super = Object.create(null, {
21887 detectNetwork: { get: () => super.detectNetwork }
21888 });
21889 return __awaiter$9(this, void 0, void 0, function* () {
21890 let network = this.network;
21891 if (network == null) {
21892 network = yield _super.detectNetwork.call(this);
21893 if (!network) {
21894 logger$u.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, {});
21895 }
21896 // If still not set, set it
21897 if (this._network == null) {
21898 // A static network does not support "any"
21899 defineReadOnly(this, "_network", network);
21900 this.emit("network", network, null);
21901 }
21902 }
21903 return network;
21904 });
21905 }
21906}
21907class UrlJsonRpcProvider extends StaticJsonRpcProvider {
21908 constructor(network, apiKey) {
21909 logger$u.checkAbstract(new.target, UrlJsonRpcProvider);
21910 // Normalize the Network and API Key
21911 network = getStatic((new.target), "getNetwork")(network);
21912 apiKey = getStatic((new.target), "getApiKey")(apiKey);
21913 const connection = getStatic((new.target), "getUrl")(network, apiKey);
21914 super(connection, network);
21915 if (typeof (apiKey) === "string") {
21916 defineReadOnly(this, "apiKey", apiKey);
21917 }
21918 else if (apiKey != null) {
21919 Object.keys(apiKey).forEach((key) => {
21920 defineReadOnly(this, key, apiKey[key]);
21921 });
21922 }
21923 }
21924 _startPending() {
21925 logger$u.warn("WARNING: API provider does not support pending filters");
21926 }
21927 getSigner(address) {
21928 return logger$u.throwError("API provider does not support signing", Logger.errors.UNSUPPORTED_OPERATION, { operation: "getSigner" });
21929 }
21930 listAccounts() {
21931 return Promise.resolve([]);
21932 }
21933 // Return a defaultApiKey if null, otherwise validate the API key
21934 static getApiKey(apiKey) {
21935 return apiKey;
21936 }
21937 // Returns the url or connection for the given network and API key. The
21938 // API key will have been sanitized by the getApiKey first, so any validation
21939 // or transformations can be done there.
21940 static getUrl(network, apiKey) {
21941 return logger$u.throwError("not implemented; sub-classes must override getUrl", Logger.errors.NOT_IMPLEMENTED, {
21942 operation: "getUrl"
21943 });
21944 }
21945}
21946
21947"use strict";
21948const logger$v = new Logger(version$m);
21949// This key was provided to ethers.js by Alchemy to be used by the
21950// default provider, but it is recommended that for your own
21951// production environments, that you acquire your own API key at:
21952// https://dashboard.alchemyapi.io
21953const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";
21954class AlchemyProvider extends UrlJsonRpcProvider {
21955 static getWebSocketProvider(network, apiKey) {
21956 const provider = new AlchemyProvider(network, apiKey);
21957 const url = provider.connection.url.replace(/^http/i, "ws")
21958 .replace(".alchemyapi.", ".ws.alchemyapi.");
21959 return new WebSocketProvider(url, provider.network);
21960 }
21961 static getApiKey(apiKey) {
21962 if (apiKey == null) {
21963 return defaultApiKey;
21964 }
21965 if (apiKey && typeof (apiKey) !== "string") {
21966 logger$v.throwArgumentError("invalid apiKey", "apiKey", apiKey);
21967 }
21968 return apiKey;
21969 }
21970 static getUrl(network, apiKey) {
21971 let host = null;
21972 switch (network.name) {
21973 case "homestead":
21974 host = "eth-mainnet.alchemyapi.io/v2/";
21975 break;
21976 case "ropsten":
21977 host = "eth-ropsten.alchemyapi.io/v2/";
21978 break;
21979 case "rinkeby":
21980 host = "eth-rinkeby.alchemyapi.io/v2/";
21981 break;
21982 case "goerli":
21983 host = "eth-goerli.alchemyapi.io/v2/";
21984 break;
21985 case "kovan":
21986 host = "eth-kovan.alchemyapi.io/v2/";
21987 break;
21988 default:
21989 logger$v.throwArgumentError("unsupported network", "network", arguments[0]);
21990 }
21991 return {
21992 url: ("https:/" + "/" + host + apiKey),
21993 throttleCallback: (attempt, url) => {
21994 if (apiKey === defaultApiKey) {
21995 showThrottleMessage();
21996 }
21997 return Promise.resolve(true);
21998 }
21999 };
22000 }
22001}
22002
22003"use strict";
22004var __awaiter$a = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
22005 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
22006 return new (P || (P = Promise))(function (resolve, reject) {
22007 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22008 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22009 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22010 step((generator = generator.apply(thisArg, _arguments || [])).next());
22011 });
22012};
22013const logger$w = new Logger(version$m);
22014class CloudflareProvider extends UrlJsonRpcProvider {
22015 static getApiKey(apiKey) {
22016 if (apiKey != null) {
22017 logger$w.throwArgumentError("apiKey not supported for cloudflare", "apiKey", apiKey);
22018 }
22019 return null;
22020 }
22021 static getUrl(network, apiKey) {
22022 let host = null;
22023 switch (network.name) {
22024 case "homestead":
22025 host = "https://cloudflare-eth.com/";
22026 break;
22027 default:
22028 logger$w.throwArgumentError("unsupported network", "network", arguments[0]);
22029 }
22030 return host;
22031 }
22032 perform(method, params) {
22033 const _super = Object.create(null, {
22034 perform: { get: () => super.perform }
22035 });
22036 return __awaiter$a(this, void 0, void 0, function* () {
22037 // The Cloudflare provider does not support eth_blockNumber,
22038 // so we get the latest block and pull it from that
22039 if (method === "getBlockNumber") {
22040 const block = yield _super.perform.call(this, "getBlock", { blockTag: "latest" });
22041 return block.number;
22042 }
22043 return _super.perform.call(this, method, params);
22044 });
22045 }
22046}
22047
22048"use strict";
22049var __awaiter$b = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
22050 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
22051 return new (P || (P = Promise))(function (resolve, reject) {
22052 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22053 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22054 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22055 step((generator = generator.apply(thisArg, _arguments || [])).next());
22056 });
22057};
22058const logger$x = new Logger(version$m);
22059// The transaction has already been sanitized by the calls in Provider
22060function getTransactionString(transaction) {
22061 const result = [];
22062 for (let key in transaction) {
22063 if (transaction[key] == null) {
22064 continue;
22065 }
22066 let value = hexlify(transaction[key]);
22067 if ({ gasLimit: true, gasPrice: true, nonce: true, value: true }[key]) {
22068 value = hexValue(value);
22069 }
22070 result.push(key + "=" + value);
22071 }
22072 return result.join("&");
22073}
22074function getResult$1(result) {
22075 // getLogs, getHistory have weird success responses
22076 if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) {
22077 return result.result;
22078 }
22079 if (result.status != 1 || result.message != "OK") {
22080 const error = new Error("invalid response");
22081 error.result = JSON.stringify(result);
22082 if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) {
22083 error.throttleRetry = true;
22084 }
22085 throw error;
22086 }
22087 return result.result;
22088}
22089function getJsonResult(result) {
22090 // This response indicates we are being throttled
22091 if (result && result.status == 0 && result.message == "NOTOK" && (result.result || "").toLowerCase().indexOf("rate limit") >= 0) {
22092 const error = new Error("throttled response");
22093 error.result = JSON.stringify(result);
22094 error.throttleRetry = true;
22095 throw error;
22096 }
22097 if (result.jsonrpc != "2.0") {
22098 // @TODO: not any
22099 const error = new Error("invalid response");
22100 error.result = JSON.stringify(result);
22101 throw error;
22102 }
22103 if (result.error) {
22104 // @TODO: not any
22105 const error = new Error(result.error.message || "unknown error");
22106 if (result.error.code) {
22107 error.code = result.error.code;
22108 }
22109 if (result.error.data) {
22110 error.data = result.error.data;
22111 }
22112 throw error;
22113 }
22114 return result.result;
22115}
22116// The blockTag was normalized as a string by the Provider pre-perform operations
22117function checkLogTag(blockTag) {
22118 if (blockTag === "pending") {
22119 throw new Error("pending not supported");
22120 }
22121 if (blockTag === "latest") {
22122 return blockTag;
22123 }
22124 return parseInt(blockTag.substring(2), 16);
22125}
22126const defaultApiKey$1 = "9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB";
22127class EtherscanProvider extends BaseProvider {
22128 constructor(network, apiKey) {
22129 logger$x.checkNew(new.target, EtherscanProvider);
22130 super(network);
22131 let name = "invalid";
22132 if (this.network) {
22133 name = this.network.name;
22134 }
22135 let baseUrl = null;
22136 switch (name) {
22137 case "homestead":
22138 baseUrl = "https://api.etherscan.io";
22139 break;
22140 case "ropsten":
22141 baseUrl = "https://api-ropsten.etherscan.io";
22142 break;
22143 case "rinkeby":
22144 baseUrl = "https://api-rinkeby.etherscan.io";
22145 break;
22146 case "kovan":
22147 baseUrl = "https://api-kovan.etherscan.io";
22148 break;
22149 case "goerli":
22150 baseUrl = "https://api-goerli.etherscan.io";
22151 break;
22152 default:
22153 throw new Error("unsupported network");
22154 }
22155 defineReadOnly(this, "baseUrl", baseUrl);
22156 defineReadOnly(this, "apiKey", apiKey || defaultApiKey$1);
22157 }
22158 detectNetwork() {
22159 return __awaiter$b(this, void 0, void 0, function* () {
22160 return this.network;
22161 });
22162 }
22163 perform(method, params) {
22164 const _super = Object.create(null, {
22165 perform: { get: () => super.perform }
22166 });
22167 return __awaiter$b(this, void 0, void 0, function* () {
22168 let url = this.baseUrl;
22169 let apiKey = "";
22170 if (this.apiKey) {
22171 apiKey += "&apikey=" + this.apiKey;
22172 }
22173 const get = (url, procFunc) => __awaiter$b(this, void 0, void 0, function* () {
22174 this.emit("debug", {
22175 action: "request",
22176 request: url,
22177 provider: this
22178 });
22179 const connection = {
22180 url: url,
22181 throttleSlotInterval: 1000,
22182 throttleCallback: (attempt, url) => {
22183 if (this.apiKey === defaultApiKey$1) {
22184 showThrottleMessage();
22185 }
22186 return Promise.resolve(true);
22187 }
22188 };
22189 const result = yield fetchJson(connection, null, procFunc || getJsonResult);
22190 this.emit("debug", {
22191 action: "response",
22192 request: url,
22193 response: deepCopy(result),
22194 provider: this
22195 });
22196 return result;
22197 });
22198 switch (method) {
22199 case "getBlockNumber":
22200 url += "/api?module=proxy&action=eth_blockNumber" + apiKey;
22201 return get(url);
22202 case "getGasPrice":
22203 url += "/api?module=proxy&action=eth_gasPrice" + apiKey;
22204 return get(url);
22205 case "getBalance":
22206 // Returns base-10 result
22207 url += "/api?module=account&action=balance&address=" + params.address;
22208 url += "&tag=" + params.blockTag + apiKey;
22209 return get(url, getResult$1);
22210 case "getTransactionCount":
22211 url += "/api?module=proxy&action=eth_getTransactionCount&address=" + params.address;
22212 url += "&tag=" + params.blockTag + apiKey;
22213 return get(url);
22214 case "getCode":
22215 url += "/api?module=proxy&action=eth_getCode&address=" + params.address;
22216 url += "&tag=" + params.blockTag + apiKey;
22217 return get(url);
22218 case "getStorageAt":
22219 url += "/api?module=proxy&action=eth_getStorageAt&address=" + params.address;
22220 url += "&position=" + params.position;
22221 url += "&tag=" + params.blockTag + apiKey;
22222 return get(url);
22223 case "sendTransaction":
22224 url += "/api?module=proxy&action=eth_sendRawTransaction&hex=" + params.signedTransaction;
22225 url += apiKey;
22226 return get(url).catch((error) => {
22227 if (error.responseText) {
22228 // "Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 21464000000000 and got: 0"
22229 if (error.responseText.toLowerCase().indexOf("insufficient funds") >= 0) {
22230 logger$x.throwError("insufficient funds", Logger.errors.INSUFFICIENT_FUNDS, {});
22231 }
22232 // "Transaction with the same hash was already imported."
22233 if (error.responseText.indexOf("same hash was already imported") >= 0) {
22234 logger$x.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, {});
22235 }
22236 // "Transaction gas price is too low. There is another transaction with same nonce in the queue. Try increasing the gas price or incrementing the nonce."
22237 if (error.responseText.indexOf("another transaction with same nonce") >= 0) {
22238 logger$x.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, {});
22239 }
22240 }
22241 throw error;
22242 });
22243 case "getBlock":
22244 if (params.blockTag) {
22245 url += "/api?module=proxy&action=eth_getBlockByNumber&tag=" + params.blockTag;
22246 if (params.includeTransactions) {
22247 url += "&boolean=true";
22248 }
22249 else {
22250 url += "&boolean=false";
22251 }
22252 url += apiKey;
22253 return get(url);
22254 }
22255 throw new Error("getBlock by blockHash not implemented");
22256 case "getTransaction":
22257 url += "/api?module=proxy&action=eth_getTransactionByHash&txhash=" + params.transactionHash;
22258 url += apiKey;
22259 return get(url);
22260 case "getTransactionReceipt":
22261 url += "/api?module=proxy&action=eth_getTransactionReceipt&txhash=" + params.transactionHash;
22262 url += apiKey;
22263 return get(url);
22264 case "call": {
22265 let transaction = getTransactionString(params.transaction);
22266 if (transaction) {
22267 transaction = "&" + transaction;
22268 }
22269 url += "/api?module=proxy&action=eth_call" + transaction;
22270 //url += "&tag=" + params.blockTag + apiKey;
22271 if (params.blockTag !== "latest") {
22272 throw new Error("EtherscanProvider does not support blockTag for call");
22273 }
22274 url += apiKey;
22275 return get(url);
22276 }
22277 case "estimateGas": {
22278 let transaction = getTransactionString(params.transaction);
22279 if (transaction) {
22280 transaction = "&" + transaction;
22281 }
22282 url += "/api?module=proxy&action=eth_estimateGas&" + transaction;
22283 url += apiKey;
22284 return get(url);
22285 }
22286 case "getLogs": {
22287 url += "/api?module=logs&action=getLogs";
22288 if (params.filter.fromBlock) {
22289 url += "&fromBlock=" + checkLogTag(params.filter.fromBlock);
22290 }
22291 if (params.filter.toBlock) {
22292 url += "&toBlock=" + checkLogTag(params.filter.toBlock);
22293 }
22294 if (params.filter.address) {
22295 url += "&address=" + params.filter.address;
22296 }
22297 // @TODO: We can handle slightly more complicated logs using the logs API
22298 if (params.filter.topics && params.filter.topics.length > 0) {
22299 if (params.filter.topics.length > 1) {
22300 logger$x.throwError("unsupported topic count", Logger.errors.UNSUPPORTED_OPERATION, { topics: params.filter.topics });
22301 }
22302 if (params.filter.topics.length === 1) {
22303 const topic0 = params.filter.topics[0];
22304 if (typeof (topic0) !== "string" || topic0.length !== 66) {
22305 logger$x.throwError("unsupported topic format", Logger.errors.UNSUPPORTED_OPERATION, { topic0: topic0 });
22306 }
22307 url += "&topic0=" + topic0;
22308 }
22309 }
22310 url += apiKey;
22311 const logs = yield get(url, getResult$1);
22312 // Cache txHash => blockHash
22313 let txs = {};
22314 // Add any missing blockHash to the logs
22315 for (let i = 0; i < logs.length; i++) {
22316 const log = logs[i];
22317 if (log.blockHash != null) {
22318 continue;
22319 }
22320 if (txs[log.transactionHash] == null) {
22321 const tx = yield this.getTransaction(log.transactionHash);
22322 if (tx) {
22323 txs[log.transactionHash] = tx.blockHash;
22324 }
22325 }
22326 log.blockHash = txs[log.transactionHash];
22327 }
22328 return logs;
22329 }
22330 case "getEtherPrice":
22331 if (this.network.name !== "homestead") {
22332 return 0.0;
22333 }
22334 url += "/api?module=stats&action=ethprice";
22335 url += apiKey;
22336 return parseFloat((yield get(url, getResult$1)).ethusd);
22337 default:
22338 break;
22339 }
22340 return _super.perform.call(this, method, params);
22341 });
22342 }
22343 // @TODO: Allow startBlock and endBlock to be Promises
22344 getHistory(addressOrName, startBlock, endBlock) {
22345 let url = this.baseUrl;
22346 let apiKey = "";
22347 if (this.apiKey) {
22348 apiKey += "&apikey=" + this.apiKey;
22349 }
22350 if (startBlock == null) {
22351 startBlock = 0;
22352 }
22353 if (endBlock == null) {
22354 endBlock = 99999999;
22355 }
22356 return this.resolveName(addressOrName).then((address) => {
22357 url += "/api?module=account&action=txlist&address=" + address;
22358 url += "&startblock=" + startBlock;
22359 url += "&endblock=" + endBlock;
22360 url += "&sort=asc" + apiKey;
22361 this.emit("debug", {
22362 action: "request",
22363 request: url,
22364 provider: this
22365 });
22366 const connection = {
22367 url: url,
22368 throttleSlotInterval: 1000,
22369 throttleCallback: (attempt, url) => {
22370 if (this.apiKey === defaultApiKey$1) {
22371 showThrottleMessage();
22372 }
22373 return Promise.resolve(true);
22374 }
22375 };
22376 return fetchJson(connection, null, getResult$1).then((result) => {
22377 this.emit("debug", {
22378 action: "response",
22379 request: url,
22380 response: deepCopy(result),
22381 provider: this
22382 });
22383 let output = [];
22384 result.forEach((tx) => {
22385 ["contractAddress", "to"].forEach(function (key) {
22386 if (tx[key] == "") {
22387 delete tx[key];
22388 }
22389 });
22390 if (tx.creates == null && tx.contractAddress != null) {
22391 tx.creates = tx.contractAddress;
22392 }
22393 let item = this.formatter.transactionResponse(tx);
22394 if (tx.timeStamp) {
22395 item.timestamp = parseInt(tx.timeStamp);
22396 }
22397 output.push(item);
22398 });
22399 return output;
22400 });
22401 });
22402 }
22403}
22404
22405"use strict";
22406var __awaiter$c = (window && window.__awaiter) || function (thisArg, _arguments, P, generator) {
22407 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
22408 return new (P || (P = Promise))(function (resolve, reject) {
22409 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
22410 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22411 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22412 step((generator = generator.apply(thisArg, _arguments || [])).next());
22413 });
22414};
22415const logger$y = new Logger(version$m);
22416function now() { return (new Date()).getTime(); }
22417// Returns to network as long as all agree, or null if any is null.
22418// Throws an error if any two networks do not match.
22419function checkNetworks(networks) {
22420 let result = null;
22421 for (let i = 0; i < networks.length; i++) {
22422 const network = networks[i];
22423 // Null! We do not know our network; bail.
22424 if (network == null) {
22425 return null;
22426 }
22427 if (result) {
22428 // Make sure the network matches the previous networks
22429 if (!(result.name === network.name && result.chainId === network.chainId &&
22430 ((result.ensAddress === network.ensAddress) || (result.ensAddress == null && network.ensAddress == null)))) {
22431 logger$y.throwArgumentError("provider mismatch", "networks", networks);
22432 }
22433 }
22434 else {
22435 result = network;
22436 }
22437 }
22438 return result;
22439}
22440function median(values, maxDelta) {
22441 values = values.slice().sort();
22442 const middle = Math.floor(values.length / 2);
22443 // Odd length; take the middle
22444 if (values.length % 2) {
22445 return values[middle];
22446 }
22447 // Even length; take the average of the two middle
22448 const a = values[middle - 1], b = values[middle];
22449 if (maxDelta != null && Math.abs(a - b) > maxDelta) {
22450 return null;
22451 }
22452 return (a + b) / 2;
22453}
22454function serialize$1(value) {
22455 if (value === null) {
22456 return "null";
22457 }
22458 else if (typeof (value) === "number" || typeof (value) === "boolean") {
22459 return JSON.stringify(value);
22460 }
22461 else if (typeof (value) === "string") {
22462 return value;
22463 }
22464 else if (BigNumber.isBigNumber(value)) {
22465 return value.toString();
22466 }
22467 else if (Array.isArray(value)) {
22468 return JSON.stringify(value.map((i) => serialize$1(i)));
22469 }
22470 else if (typeof (value) === "object") {
22471 const keys = Object.keys(value);
22472 keys.sort();
22473 return "{" + keys.map((key) => {
22474 let v = value[key];
22475 if (typeof (v) === "function") {
22476 v = "[function]";
22477 }
22478 else {
22479 v = serialize$1(v);
22480 }
22481 return JSON.stringify(key) + ":" + v;
22482 }).join(",") + "}";
22483 }
22484 throw new Error("unknown value type: " + typeof (value));
22485}
22486// Next request ID to use for emitting debug info
22487let nextRid = 1;
22488;
22489function stall$1(duration) {
22490 let cancel = null;
22491 let timer = null;
22492 let promise = (new Promise((resolve) => {
22493 cancel = function () {
22494 if (timer) {
22495 clearTimeout(timer);
22496 timer = null;
22497 }
22498 resolve();
22499 };
22500 timer = setTimeout(cancel, duration);
22501 }));
22502 const wait = (func) => {
22503 promise = promise.then(func);
22504 return promise;
22505 };
22506 function getPromise() {
22507 return promise;
22508 }
22509 return { cancel, getPromise, wait };
22510}
22511;
22512function exposeDebugConfig(config, now) {
22513 const result = {
22514 provider: config.provider,
22515 weight: config.weight
22516 };
22517 if (config.start) {
22518 result.start = config.start;
22519 }
22520 if (now) {
22521 result.duration = (now - config.start);
22522 }
22523 if (config.done) {
22524 if (config.error) {
22525 result.error = config.error;
22526 }
22527 else {
22528 result.result = config.result || null;
22529 }
22530 }
22531 return result;
22532}
22533function normalizedTally(normalize, quorum) {
22534 return function (configs) {
22535 // Count the votes for each result
22536 const tally = {};
22537 configs.forEach((c) => {
22538 const value = normalize(c.result);
22539 if (!tally[value]) {
22540 tally[value] = { count: 0, result: c.result };
22541 }
22542 tally[value].count++;
22543 });
22544 // Check for a quorum on any given result
22545 const keys = Object.keys(tally);
22546 for (let i = 0; i < keys.length; i++) {
22547 const check = tally[keys[i]];
22548 if (check.count >= quorum) {
22549 return check.result;
22550 }
22551 }
22552 // No quroum
22553 return undefined;
22554 };
22555}
22556function getProcessFunc(provider, method, params) {
22557 let normalize = serialize$1;
22558 switch (method) {
22559 case "getBlockNumber":
22560 // Return the median value, unless there is (median + 1) is also
22561 // present, in which case that is probably true and the median
22562 // is going to be stale soon. In the event of a malicious node,
22563 // the lie will be true soon enough.
22564 return function (configs) {
22565 const values = configs.map((c) => c.result);
22566 // Get the median block number
22567 let blockNumber = median(configs.map((c) => c.result), 2);
22568 if (blockNumber == null) {
22569 return undefined;
22570 }
22571 blockNumber = Math.ceil(blockNumber);
22572 // If the next block height is present, its prolly safe to use
22573 if (values.indexOf(blockNumber + 1) >= 0) {
22574 blockNumber++;
22575 }
22576 // Don't ever roll back the blockNumber
22577 if (blockNumber >= provider._highestBlockNumber) {
22578 provider._highestBlockNumber = blockNumber;
22579 }
22580 return provider._highestBlockNumber;
22581 };
22582 case "getGasPrice":
22583 // Return the middle (round index up) value, similar to median
22584 // but do not average even entries and choose the higher.
22585 // Malicious actors must compromise 50% of the nodes to lie.
22586 return function (configs) {
22587 const values = configs.map((c) => c.result);
22588 values.sort();
22589 return values[Math.floor(values.length / 2)];
22590 };
22591 case "getEtherPrice":
22592 // Returns the median price. Malicious actors must compromise at
22593 // least 50% of the nodes to lie (in a meaningful way).
22594 return function (configs) {
22595 return median(configs.map((c) => c.result));
22596 };
22597 // No additional normalizing required; serialize is enough
22598 case "getBalance":
22599 case "getTransactionCount":
22600 case "getCode":
22601 case "getStorageAt":
22602 case "call":
22603 case "estimateGas":
22604 case "getLogs":
22605 break;
22606 // We drop the confirmations from transactions as it is approximate
22607 case "getTransaction":
22608 case "getTransactionReceipt":
22609 normalize = function (tx) {
22610 if (tx == null) {
22611 return null;
22612 }
22613 tx = shallowCopy(tx);
22614 tx.confirmations = -1;
22615 return serialize$1(tx);
22616 };
22617 break;
22618 // We drop the confirmations from transactions as it is approximate
22619 case "getBlock":
22620 // We drop the confirmations from transactions as it is approximate
22621 if (params.includeTransactions) {
22622 normalize = function (block) {
22623 if (block == null) {
22624 return null;
22625 }
22626 block = shallowCopy(block);
22627 block.transactions = block.transactions.map((tx) => {
22628 tx = shallowCopy(tx);
22629 tx.confirmations = -1;
22630 return tx;
22631 });
22632 return serialize$1(block);
22633 };
22634 }
22635 else {
22636 normalize = function (block) {
22637 if (block == null) {
22638 return null;
22639 }
22640 return serialize$1(block);
22641 };
22642 }
22643 break;
22644 default:
22645 throw new Error("unknown method: " + method);
22646 }
22647 // Return the result if and only if the expected quorum is
22648 // satisfied and agreed upon for the final result.
22649 return normalizedTally(normalize, provider.quorum);
22650}
22651// If we are doing a blockTag query, we need to make sure the backend is
22652// caught up to the FallbackProvider, before sending a request to it.
22653function waitForSync(config, blockNumber) {
22654 return __awaiter$c(this, void 0, void 0, function* () {
22655 const provider = (config.provider);
22656 if ((provider.blockNumber != null && provider.blockNumber >= blockNumber) || blockNumber === -1) {
22657 return provider;
22658 }
22659 return poll(() => {
22660 return new Promise((resolve, reject) => {
22661 setTimeout(function () {
22662 // We are synced
22663 if (provider.blockNumber >= blockNumber) {
22664 return resolve(provider);
22665 }
22666 // We're done; just quit
22667 if (config.cancelled) {
22668 return resolve(null);
22669 }
22670 // Try again, next block
22671 return resolve(undefined);
22672 }, 0);
22673 });
22674 }, { oncePoll: provider });
22675 });
22676}
22677function getRunner(config, currentBlockNumber, method, params) {
22678 return __awaiter$c(this, void 0, void 0, function* () {
22679 let provider = config.provider;
22680 switch (method) {
22681 case "getBlockNumber":
22682 case "getGasPrice":
22683 return provider[method]();
22684 case "getEtherPrice":
22685 if (provider.getEtherPrice) {
22686 return provider.getEtherPrice();
22687 }
22688 break;
22689 case "getBalance":
22690 case "getTransactionCount":
22691 case "getCode":
22692 if (params.blockTag && isHexString(params.blockTag)) {
22693 provider = yield waitForSync(config, currentBlockNumber);
22694 }
22695 return provider[method](params.address, params.blockTag || "latest");
22696 case "getStorageAt":
22697 if (params.blockTag && isHexString(params.blockTag)) {
22698 provider = yield waitForSync(config, currentBlockNumber);
22699 }
22700 return provider.getStorageAt(params.address, params.position, params.blockTag || "latest");
22701 case "getBlock":
22702 if (params.blockTag && isHexString(params.blockTag)) {
22703 provider = yield waitForSync(config, currentBlockNumber);
22704 }
22705 return provider[(params.includeTransactions ? "getBlockWithTransactions" : "getBlock")](params.blockTag || params.blockHash);
22706 case "call":
22707 case "estimateGas":
22708 if (params.blockTag && isHexString(params.blockTag)) {
22709 provider = yield waitForSync(config, currentBlockNumber);
22710 }
22711 return provider[method](params.transaction);
22712 case "getTransaction":
22713 case "getTransactionReceipt":
22714 return provider[method](params.transactionHash);
22715 case "getLogs": {
22716 let filter = params.filter;
22717 if ((filter.fromBlock && isHexString(filter.fromBlock)) || (filter.toBlock && isHexString(filter.toBlock))) {
22718 provider = yield waitForSync(config, currentBlockNumber);
22719 }
22720 return provider.getLogs(filter);
22721 }
22722 }
22723 return logger$y.throwError("unknown method error", Logger.errors.UNKNOWN_ERROR, {
22724 method: method,
22725 params: params
22726 });
22727 });
22728}
22729class FallbackProvider extends BaseProvider {
22730 constructor(providers, quorum) {
22731 logger$y.checkNew(new.target, FallbackProvider);
22732 if (providers.length === 0) {
22733 logger$y.throwArgumentError("missing providers", "providers", providers);
22734 }
22735 const providerConfigs = providers.map((configOrProvider, index) => {
22736 if (Provider.isProvider(configOrProvider)) {
22737 return Object.freeze({ provider: configOrProvider, weight: 1, stallTimeout: 750, priority: 1 });
22738 }
22739 const config = shallowCopy(configOrProvider);
22740 if (config.priority == null) {
22741 config.priority = 1;
22742 }
22743 if (config.stallTimeout == null) {
22744 config.stallTimeout = 750;
22745 }
22746 if (config.weight == null) {
22747 config.weight = 1;
22748 }
22749 const weight = config.weight;
22750 if (weight % 1 || weight > 512 || weight < 1) {
22751 logger$y.throwArgumentError("invalid weight; must be integer in [1, 512]", `providers[${index}].weight`, weight);
22752 }
22753 return Object.freeze(config);
22754 });
22755 const total = providerConfigs.reduce((accum, c) => (accum + c.weight), 0);
22756 if (quorum == null) {
22757 quorum = total / 2;
22758 }
22759 else if (quorum > total) {
22760 logger$y.throwArgumentError("quorum will always fail; larger than total weight", "quorum", quorum);
22761 }
22762 // Are all providers' networks are known
22763 let networkOrReady = checkNetworks(providerConfigs.map((c) => (c.provider).network));
22764 // Not all networks are known; we must stall
22765 if (networkOrReady == null) {
22766 networkOrReady = new Promise((resolve, reject) => {
22767 setTimeout(() => {
22768 this.detectNetwork().then(resolve, reject);
22769 }, 0);
22770 });
22771 }
22772 super(networkOrReady);
22773 // Preserve a copy, so we do not get mutated
22774 defineReadOnly(this, "providerConfigs", Object.freeze(providerConfigs));
22775 defineReadOnly(this, "quorum", quorum);
22776 this._highestBlockNumber = -1;
22777 }
22778 detectNetwork() {
22779 return __awaiter$c(this, void 0, void 0, function* () {
22780 const networks = yield Promise.all(this.providerConfigs.map((c) => c.provider.getNetwork()));
22781 return checkNetworks(networks);
22782 });
22783 }
22784 perform(method, params) {
22785 return __awaiter$c(this, void 0, void 0, function* () {
22786 // Sending transactions is special; always broadcast it to all backends
22787 if (method === "sendTransaction") {
22788 const results = yield Promise.all(this.providerConfigs.map((c) => {
22789 return c.provider.sendTransaction(params.signedTransaction).then((result) => {
22790 return result.hash;
22791 }, (error) => {
22792 return error;
22793 });
22794 }));
22795 // Any success is good enough (other errors are likely "already seen" errors
22796 for (let i = 0; i < results.length; i++) {
22797 const result = results[i];
22798 if (typeof (result) === "string") {
22799 return result;
22800 }
22801 }
22802 // They were all an error; pick the first error
22803 throw results[0];
22804 }
22805 // We need to make sure we are in sync with our backends, so we need
22806 // to know this before we can make a lot of calls
22807 if (this._highestBlockNumber === -1 && method !== "getBlockNumber") {
22808 yield this.getBlockNumber();
22809 }
22810 const processFunc = getProcessFunc(this, method, params);
22811 // Shuffle the providers and then sort them by their priority; we
22812 // shallowCopy them since we will store the result in them too
22813 const configs = shuffled(this.providerConfigs.map(shallowCopy));
22814 configs.sort((a, b) => (a.priority - b.priority));
22815 const currentBlockNumber = this._highestBlockNumber;
22816 let i = 0;
22817 let first = true;
22818 while (true) {
22819 const t0 = now();
22820 // Compute the inflight weight (exclude anything past)
22821 let inflightWeight = configs.filter((c) => (c.runner && ((t0 - c.start) < c.stallTimeout)))
22822 .reduce((accum, c) => (accum + c.weight), 0);
22823 // Start running enough to meet quorum
22824 while (inflightWeight < this.quorum && i < configs.length) {
22825 const config = configs[i++];
22826 const rid = nextRid++;
22827 config.start = now();
22828 config.staller = stall$1(config.stallTimeout);
22829 config.staller.wait(() => { config.staller = null; });
22830 config.runner = getRunner(config, currentBlockNumber, method, params).then((result) => {
22831 config.done = true;
22832 config.result = result;
22833 if (this.listenerCount("debug")) {
22834 this.emit("debug", {
22835 action: "request",
22836 rid: rid,
22837 backend: exposeDebugConfig(config, now()),
22838 request: { method: method, params: deepCopy(params) },
22839 provider: this
22840 });
22841 }
22842 }, (error) => {
22843 config.done = true;
22844 config.error = error;
22845 if (this.listenerCount("debug")) {
22846 this.emit("debug", {
22847 action: "request",
22848 rid: rid,
22849 backend: exposeDebugConfig(config, now()),
22850 request: { method: method, params: deepCopy(params) },
22851 provider: this
22852 });
22853 }
22854 });
22855 if (this.listenerCount("debug")) {
22856 this.emit("debug", {
22857 action: "request",
22858 rid: rid,
22859 backend: exposeDebugConfig(config, null),
22860 request: { method: method, params: deepCopy(params) },
22861 provider: this
22862 });
22863 }
22864 inflightWeight += config.weight;
22865 }
22866 // Wait for anything meaningful to finish or stall out
22867 const waiting = [];
22868 configs.forEach((c) => {
22869 if (c.done || !c.runner) {
22870 return;
22871 }
22872 waiting.push(c.runner);
22873 if (c.staller) {
22874 waiting.push(c.staller.getPromise());
22875 }
22876 });
22877 if (waiting.length) {
22878 yield Promise.race(waiting);
22879 }
22880 // Check the quorum and process the results; the process function
22881 // may additionally decide the quorum is not met
22882 const results = configs.filter((c) => (c.done && c.error == null));
22883 if (results.length >= this.quorum) {
22884 const result = processFunc(results);
22885 if (result !== undefined) {
22886 // Shut down any stallers
22887 configs.forEach(c => {
22888 if (c.staller) {
22889 c.staller.cancel();
22890 }
22891 c.cancelled = true;
22892 });
22893 return result;
22894 }
22895 if (!first) {
22896 yield stall$1(100).getPromise();
22897 }
22898 first = false;
22899 }
22900 // All configs have run to completion; we will never get more data
22901 if (configs.filter((c) => !c.done).length === 0) {
22902 break;
22903 }
22904 }
22905 // Shut down any stallers; shouldn't be any
22906 configs.forEach(c => {
22907 if (c.staller) {
22908 c.staller.cancel();
22909 }
22910 c.cancelled = true;
22911 });
22912 return logger$y.throwError("failed to meet quorum", Logger.errors.SERVER_ERROR, {
22913 method: method,
22914 params: params,
22915 //results: configs.map((c) => c.result),
22916 //errors: configs.map((c) => c.error),
22917 results: configs.map((c) => exposeDebugConfig(c)),
22918 provider: this
22919 });
22920 });
22921 }
22922}
22923
22924"use strict";
22925var IpcProvider = null;
22926
22927
22928var browserIpcProvider = {
22929 IpcProvider: IpcProvider
22930};
22931
22932"use strict";
22933const logger$z = new Logger(version$m);
22934const defaultProjectId = "84842078b09946638c03157f83405213";
22935class InfuraProvider extends UrlJsonRpcProvider {
22936 static getWebSocketProvider(network, apiKey) {
22937 const provider = new InfuraProvider(network, apiKey);
22938 const connection = provider.connection;
22939 if (connection.password) {
22940 logger$z.throwError("INFURA WebSocket project secrets unsupported", Logger.errors.UNSUPPORTED_OPERATION, {
22941 operation: "InfuraProvider.getWebSocketProvider()"
22942 });
22943 }
22944 const url = connection.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/");
22945 return new WebSocketProvider(url, network);
22946 }
22947 static getApiKey(apiKey) {
22948 const apiKeyObj = {
22949 apiKey: defaultProjectId,
22950 projectId: defaultProjectId,
22951 projectSecret: null
22952 };
22953 if (apiKey == null) {
22954 return apiKeyObj;
22955 }
22956 if (typeof (apiKey) === "string") {
22957 apiKeyObj.projectId = apiKey;
22958 }
22959 else if (apiKey.projectSecret != null) {
22960 logger$z.assertArgument((typeof (apiKey.projectId) === "string"), "projectSecret requires a projectId", "projectId", apiKey.projectId);
22961 logger$z.assertArgument((typeof (apiKey.projectSecret) === "string"), "invalid projectSecret", "projectSecret", "[REDACTED]");
22962 apiKeyObj.projectId = apiKey.projectId;
22963 apiKeyObj.projectSecret = apiKey.projectSecret;
22964 }
22965 else if (apiKey.projectId) {
22966 apiKeyObj.projectId = apiKey.projectId;
22967 }
22968 apiKeyObj.apiKey = apiKeyObj.projectId;
22969 return apiKeyObj;
22970 }
22971 static getUrl(network, apiKey) {
22972 let host = null;
22973 switch (network ? network.name : "unknown") {
22974 case "homestead":
22975 host = "mainnet.infura.io";
22976 break;
22977 case "ropsten":
22978 host = "ropsten.infura.io";
22979 break;
22980 case "rinkeby":
22981 host = "rinkeby.infura.io";
22982 break;
22983 case "kovan":
22984 host = "kovan.infura.io";
22985 break;
22986 case "goerli":
22987 host = "goerli.infura.io";
22988 break;
22989 default:
22990 logger$z.throwError("unsupported network", Logger.errors.INVALID_ARGUMENT, {
22991 argument: "network",
22992 value: network
22993 });
22994 }
22995 const connection = {
22996 url: ("https:/" + "/" + host + "/v3/" + apiKey.projectId),
22997 throttleCallback: (attempt, url) => {
22998 if (apiKey.projectId === defaultProjectId) {
22999 showThrottleMessage();
23000 }
23001 return Promise.resolve(true);
23002 }
23003 };
23004 if (apiKey.projectSecret != null) {
23005 connection.user = "";
23006 connection.password = apiKey.projectSecret;
23007 }
23008 return connection;
23009 }
23010}
23011
23012/* istanbul ignore file */
23013"use strict";
23014const logger$A = new Logger(version$m);
23015// Special API key provided by Nodesmith for ethers.js
23016const defaultApiKey$2 = "ETHERS_JS_SHARED";
23017class NodesmithProvider extends UrlJsonRpcProvider {
23018 static getApiKey(apiKey) {
23019 if (apiKey && typeof (apiKey) !== "string") {
23020 logger$A.throwArgumentError("invalid apiKey", "apiKey", apiKey);
23021 }
23022 return apiKey || defaultApiKey$2;
23023 }
23024 static getUrl(network, apiKey) {
23025 logger$A.warn("NodeSmith will be discontinued on 2019-12-20; please migrate to another platform.");
23026 let host = null;
23027 switch (network.name) {
23028 case "homestead":
23029 host = "https://ethereum.api.nodesmith.io/v1/mainnet/jsonrpc";
23030 break;
23031 case "ropsten":
23032 host = "https://ethereum.api.nodesmith.io/v1/ropsten/jsonrpc";
23033 break;
23034 case "rinkeby":
23035 host = "https://ethereum.api.nodesmith.io/v1/rinkeby/jsonrpc";
23036 break;
23037 case "goerli":
23038 host = "https://ethereum.api.nodesmith.io/v1/goerli/jsonrpc";
23039 break;
23040 case "kovan":
23041 host = "https://ethereum.api.nodesmith.io/v1/kovan/jsonrpc";
23042 break;
23043 default:
23044 logger$A.throwArgumentError("unsupported network", "network", arguments[0]);
23045 }
23046 return (host + "?apiKey=" + apiKey);
23047 }
23048}
23049
23050"use strict";
23051const logger$B = new Logger(version$m);
23052let _nextId = 1;
23053function buildWeb3LegacyFetcher(provider, sendFunc) {
23054 return function (method, params) {
23055 // Metamask complains about eth_sign (and on some versions hangs)
23056 if (method == "eth_sign" && provider.isMetaMask) {
23057 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
23058 method = "personal_sign";
23059 params = [params[1], params[0]];
23060 }
23061 const request = {
23062 method: method,
23063 params: params,
23064 id: (_nextId++),
23065 jsonrpc: "2.0"
23066 };
23067 return new Promise((resolve, reject) => {
23068 sendFunc(request, function (error, result) {
23069 if (error) {
23070 return reject(error);
23071 }
23072 if (result.error) {
23073 const error = new Error(result.error.message);
23074 error.code = result.error.code;
23075 error.data = result.error.data;
23076 return reject(error);
23077 }
23078 resolve(result.result);
23079 });
23080 });
23081 };
23082}
23083function buildEip1193Fetcher(provider) {
23084 return function (method, params) {
23085 if (params == null) {
23086 params = [];
23087 }
23088 // Metamask complains about eth_sign (and on some versions hangs)
23089 if (method == "eth_sign" && provider.isMetaMask) {
23090 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
23091 method = "personal_sign";
23092 params = [params[1], params[0]];
23093 }
23094 return provider.request({ method, params });
23095 };
23096}
23097class Web3Provider extends JsonRpcProvider {
23098 constructor(provider, network) {
23099 logger$B.checkNew(new.target, Web3Provider);
23100 if (provider == null) {
23101 logger$B.throwArgumentError("missing provider", "provider", provider);
23102 }
23103 let path = null;
23104 let jsonRpcFetchFunc = null;
23105 let subprovider = null;
23106 if (typeof (provider) === "function") {
23107 path = "unknown:";
23108 jsonRpcFetchFunc = provider;
23109 }
23110 else {
23111 path = provider.host || provider.path || "";
23112 if (!path && provider.isMetaMask) {
23113 path = "metamask";
23114 }
23115 subprovider = provider;
23116 if (provider.request) {
23117 if (path === "") {
23118 path = "eip-1193:";
23119 }
23120 jsonRpcFetchFunc = buildEip1193Fetcher(provider);
23121 }
23122 else if (provider.sendAsync) {
23123 jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.sendAsync.bind(provider));
23124 }
23125 else if (provider.send) {
23126 jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.send.bind(provider));
23127 }
23128 else {
23129 logger$B.throwArgumentError("unsupported provider", "provider", provider);
23130 }
23131 if (!path) {
23132 path = "unknown:";
23133 }
23134 }
23135 super(path, network);
23136 defineReadOnly(this, "jsonRpcFetchFunc", jsonRpcFetchFunc);
23137 defineReadOnly(this, "provider", subprovider);
23138 }
23139 send(method, params) {
23140 return this.jsonRpcFetchFunc(method, params);
23141 }
23142}
23143
23144"use strict";
23145const logger$C = new Logger(version$m);
23146////////////////////////
23147// Helper Functions
23148function getDefaultProvider(network, options) {
23149 if (network == null) {
23150 network = "homestead";
23151 }
23152 // If passed a URL, figure out the right type of provider based on the scheme
23153 if (typeof (network) === "string") {
23154 // @TODO: Add support for IpcProvider; maybe if it ends in ".ipc"?
23155 // Handle http and ws (and their secure variants)
23156 const match = network.match(/^(ws|http)s?:/i);
23157 if (match) {
23158 switch (match[1]) {
23159 case "http":
23160 return new JsonRpcProvider(network);
23161 case "ws":
23162 return new WebSocketProvider(network);
23163 default:
23164 logger$C.throwArgumentError("unsupported URL scheme", "network", network);
23165 }
23166 }
23167 }
23168 const n = getNetwork(network);
23169 if (!n || !n._defaultProvider) {
23170 logger$C.throwError("unsupported getDefaultProvider network", Logger.errors.NETWORK_ERROR, {
23171 operation: "getDefaultProvider",
23172 network: network
23173 });
23174 }
23175 return n._defaultProvider({
23176 FallbackProvider,
23177 AlchemyProvider,
23178 CloudflareProvider,
23179 EtherscanProvider,
23180 InfuraProvider,
23181 JsonRpcProvider,
23182 NodesmithProvider,
23183 Web3Provider,
23184 IpcProvider,
23185 }, options);
23186}
23187
23188var index$2 = /*#__PURE__*/Object.freeze({
23189 Provider: Provider,
23190 BaseProvider: BaseProvider,
23191 UrlJsonRpcProvider: UrlJsonRpcProvider,
23192 FallbackProvider: FallbackProvider,
23193 AlchemyProvider: AlchemyProvider,
23194 CloudflareProvider: CloudflareProvider,
23195 EtherscanProvider: EtherscanProvider,
23196 InfuraProvider: InfuraProvider,
23197 JsonRpcProvider: JsonRpcProvider,
23198 NodesmithProvider: NodesmithProvider,
23199 StaticJsonRpcProvider: StaticJsonRpcProvider,
23200 Web3Provider: Web3Provider,
23201 WebSocketProvider: WebSocketProvider,
23202 IpcProvider: IpcProvider,
23203 JsonRpcSigner: JsonRpcSigner,
23204 getDefaultProvider: getDefaultProvider,
23205 getNetwork: getNetwork,
23206 Formatter: Formatter
23207});
23208
23209"use strict";
23210const regexBytes = new RegExp("^bytes([0-9]+)$");
23211const regexNumber = new RegExp("^(u?int)([0-9]*)$");
23212const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$");
23213const Zeros$1 = "0000000000000000000000000000000000000000000000000000000000000000";
23214function _pack(type, value, isArray) {
23215 switch (type) {
23216 case "address":
23217 if (isArray) {
23218 return zeroPad(value, 32);
23219 }
23220 return arrayify(value);
23221 case "string":
23222 return toUtf8Bytes(value);
23223 case "bytes":
23224 return arrayify(value);
23225 case "bool":
23226 value = (value ? "0x01" : "0x00");
23227 if (isArray) {
23228 return zeroPad(value, 32);
23229 }
23230 return arrayify(value);
23231 }
23232 let match = type.match(regexNumber);
23233 if (match) {
23234 //let signed = (match[1] === "int")
23235 let size = parseInt(match[2] || "256");
23236 if ((match[2] && String(size) !== match[2]) || (size % 8 !== 0) || size === 0 || size > 256) {
23237 throw new Error("invalid number type - " + type);
23238 }
23239 if (isArray) {
23240 size = 256;
23241 }
23242 value = BigNumber.from(value).toTwos(size);
23243 return zeroPad(value, size / 8);
23244 }
23245 match = type.match(regexBytes);
23246 if (match) {
23247 const size = parseInt(match[1]);
23248 if (String(size) !== match[1] || size === 0 || size > 32) {
23249 throw new Error("invalid bytes type - " + type);
23250 }
23251 if (arrayify(value).byteLength !== size) {
23252 throw new Error("invalid value for " + type);
23253 }
23254 if (isArray) {
23255 return arrayify((value + Zeros$1).substring(0, 66));
23256 }
23257 return value;
23258 }
23259 match = type.match(regexArray);
23260 if (match && Array.isArray(value)) {
23261 const baseType = match[1];
23262 const count = parseInt(match[2] || String(value.length));
23263 if (count != value.length) {
23264 throw new Error("invalid value for " + type);
23265 }
23266 const result = [];
23267 value.forEach(function (value) {
23268 result.push(_pack(baseType, value, true));
23269 });
23270 return concat(result);
23271 }
23272 throw new Error("invalid type - " + type);
23273}
23274// @TODO: Array Enum
23275function pack$1(types, values) {
23276 if (types.length != values.length) {
23277 throw new Error("type/value count mismatch");
23278 }
23279 const tight = [];
23280 types.forEach(function (type, index) {
23281 tight.push(_pack(type, values[index]));
23282 });
23283 return hexlify(concat(tight));
23284}
23285function keccak256$1(types, values) {
23286 return keccak256(pack$1(types, values));
23287}
23288function sha256$1(types, values) {
23289 return browser_3(pack$1(types, values));
23290}
23291
23292const version$n = "units/5.0.2";
23293
23294"use strict";
23295const logger$D = new Logger(version$n);
23296const names = [
23297 "wei",
23298 "kwei",
23299 "mwei",
23300 "gwei",
23301 "szabo",
23302 "finney",
23303 "ether",
23304];
23305// Some environments have issues with RegEx that contain back-tracking, so we cannot
23306// use them.
23307function commify(value) {
23308 const comps = String(value).split(".");
23309 if (comps.length > 2 || !comps[0].match(/^-?[0-9]*$/) || (comps[1] && !comps[1].match(/^[0-9]*$/)) || value === "." || value === "-.") {
23310 logger$D.throwArgumentError("invalid value", "value", value);
23311 }
23312 // Make sure we have at least one whole digit (0 if none)
23313 let whole = comps[0];
23314 let negative = "";
23315 if (whole.substring(0, 1) === "-") {
23316 negative = "-";
23317 whole = whole.substring(1);
23318 }
23319 // Make sure we have at least 1 whole digit with no leading zeros
23320 while (whole.substring(0, 1) === "0") {
23321 whole = whole.substring(1);
23322 }
23323 if (whole === "") {
23324 whole = "0";
23325 }
23326 let suffix = "";
23327 if (comps.length === 2) {
23328 suffix = "." + (comps[1] || "0");
23329 }
23330 while (suffix.length > 2 && suffix[suffix.length - 1] === "0") {
23331 suffix = suffix.substring(0, suffix.length - 1);
23332 }
23333 const formatted = [];
23334 while (whole.length) {
23335 if (whole.length <= 3) {
23336 formatted.unshift(whole);
23337 break;
23338 }
23339 else {
23340 const index = whole.length - 3;
23341 formatted.unshift(whole.substring(index));
23342 whole = whole.substring(0, index);
23343 }
23344 }
23345 return negative + formatted.join(",") + suffix;
23346}
23347function formatUnits(value, unitName) {
23348 if (typeof (unitName) === "string") {
23349 const index = names.indexOf(unitName);
23350 if (index !== -1) {
23351 unitName = 3 * index;
23352 }
23353 }
23354 return formatFixed(value, (unitName != null) ? unitName : 18);
23355}
23356function parseUnits(value, unitName) {
23357 if (typeof (unitName) === "string") {
23358 const index = names.indexOf(unitName);
23359 if (index !== -1) {
23360 unitName = 3 * index;
23361 }
23362 }
23363 return parseFixed(value, (unitName != null) ? unitName : 18);
23364}
23365function formatEther(wei) {
23366 return formatUnits(wei, 18);
23367}
23368function parseEther(ether) {
23369 return parseUnits(ether, 18);
23370}
23371
23372"use strict";
23373
23374var utils$1 = /*#__PURE__*/Object.freeze({
23375 AbiCoder: AbiCoder,
23376 defaultAbiCoder: defaultAbiCoder,
23377 Fragment: Fragment,
23378 EventFragment: EventFragment,
23379 FunctionFragment: FunctionFragment,
23380 ParamType: ParamType,
23381 FormatTypes: FormatTypes,
23382 checkResultErrors: checkResultErrors,
23383 Logger: Logger,
23384 RLP: index,
23385 _fetchData: _fetchData,
23386 fetchJson: fetchJson,
23387 poll: poll,
23388 checkProperties: checkProperties,
23389 deepCopy: deepCopy,
23390 defineReadOnly: defineReadOnly,
23391 getStatic: getStatic,
23392 resolveProperties: resolveProperties,
23393 shallowCopy: shallowCopy,
23394 arrayify: arrayify,
23395 concat: concat,
23396 stripZeros: stripZeros,
23397 zeroPad: zeroPad,
23398 isBytes: isBytes,
23399 isBytesLike: isBytesLike,
23400 defaultPath: defaultPath,
23401 HDNode: HDNode,
23402 SigningKey: SigningKey,
23403 Interface: Interface,
23404 LogDescription: LogDescription,
23405 TransactionDescription: TransactionDescription,
23406 base58: Base58,
23407 base64: browser$2,
23408 hexlify: hexlify,
23409 isHexString: isHexString,
23410 hexStripZeros: hexStripZeros,
23411 hexValue: hexValue,
23412 hexZeroPad: hexZeroPad,
23413 hexDataLength: hexDataLength,
23414 hexDataSlice: hexDataSlice,
23415 nameprep: nameprep,
23416 _toEscapedUtf8String: _toEscapedUtf8String,
23417 toUtf8Bytes: toUtf8Bytes,
23418 toUtf8CodePoints: toUtf8CodePoints,
23419 toUtf8String: toUtf8String,
23420 Utf8ErrorFuncs: Utf8ErrorFuncs,
23421 formatBytes32String: formatBytes32String,
23422 parseBytes32String: parseBytes32String,
23423 hashMessage: hashMessage,
23424 namehash: namehash,
23425 isValidName: isValidName,
23426 id: id,
23427 getAddress: getAddress,
23428 getIcapAddress: getIcapAddress,
23429 getContractAddress: getContractAddress,
23430 getCreate2Address: getCreate2Address,
23431 isAddress: isAddress,
23432 formatEther: formatEther,
23433 parseEther: parseEther,
23434 formatUnits: formatUnits,
23435 parseUnits: parseUnits,
23436 commify: commify,
23437 computeHmac: browser_5,
23438 keccak256: keccak256,
23439 ripemd160: browser_2,
23440 sha256: browser_3,
23441 sha512: browser_4,
23442 randomBytes: randomBytes,
23443 shuffled: shuffled,
23444 solidityPack: pack$1,
23445 solidityKeccak256: keccak256$1,
23446 soliditySha256: sha256$1,
23447 splitSignature: splitSignature,
23448 joinSignature: joinSignature,
23449 parseTransaction: parse,
23450 serializeTransaction: serialize,
23451 getJsonWalletAddress: getJsonWalletAddress,
23452 computeAddress: computeAddress,
23453 recoverAddress: recoverAddress,
23454 computePublicKey: computePublicKey,
23455 recoverPublicKey: recoverPublicKey,
23456 verifyMessage: verifyMessage,
23457 mnemonicToEntropy: mnemonicToEntropy,
23458 entropyToMnemonic: entropyToMnemonic,
23459 isValidMnemonic: isValidMnemonic,
23460 mnemonicToSeed: mnemonicToSeed,
23461 SupportedAlgorithm: browser_1,
23462 get UnicodeNormalizationForm () { return UnicodeNormalizationForm; },
23463 get Utf8ErrorReason () { return Utf8ErrorReason; },
23464 Indexed: Indexed
23465});
23466
23467const version$o = "ethers/5.0.8";
23468
23469"use strict";
23470const logger$E = new Logger(version$o);
23471
23472var ethers = /*#__PURE__*/Object.freeze({
23473 Signer: Signer,
23474 Wallet: Wallet,
23475 VoidSigner: VoidSigner,
23476 getDefaultProvider: getDefaultProvider,
23477 providers: index$2,
23478 Contract: Contract,
23479 ContractFactory: ContractFactory,
23480 BigNumber: BigNumber,
23481 FixedNumber: FixedNumber,
23482 constants: index$1,
23483 get errors () { return ErrorCode; },
23484 logger: logger$E,
23485 utils: utils$1,
23486 wordlists: wordlists,
23487 version: version$o,
23488 Wordlist: Wordlist
23489});
23490
23491"use strict";
23492try {
23493 const anyGlobal = window;
23494 if (anyGlobal._ethers == null) {
23495 anyGlobal._ethers = ethers;
23496 }
23497}
23498catch (error) { }
23499
23500export { BigNumber, Contract, ContractFactory, FixedNumber, Signer, VoidSigner, Wallet, Wordlist, index$1 as constants, ErrorCode as errors, ethers, getDefaultProvider, logger$E as logger, index$2 as providers, utils$1 as utils, version$o as version, wordlists };