UNPKG

284 kBJavaScriptView Raw
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bchaddr = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2// base-x encoding
3// Forked from https://github.com/cryptocoinjs/bs58
4// Originally written by Mike Hearn for BitcoinJ
5// Copyright (c) 2011 Google Inc
6// Ported to JavaScript by Stefan Thomas
7// Merged Buffer refactorings from base58-native by Stephen Pair
8// Copyright (c) 2013 BitPay Inc
9
10var Buffer = require('safe-buffer').Buffer
11
12module.exports = function base (ALPHABET) {
13 var ALPHABET_MAP = {}
14 var BASE = ALPHABET.length
15 var LEADER = ALPHABET.charAt(0)
16
17 // pre-compute lookup table
18 for (var z = 0; z < ALPHABET.length; z++) {
19 var x = ALPHABET.charAt(z)
20
21 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
22 ALPHABET_MAP[x] = z
23 }
24
25 function encode (source) {
26 if (source.length === 0) return ''
27
28 var digits = [0]
29 for (var i = 0; i < source.length; ++i) {
30 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
31 carry += digits[j] << 8
32 digits[j] = carry % BASE
33 carry = (carry / BASE) | 0
34 }
35
36 while (carry > 0) {
37 digits.push(carry % BASE)
38 carry = (carry / BASE) | 0
39 }
40 }
41
42 var string = ''
43
44 // deal with leading zeros
45 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
46 // convert digits to a string
47 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
48
49 return string
50 }
51
52 function decodeUnsafe (string) {
53 if (typeof string !== 'string') throw new TypeError('Expected String')
54 if (string.length === 0) return Buffer.allocUnsafe(0)
55
56 var bytes = [0]
57 for (var i = 0; i < string.length; i++) {
58 var value = ALPHABET_MAP[string[i]]
59 if (value === undefined) return
60
61 for (var j = 0, carry = value; j < bytes.length; ++j) {
62 carry += bytes[j] * BASE
63 bytes[j] = carry & 0xff
64 carry >>= 8
65 }
66
67 while (carry > 0) {
68 bytes.push(carry & 0xff)
69 carry >>= 8
70 }
71 }
72
73 // deal with leading zeros
74 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
75 bytes.push(0)
76 }
77
78 return Buffer.from(bytes.reverse())
79 }
80
81 function decode (string) {
82 var buffer = decodeUnsafe(string)
83 if (buffer) return buffer
84
85 throw new Error('Non-base' + BASE + ' character')
86 }
87
88 return {
89 encode: encode,
90 decodeUnsafe: decodeUnsafe,
91 decode: decode
92 }
93}
94
95},{"safe-buffer":41}],2:[function(require,module,exports){
96'use strict'
97
98exports.byteLength = byteLength
99exports.toByteArray = toByteArray
100exports.fromByteArray = fromByteArray
101
102var lookup = []
103var revLookup = []
104var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
105
106var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
107for (var i = 0, len = code.length; i < len; ++i) {
108 lookup[i] = code[i]
109 revLookup[code.charCodeAt(i)] = i
110}
111
112revLookup['-'.charCodeAt(0)] = 62
113revLookup['_'.charCodeAt(0)] = 63
114
115function placeHoldersCount (b64) {
116 var len = b64.length
117 if (len % 4 > 0) {
118 throw new Error('Invalid string. Length must be a multiple of 4')
119 }
120
121 // the number of equal signs (place holders)
122 // if there are two placeholders, than the two characters before it
123 // represent one byte
124 // if there is only one, then the three characters before it represent 2 bytes
125 // this is just a cheap hack to not do indexOf twice
126 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
127}
128
129function byteLength (b64) {
130 // base64 is 4/3 + up to two characters of the original data
131 return (b64.length * 3 / 4) - placeHoldersCount(b64)
132}
133
134function toByteArray (b64) {
135 var i, l, tmp, placeHolders, arr
136 var len = b64.length
137 placeHolders = placeHoldersCount(b64)
138
139 arr = new Arr((len * 3 / 4) - placeHolders)
140
141 // if there are placeholders, only get up to the last complete 4 chars
142 l = placeHolders > 0 ? len - 4 : len
143
144 var L = 0
145
146 for (i = 0; i < l; i += 4) {
147 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
148 arr[L++] = (tmp >> 16) & 0xFF
149 arr[L++] = (tmp >> 8) & 0xFF
150 arr[L++] = tmp & 0xFF
151 }
152
153 if (placeHolders === 2) {
154 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
155 arr[L++] = tmp & 0xFF
156 } else if (placeHolders === 1) {
157 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
158 arr[L++] = (tmp >> 8) & 0xFF
159 arr[L++] = tmp & 0xFF
160 }
161
162 return arr
163}
164
165function tripletToBase64 (num) {
166 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
167}
168
169function encodeChunk (uint8, start, end) {
170 var tmp
171 var output = []
172 for (var i = start; i < end; i += 3) {
173 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
174 output.push(tripletToBase64(tmp))
175 }
176 return output.join('')
177}
178
179function fromByteArray (uint8) {
180 var tmp
181 var len = uint8.length
182 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
183 var output = ''
184 var parts = []
185 var maxChunkLength = 16383 // must be multiple of 3
186
187 // go through the array every three bytes, we'll deal with trailing stuff later
188 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
189 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
190 }
191
192 // pad the end with zeros, but make sure to not forget the extra bytes
193 if (extraBytes === 1) {
194 tmp = uint8[len - 1]
195 output += lookup[tmp >> 2]
196 output += lookup[(tmp << 4) & 0x3F]
197 output += '=='
198 } else if (extraBytes === 2) {
199 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
200 output += lookup[tmp >> 10]
201 output += lookup[(tmp >> 4) & 0x3F]
202 output += lookup[(tmp << 2) & 0x3F]
203 output += '='
204 }
205
206 parts.push(output)
207
208 return parts.join('')
209}
210
211},{}],3:[function(require,module,exports){
212var bigInt = (function (undefined) {
213 "use strict";
214
215 var BASE = 1e7,
216 LOG_BASE = 7,
217 MAX_INT = 9007199254740992,
218 MAX_INT_ARR = smallToArray(MAX_INT),
219 LOG_MAX_INT = Math.log(MAX_INT);
220
221 function Integer(v, radix) {
222 if (typeof v === "undefined") return Integer[0];
223 if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix);
224 return parseValue(v);
225 }
226
227 function BigInteger(value, sign) {
228 this.value = value;
229 this.sign = sign;
230 this.isSmall = false;
231 }
232 BigInteger.prototype = Object.create(Integer.prototype);
233
234 function SmallInteger(value) {
235 this.value = value;
236 this.sign = value < 0;
237 this.isSmall = true;
238 }
239 SmallInteger.prototype = Object.create(Integer.prototype);
240
241 function isPrecise(n) {
242 return -MAX_INT < n && n < MAX_INT;
243 }
244
245 function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
246 if (n < 1e7)
247 return [n];
248 if (n < 1e14)
249 return [n % 1e7, Math.floor(n / 1e7)];
250 return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
251 }
252
253 function arrayToSmall(arr) { // If BASE changes this function may need to change
254 trim(arr);
255 var length = arr.length;
256 if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
257 switch (length) {
258 case 0: return 0;
259 case 1: return arr[0];
260 case 2: return arr[0] + arr[1] * BASE;
261 default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
262 }
263 }
264 return arr;
265 }
266
267 function trim(v) {
268 var i = v.length;
269 while (v[--i] === 0);
270 v.length = i + 1;
271 }
272
273 function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
274 var x = new Array(length);
275 var i = -1;
276 while (++i < length) {
277 x[i] = 0;
278 }
279 return x;
280 }
281
282 function truncate(n) {
283 if (n > 0) return Math.floor(n);
284 return Math.ceil(n);
285 }
286
287 function add(a, b) { // assumes a and b are arrays with a.length >= b.length
288 var l_a = a.length,
289 l_b = b.length,
290 r = new Array(l_a),
291 carry = 0,
292 base = BASE,
293 sum, i;
294 for (i = 0; i < l_b; i++) {
295 sum = a[i] + b[i] + carry;
296 carry = sum >= base ? 1 : 0;
297 r[i] = sum - carry * base;
298 }
299 while (i < l_a) {
300 sum = a[i] + carry;
301 carry = sum === base ? 1 : 0;
302 r[i++] = sum - carry * base;
303 }
304 if (carry > 0) r.push(carry);
305 return r;
306 }
307
308 function addAny(a, b) {
309 if (a.length >= b.length) return add(a, b);
310 return add(b, a);
311 }
312
313 function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
314 var l = a.length,
315 r = new Array(l),
316 base = BASE,
317 sum, i;
318 for (i = 0; i < l; i++) {
319 sum = a[i] - base + carry;
320 carry = Math.floor(sum / base);
321 r[i] = sum - carry * base;
322 carry += 1;
323 }
324 while (carry > 0) {
325 r[i++] = carry % base;
326 carry = Math.floor(carry / base);
327 }
328 return r;
329 }
330
331 BigInteger.prototype.add = function (v) {
332 var n = parseValue(v);
333 if (this.sign !== n.sign) {
334 return this.subtract(n.negate());
335 }
336 var a = this.value, b = n.value;
337 if (n.isSmall) {
338 return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
339 }
340 return new BigInteger(addAny(a, b), this.sign);
341 };
342 BigInteger.prototype.plus = BigInteger.prototype.add;
343
344 SmallInteger.prototype.add = function (v) {
345 var n = parseValue(v);
346 var a = this.value;
347 if (a < 0 !== n.sign) {
348 return this.subtract(n.negate());
349 }
350 var b = n.value;
351 if (n.isSmall) {
352 if (isPrecise(a + b)) return new SmallInteger(a + b);
353 b = smallToArray(Math.abs(b));
354 }
355 return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
356 };
357 SmallInteger.prototype.plus = SmallInteger.prototype.add;
358
359 function subtract(a, b) { // assumes a and b are arrays with a >= b
360 var a_l = a.length,
361 b_l = b.length,
362 r = new Array(a_l),
363 borrow = 0,
364 base = BASE,
365 i, difference;
366 for (i = 0; i < b_l; i++) {
367 difference = a[i] - borrow - b[i];
368 if (difference < 0) {
369 difference += base;
370 borrow = 1;
371 } else borrow = 0;
372 r[i] = difference;
373 }
374 for (i = b_l; i < a_l; i++) {
375 difference = a[i] - borrow;
376 if (difference < 0) difference += base;
377 else {
378 r[i++] = difference;
379 break;
380 }
381 r[i] = difference;
382 }
383 for (; i < a_l; i++) {
384 r[i] = a[i];
385 }
386 trim(r);
387 return r;
388 }
389
390 function subtractAny(a, b, sign) {
391 var value;
392 if (compareAbs(a, b) >= 0) {
393 value = subtract(a, b);
394 } else {
395 value = subtract(b, a);
396 sign = !sign;
397 }
398 value = arrayToSmall(value);
399 if (typeof value === "number") {
400 if (sign) value = -value;
401 return new SmallInteger(value);
402 }
403 return new BigInteger(value, sign);
404 }
405
406 function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
407 var l = a.length,
408 r = new Array(l),
409 carry = -b,
410 base = BASE,
411 i, difference;
412 for (i = 0; i < l; i++) {
413 difference = a[i] + carry;
414 carry = Math.floor(difference / base);
415 difference %= base;
416 r[i] = difference < 0 ? difference + base : difference;
417 }
418 r = arrayToSmall(r);
419 if (typeof r === "number") {
420 if (sign) r = -r;
421 return new SmallInteger(r);
422 } return new BigInteger(r, sign);
423 }
424
425 BigInteger.prototype.subtract = function (v) {
426 var n = parseValue(v);
427 if (this.sign !== n.sign) {
428 return this.add(n.negate());
429 }
430 var a = this.value, b = n.value;
431 if (n.isSmall)
432 return subtractSmall(a, Math.abs(b), this.sign);
433 return subtractAny(a, b, this.sign);
434 };
435 BigInteger.prototype.minus = BigInteger.prototype.subtract;
436
437 SmallInteger.prototype.subtract = function (v) {
438 var n = parseValue(v);
439 var a = this.value;
440 if (a < 0 !== n.sign) {
441 return this.add(n.negate());
442 }
443 var b = n.value;
444 if (n.isSmall) {
445 return new SmallInteger(a - b);
446 }
447 return subtractSmall(b, Math.abs(a), a >= 0);
448 };
449 SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
450
451 BigInteger.prototype.negate = function () {
452 return new BigInteger(this.value, !this.sign);
453 };
454 SmallInteger.prototype.negate = function () {
455 var sign = this.sign;
456 var small = new SmallInteger(-this.value);
457 small.sign = !sign;
458 return small;
459 };
460
461 BigInteger.prototype.abs = function () {
462 return new BigInteger(this.value, false);
463 };
464 SmallInteger.prototype.abs = function () {
465 return new SmallInteger(Math.abs(this.value));
466 };
467
468 function multiplyLong(a, b) {
469 var a_l = a.length,
470 b_l = b.length,
471 l = a_l + b_l,
472 r = createArray(l),
473 base = BASE,
474 product, carry, i, a_i, b_j;
475 for (i = 0; i < a_l; ++i) {
476 a_i = a[i];
477 for (var j = 0; j < b_l; ++j) {
478 b_j = b[j];
479 product = a_i * b_j + r[i + j];
480 carry = Math.floor(product / base);
481 r[i + j] = product - carry * base;
482 r[i + j + 1] += carry;
483 }
484 }
485 trim(r);
486 return r;
487 }
488
489 function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
490 var l = a.length,
491 r = new Array(l),
492 base = BASE,
493 carry = 0,
494 product, i;
495 for (i = 0; i < l; i++) {
496 product = a[i] * b + carry;
497 carry = Math.floor(product / base);
498 r[i] = product - carry * base;
499 }
500 while (carry > 0) {
501 r[i++] = carry % base;
502 carry = Math.floor(carry / base);
503 }
504 return r;
505 }
506
507 function shiftLeft(x, n) {
508 var r = [];
509 while (n-- > 0) r.push(0);
510 return r.concat(x);
511 }
512
513 function multiplyKaratsuba(x, y) {
514 var n = Math.max(x.length, y.length);
515
516 if (n <= 30) return multiplyLong(x, y);
517 n = Math.ceil(n / 2);
518
519 var b = x.slice(n),
520 a = x.slice(0, n),
521 d = y.slice(n),
522 c = y.slice(0, n);
523
524 var ac = multiplyKaratsuba(a, c),
525 bd = multiplyKaratsuba(b, d),
526 abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
527
528 var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
529 trim(product);
530 return product;
531 }
532
533 // The following function is derived from a surface fit of a graph plotting the performance difference
534 // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
535 function useKaratsuba(l1, l2) {
536 return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
537 }
538
539 BigInteger.prototype.multiply = function (v) {
540 var n = parseValue(v),
541 a = this.value, b = n.value,
542 sign = this.sign !== n.sign,
543 abs;
544 if (n.isSmall) {
545 if (b === 0) return Integer[0];
546 if (b === 1) return this;
547 if (b === -1) return this.negate();
548 abs = Math.abs(b);
549 if (abs < BASE) {
550 return new BigInteger(multiplySmall(a, abs), sign);
551 }
552 b = smallToArray(abs);
553 }
554 if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
555 return new BigInteger(multiplyKaratsuba(a, b), sign);
556 return new BigInteger(multiplyLong(a, b), sign);
557 };
558
559 BigInteger.prototype.times = BigInteger.prototype.multiply;
560
561 function multiplySmallAndArray(a, b, sign) { // a >= 0
562 if (a < BASE) {
563 return new BigInteger(multiplySmall(b, a), sign);
564 }
565 return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
566 }
567 SmallInteger.prototype._multiplyBySmall = function (a) {
568 if (isPrecise(a.value * this.value)) {
569 return new SmallInteger(a.value * this.value);
570 }
571 return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
572 };
573 BigInteger.prototype._multiplyBySmall = function (a) {
574 if (a.value === 0) return Integer[0];
575 if (a.value === 1) return this;
576 if (a.value === -1) return this.negate();
577 return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
578 };
579 SmallInteger.prototype.multiply = function (v) {
580 return parseValue(v)._multiplyBySmall(this);
581 };
582 SmallInteger.prototype.times = SmallInteger.prototype.multiply;
583
584 function square(a) {
585 //console.assert(2 * BASE * BASE < MAX_INT);
586 var l = a.length,
587 r = createArray(l + l),
588 base = BASE,
589 product, carry, i, a_i, a_j;
590 for (i = 0; i < l; i++) {
591 a_i = a[i];
592 carry = 0 - a_i * a_i;
593 for (var j = i; j < l; j++) {
594 a_j = a[j];
595 product = 2 * (a_i * a_j) + r[i + j] + carry;
596 carry = Math.floor(product / base);
597 r[i + j] = product - carry * base;
598 }
599 r[i + l] = carry;
600 }
601 trim(r);
602 return r;
603 }
604
605 BigInteger.prototype.square = function () {
606 return new BigInteger(square(this.value), false);
607 };
608
609 SmallInteger.prototype.square = function () {
610 var value = this.value * this.value;
611 if (isPrecise(value)) return new SmallInteger(value);
612 return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
613 };
614
615 function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
616 var a_l = a.length,
617 b_l = b.length,
618 base = BASE,
619 result = createArray(b.length),
620 divisorMostSignificantDigit = b[b_l - 1],
621 // normalization
622 lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
623 remainder = multiplySmall(a, lambda),
624 divisor = multiplySmall(b, lambda),
625 quotientDigit, shift, carry, borrow, i, l, q;
626 if (remainder.length <= a_l) remainder.push(0);
627 divisor.push(0);
628 divisorMostSignificantDigit = divisor[b_l - 1];
629 for (shift = a_l - b_l; shift >= 0; shift--) {
630 quotientDigit = base - 1;
631 if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
632 quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
633 }
634 // quotientDigit <= base - 1
635 carry = 0;
636 borrow = 0;
637 l = divisor.length;
638 for (i = 0; i < l; i++) {
639 carry += quotientDigit * divisor[i];
640 q = Math.floor(carry / base);
641 borrow += remainder[shift + i] - (carry - q * base);
642 carry = q;
643 if (borrow < 0) {
644 remainder[shift + i] = borrow + base;
645 borrow = -1;
646 } else {
647 remainder[shift + i] = borrow;
648 borrow = 0;
649 }
650 }
651 while (borrow !== 0) {
652 quotientDigit -= 1;
653 carry = 0;
654 for (i = 0; i < l; i++) {
655 carry += remainder[shift + i] - base + divisor[i];
656 if (carry < 0) {
657 remainder[shift + i] = carry + base;
658 carry = 0;
659 } else {
660 remainder[shift + i] = carry;
661 carry = 1;
662 }
663 }
664 borrow += carry;
665 }
666 result[shift] = quotientDigit;
667 }
668 // denormalization
669 remainder = divModSmall(remainder, lambda)[0];
670 return [arrayToSmall(result), arrayToSmall(remainder)];
671 }
672
673 function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
674 // Performs faster than divMod1 on larger input sizes.
675 var a_l = a.length,
676 b_l = b.length,
677 result = [],
678 part = [],
679 base = BASE,
680 guess, xlen, highx, highy, check;
681 while (a_l) {
682 part.unshift(a[--a_l]);
683 trim(part);
684 if (compareAbs(part, b) < 0) {
685 result.push(0);
686 continue;
687 }
688 xlen = part.length;
689 highx = part[xlen - 1] * base + part[xlen - 2];
690 highy = b[b_l - 1] * base + b[b_l - 2];
691 if (xlen > b_l) {
692 highx = (highx + 1) * base;
693 }
694 guess = Math.ceil(highx / highy);
695 do {
696 check = multiplySmall(b, guess);
697 if (compareAbs(check, part) <= 0) break;
698 guess--;
699 } while (guess);
700 result.push(guess);
701 part = subtract(part, check);
702 }
703 result.reverse();
704 return [arrayToSmall(result), arrayToSmall(part)];
705 }
706
707 function divModSmall(value, lambda) {
708 var length = value.length,
709 quotient = createArray(length),
710 base = BASE,
711 i, q, remainder, divisor;
712 remainder = 0;
713 for (i = length - 1; i >= 0; --i) {
714 divisor = remainder * base + value[i];
715 q = truncate(divisor / lambda);
716 remainder = divisor - q * lambda;
717 quotient[i] = q | 0;
718 }
719 return [quotient, remainder | 0];
720 }
721
722 function divModAny(self, v) {
723 var value, n = parseValue(v);
724 var a = self.value, b = n.value;
725 var quotient;
726 if (b === 0) throw new Error("Cannot divide by zero");
727 if (self.isSmall) {
728 if (n.isSmall) {
729 return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
730 }
731 return [Integer[0], self];
732 }
733 if (n.isSmall) {
734 if (b === 1) return [self, Integer[0]];
735 if (b == -1) return [self.negate(), Integer[0]];
736 var abs = Math.abs(b);
737 if (abs < BASE) {
738 value = divModSmall(a, abs);
739 quotient = arrayToSmall(value[0]);
740 var remainder = value[1];
741 if (self.sign) remainder = -remainder;
742 if (typeof quotient === "number") {
743 if (self.sign !== n.sign) quotient = -quotient;
744 return [new SmallInteger(quotient), new SmallInteger(remainder)];
745 }
746 return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
747 }
748 b = smallToArray(abs);
749 }
750 var comparison = compareAbs(a, b);
751 if (comparison === -1) return [Integer[0], self];
752 if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
753
754 // divMod1 is faster on smaller input sizes
755 if (a.length + b.length <= 200)
756 value = divMod1(a, b);
757 else value = divMod2(a, b);
758
759 quotient = value[0];
760 var qSign = self.sign !== n.sign,
761 mod = value[1],
762 mSign = self.sign;
763 if (typeof quotient === "number") {
764 if (qSign) quotient = -quotient;
765 quotient = new SmallInteger(quotient);
766 } else quotient = new BigInteger(quotient, qSign);
767 if (typeof mod === "number") {
768 if (mSign) mod = -mod;
769 mod = new SmallInteger(mod);
770 } else mod = new BigInteger(mod, mSign);
771 return [quotient, mod];
772 }
773
774 BigInteger.prototype.divmod = function (v) {
775 var result = divModAny(this, v);
776 return {
777 quotient: result[0],
778 remainder: result[1]
779 };
780 };
781 SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
782
783 BigInteger.prototype.divide = function (v) {
784 return divModAny(this, v)[0];
785 };
786 SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
787
788 BigInteger.prototype.mod = function (v) {
789 return divModAny(this, v)[1];
790 };
791 SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
792
793 BigInteger.prototype.pow = function (v) {
794 var n = parseValue(v),
795 a = this.value,
796 b = n.value,
797 value, x, y;
798 if (b === 0) return Integer[1];
799 if (a === 0) return Integer[0];
800 if (a === 1) return Integer[1];
801 if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
802 if (n.sign) {
803 return Integer[0];
804 }
805 if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
806 if (this.isSmall) {
807 if (isPrecise(value = Math.pow(a, b)))
808 return new SmallInteger(truncate(value));
809 }
810 x = this;
811 y = Integer[1];
812 while (true) {
813 if (b & 1 === 1) {
814 y = y.times(x);
815 --b;
816 }
817 if (b === 0) break;
818 b /= 2;
819 x = x.square();
820 }
821 return y;
822 };
823 SmallInteger.prototype.pow = BigInteger.prototype.pow;
824
825 BigInteger.prototype.modPow = function (exp, mod) {
826 exp = parseValue(exp);
827 mod = parseValue(mod);
828 if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
829 var r = Integer[1],
830 base = this.mod(mod);
831 while (exp.isPositive()) {
832 if (base.isZero()) return Integer[0];
833 if (exp.isOdd()) r = r.multiply(base).mod(mod);
834 exp = exp.divide(2);
835 base = base.square().mod(mod);
836 }
837 return r;
838 };
839 SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
840
841 function compareAbs(a, b) {
842 if (a.length !== b.length) {
843 return a.length > b.length ? 1 : -1;
844 }
845 for (var i = a.length - 1; i >= 0; i--) {
846 if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
847 }
848 return 0;
849 }
850
851 BigInteger.prototype.compareAbs = function (v) {
852 var n = parseValue(v),
853 a = this.value,
854 b = n.value;
855 if (n.isSmall) return 1;
856 return compareAbs(a, b);
857 };
858 SmallInteger.prototype.compareAbs = function (v) {
859 var n = parseValue(v),
860 a = Math.abs(this.value),
861 b = n.value;
862 if (n.isSmall) {
863 b = Math.abs(b);
864 return a === b ? 0 : a > b ? 1 : -1;
865 }
866 return -1;
867 };
868
869 BigInteger.prototype.compare = function (v) {
870 // See discussion about comparison with Infinity:
871 // https://github.com/peterolson/BigInteger.js/issues/61
872 if (v === Infinity) {
873 return -1;
874 }
875 if (v === -Infinity) {
876 return 1;
877 }
878
879 var n = parseValue(v),
880 a = this.value,
881 b = n.value;
882 if (this.sign !== n.sign) {
883 return n.sign ? 1 : -1;
884 }
885 if (n.isSmall) {
886 return this.sign ? -1 : 1;
887 }
888 return compareAbs(a, b) * (this.sign ? -1 : 1);
889 };
890 BigInteger.prototype.compareTo = BigInteger.prototype.compare;
891
892 SmallInteger.prototype.compare = function (v) {
893 if (v === Infinity) {
894 return -1;
895 }
896 if (v === -Infinity) {
897 return 1;
898 }
899
900 var n = parseValue(v),
901 a = this.value,
902 b = n.value;
903 if (n.isSmall) {
904 return a == b ? 0 : a > b ? 1 : -1;
905 }
906 if (a < 0 !== n.sign) {
907 return a < 0 ? -1 : 1;
908 }
909 return a < 0 ? 1 : -1;
910 };
911 SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
912
913 BigInteger.prototype.equals = function (v) {
914 return this.compare(v) === 0;
915 };
916 SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
917
918 BigInteger.prototype.notEquals = function (v) {
919 return this.compare(v) !== 0;
920 };
921 SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
922
923 BigInteger.prototype.greater = function (v) {
924 return this.compare(v) > 0;
925 };
926 SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
927
928 BigInteger.prototype.lesser = function (v) {
929 return this.compare(v) < 0;
930 };
931 SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
932
933 BigInteger.prototype.greaterOrEquals = function (v) {
934 return this.compare(v) >= 0;
935 };
936 SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
937
938 BigInteger.prototype.lesserOrEquals = function (v) {
939 return this.compare(v) <= 0;
940 };
941 SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
942
943 BigInteger.prototype.isEven = function () {
944 return (this.value[0] & 1) === 0;
945 };
946 SmallInteger.prototype.isEven = function () {
947 return (this.value & 1) === 0;
948 };
949
950 BigInteger.prototype.isOdd = function () {
951 return (this.value[0] & 1) === 1;
952 };
953 SmallInteger.prototype.isOdd = function () {
954 return (this.value & 1) === 1;
955 };
956
957 BigInteger.prototype.isPositive = function () {
958 return !this.sign;
959 };
960 SmallInteger.prototype.isPositive = function () {
961 return this.value > 0;
962 };
963
964 BigInteger.prototype.isNegative = function () {
965 return this.sign;
966 };
967 SmallInteger.prototype.isNegative = function () {
968 return this.value < 0;
969 };
970
971 BigInteger.prototype.isUnit = function () {
972 return false;
973 };
974 SmallInteger.prototype.isUnit = function () {
975 return Math.abs(this.value) === 1;
976 };
977
978 BigInteger.prototype.isZero = function () {
979 return false;
980 };
981 SmallInteger.prototype.isZero = function () {
982 return this.value === 0;
983 };
984 BigInteger.prototype.isDivisibleBy = function (v) {
985 var n = parseValue(v);
986 var value = n.value;
987 if (value === 0) return false;
988 if (value === 1) return true;
989 if (value === 2) return this.isEven();
990 return this.mod(n).equals(Integer[0]);
991 };
992 SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
993
994 function isBasicPrime(v) {
995 var n = v.abs();
996 if (n.isUnit()) return false;
997 if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
998 if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
999 if (n.lesser(49)) return true;
1000 // we don't know if it's prime: let the other functions figure it out
1001 }
1002
1003 function millerRabinTest(n, a) {
1004 var nPrev = n.prev(),
1005 b = nPrev,
1006 r = 0,
1007 d, t, i, x;
1008 while (b.isEven()) b = b.divide(2), r++;
1009 next : for (i = 0; i < a.length; i++) {
1010 if (n.lesser(a[i])) continue;
1011 x = bigInt(a[i]).modPow(b, n);
1012 if (x.equals(Integer[1]) || x.equals(nPrev)) continue;
1013 for (d = r - 1; d != 0; d--) {
1014 x = x.square().mod(n);
1015 if (x.isUnit()) return false;
1016 if (x.equals(nPrev)) continue next;
1017 }
1018 return false;
1019 }
1020 return true;
1021 }
1022
1023// Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
1024 BigInteger.prototype.isPrime = function (strict) {
1025 var isPrime = isBasicPrime(this);
1026 if (isPrime !== undefined) return isPrime;
1027 var n = this.abs();
1028 var bits = n.bitLength();
1029 if(bits <= 64)
1030 return millerRabinTest(n, [2, 325, 9375, 28178, 450775, 9780504, 1795265022]);
1031 var logN = Math.log(2) * bits;
1032 var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
1033 for (var a = [], i = 0; i < t; i++) {
1034 a.push(bigInt(i + 2));
1035 }
1036 return millerRabinTest(n, a);
1037 };
1038 SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
1039
1040 BigInteger.prototype.isProbablePrime = function (iterations) {
1041 var isPrime = isBasicPrime(this);
1042 if (isPrime !== undefined) return isPrime;
1043 var n = this.abs();
1044 var t = iterations === undefined ? 5 : iterations;
1045 for (var a = [], i = 0; i < t; i++) {
1046 a.push(bigInt.randBetween(2, n.minus(2)));
1047 }
1048 return millerRabinTest(n, a);
1049 };
1050 SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
1051
1052 BigInteger.prototype.modInv = function (n) {
1053 var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
1054 while (!newR.equals(bigInt.zero)) {
1055 q = r.divide(newR);
1056 lastT = t;
1057 lastR = r;
1058 t = newT;
1059 r = newR;
1060 newT = lastT.subtract(q.multiply(newT));
1061 newR = lastR.subtract(q.multiply(newR));
1062 }
1063 if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
1064 if (t.compare(0) === -1) {
1065 t = t.add(n);
1066 }
1067 if (this.isNegative()) {
1068 return t.negate();
1069 }
1070 return t;
1071 };
1072
1073 SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
1074
1075 BigInteger.prototype.next = function () {
1076 var value = this.value;
1077 if (this.sign) {
1078 return subtractSmall(value, 1, this.sign);
1079 }
1080 return new BigInteger(addSmall(value, 1), this.sign);
1081 };
1082 SmallInteger.prototype.next = function () {
1083 var value = this.value;
1084 if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
1085 return new BigInteger(MAX_INT_ARR, false);
1086 };
1087
1088 BigInteger.prototype.prev = function () {
1089 var value = this.value;
1090 if (this.sign) {
1091 return new BigInteger(addSmall(value, 1), true);
1092 }
1093 return subtractSmall(value, 1, this.sign);
1094 };
1095 SmallInteger.prototype.prev = function () {
1096 var value = this.value;
1097 if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
1098 return new BigInteger(MAX_INT_ARR, true);
1099 };
1100
1101 var powersOfTwo = [1];
1102 while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
1103 var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
1104
1105 function shift_isSmall(n) {
1106 return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) ||
1107 (n instanceof BigInteger && n.value.length <= 1);
1108 }
1109
1110 BigInteger.prototype.shiftLeft = function (n) {
1111 if (!shift_isSmall(n)) {
1112 throw new Error(String(n) + " is too large for shifting.");
1113 }
1114 n = +n;
1115 if (n < 0) return this.shiftRight(-n);
1116 var result = this;
1117 if (result.isZero()) return result;
1118 while (n >= powers2Length) {
1119 result = result.multiply(highestPower2);
1120 n -= powers2Length - 1;
1121 }
1122 return result.multiply(powersOfTwo[n]);
1123 };
1124 SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
1125
1126 BigInteger.prototype.shiftRight = function (n) {
1127 var remQuo;
1128 if (!shift_isSmall(n)) {
1129 throw new Error(String(n) + " is too large for shifting.");
1130 }
1131 n = +n;
1132 if (n < 0) return this.shiftLeft(-n);
1133 var result = this;
1134 while (n >= powers2Length) {
1135 if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
1136 remQuo = divModAny(result, highestPower2);
1137 result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
1138 n -= powers2Length - 1;
1139 }
1140 remQuo = divModAny(result, powersOfTwo[n]);
1141 return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
1142 };
1143 SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
1144
1145 function bitwise(x, y, fn) {
1146 y = parseValue(y);
1147 var xSign = x.isNegative(), ySign = y.isNegative();
1148 var xRem = xSign ? x.not() : x,
1149 yRem = ySign ? y.not() : y;
1150 var xDigit = 0, yDigit = 0;
1151 var xDivMod = null, yDivMod = null;
1152 var result = [];
1153 while (!xRem.isZero() || !yRem.isZero()) {
1154 xDivMod = divModAny(xRem, highestPower2);
1155 xDigit = xDivMod[1].toJSNumber();
1156 if (xSign) {
1157 xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
1158 }
1159
1160 yDivMod = divModAny(yRem, highestPower2);
1161 yDigit = yDivMod[1].toJSNumber();
1162 if (ySign) {
1163 yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
1164 }
1165
1166 xRem = xDivMod[0];
1167 yRem = yDivMod[0];
1168 result.push(fn(xDigit, yDigit));
1169 }
1170 var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
1171 for (var i = result.length - 1; i >= 0; i -= 1) {
1172 sum = sum.multiply(highestPower2).add(bigInt(result[i]));
1173 }
1174 return sum;
1175 }
1176
1177 BigInteger.prototype.not = function () {
1178 return this.negate().prev();
1179 };
1180 SmallInteger.prototype.not = BigInteger.prototype.not;
1181
1182 BigInteger.prototype.and = function (n) {
1183 return bitwise(this, n, function (a, b) { return a & b; });
1184 };
1185 SmallInteger.prototype.and = BigInteger.prototype.and;
1186
1187 BigInteger.prototype.or = function (n) {
1188 return bitwise(this, n, function (a, b) { return a | b; });
1189 };
1190 SmallInteger.prototype.or = BigInteger.prototype.or;
1191
1192 BigInteger.prototype.xor = function (n) {
1193 return bitwise(this, n, function (a, b) { return a ^ b; });
1194 };
1195 SmallInteger.prototype.xor = BigInteger.prototype.xor;
1196
1197 var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
1198 function roughLOB(n) { // get lowestOneBit (rough)
1199 // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
1200 // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
1201 var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI;
1202 return x & -x;
1203 }
1204
1205 function integerLogarithm(value, base) {
1206 if (base.compareTo(value) <= 0) {
1207 var tmp = integerLogarithm(value, base.square(base));
1208 var p = tmp.p;
1209 var e = tmp.e;
1210 var t = p.multiply(base);
1211 return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
1212 }
1213 return { p: bigInt(1), e: 0 };
1214 }
1215
1216 BigInteger.prototype.bitLength = function () {
1217 var n = this;
1218 if (n.compareTo(bigInt(0)) < 0) {
1219 n = n.negate().subtract(bigInt(1));
1220 }
1221 if (n.compareTo(bigInt(0)) === 0) {
1222 return bigInt(0);
1223 }
1224 return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
1225 }
1226 SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
1227
1228 function max(a, b) {
1229 a = parseValue(a);
1230 b = parseValue(b);
1231 return a.greater(b) ? a : b;
1232 }
1233 function min(a, b) {
1234 a = parseValue(a);
1235 b = parseValue(b);
1236 return a.lesser(b) ? a : b;
1237 }
1238 function gcd(a, b) {
1239 a = parseValue(a).abs();
1240 b = parseValue(b).abs();
1241 if (a.equals(b)) return a;
1242 if (a.isZero()) return b;
1243 if (b.isZero()) return a;
1244 var c = Integer[1], d, t;
1245 while (a.isEven() && b.isEven()) {
1246 d = Math.min(roughLOB(a), roughLOB(b));
1247 a = a.divide(d);
1248 b = b.divide(d);
1249 c = c.multiply(d);
1250 }
1251 while (a.isEven()) {
1252 a = a.divide(roughLOB(a));
1253 }
1254 do {
1255 while (b.isEven()) {
1256 b = b.divide(roughLOB(b));
1257 }
1258 if (a.greater(b)) {
1259 t = b; b = a; a = t;
1260 }
1261 b = b.subtract(a);
1262 } while (!b.isZero());
1263 return c.isUnit() ? a : a.multiply(c);
1264 }
1265 function lcm(a, b) {
1266 a = parseValue(a).abs();
1267 b = parseValue(b).abs();
1268 return a.divide(gcd(a, b)).multiply(b);
1269 }
1270 function randBetween(a, b) {
1271 a = parseValue(a);
1272 b = parseValue(b);
1273 var low = min(a, b), high = max(a, b);
1274 var range = high.subtract(low).add(1);
1275 if (range.isSmall) return low.add(Math.floor(Math.random() * range));
1276 var length = range.value.length - 1;
1277 var result = [], restricted = true;
1278 for (var i = length; i >= 0; i--) {
1279 var top = restricted ? range.value[i] : BASE;
1280 var digit = truncate(Math.random() * top);
1281 result.unshift(digit);
1282 if (digit < top) restricted = false;
1283 }
1284 result = arrayToSmall(result);
1285 return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false));
1286 }
1287 var parseBase = function (text, base) {
1288 var length = text.length;
1289 var i;
1290 var absBase = Math.abs(base);
1291 for (var i = 0; i < length; i++) {
1292 var c = text[i].toLowerCase();
1293 if (c === "-") continue;
1294 if (/[a-z0-9]/.test(c)) {
1295 if (/[0-9]/.test(c) && +c >= absBase) {
1296 if (c === "1" && absBase === 1) continue;
1297 throw new Error(c + " is not a valid digit in base " + base + ".");
1298 } else if (c.charCodeAt(0) - 87 >= absBase) {
1299 throw new Error(c + " is not a valid digit in base " + base + ".");
1300 }
1301 }
1302 }
1303 if (2 <= base && base <= 36) {
1304 if (length <= LOG_MAX_INT / Math.log(base)) {
1305 var result = parseInt(text, base);
1306 if (isNaN(result)) {
1307 throw new Error(c + " is not a valid digit in base " + base + ".");
1308 }
1309 return new SmallInteger(parseInt(text, base));
1310 }
1311 }
1312 base = parseValue(base);
1313 var digits = [];
1314 var isNegative = text[0] === "-";
1315 for (i = isNegative ? 1 : 0; i < text.length; i++) {
1316 var c = text[i].toLowerCase(),
1317 charCode = c.charCodeAt(0);
1318 if (48 <= charCode && charCode <= 57) digits.push(parseValue(c));
1319 else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87));
1320 else if (c === "<") {
1321 var start = i;
1322 do { i++; } while (text[i] !== ">");
1323 digits.push(parseValue(text.slice(start + 1, i)));
1324 }
1325 else throw new Error(c + " is not a valid character");
1326 }
1327 return parseBaseFromArray(digits, base, isNegative);
1328 };
1329
1330 function parseBaseFromArray(digits, base, isNegative) {
1331 var val = Integer[0], pow = Integer[1], i;
1332 for (i = digits.length - 1; i >= 0; i--) {
1333 val = val.add(digits[i].times(pow));
1334 pow = pow.times(base);
1335 }
1336 return isNegative ? val.negate() : val;
1337 }
1338
1339 function stringify(digit) {
1340 if (digit <= 35) {
1341 return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(digit);
1342 }
1343 return "<" + digit + ">";
1344 }
1345
1346 function toBase(n, base) {
1347 base = bigInt(base);
1348 if (base.isZero()) {
1349 if (n.isZero()) return { value: [0], isNegative: false };
1350 throw new Error("Cannot convert nonzero numbers to base 0.");
1351 }
1352 if (base.equals(-1)) {
1353 if (n.isZero()) return { value: [0], isNegative: false };
1354 if (n.isNegative())
1355 return {
1356 value: [].concat.apply([], Array.apply(null, Array(-n))
1357 .map(Array.prototype.valueOf, [1, 0])
1358 ),
1359 isNegative: false
1360 };
1361
1362 var arr = Array.apply(null, Array(+n - 1))
1363 .map(Array.prototype.valueOf, [0, 1]);
1364 arr.unshift([1]);
1365 return {
1366 value: [].concat.apply([], arr),
1367 isNegative: false
1368 };
1369 }
1370
1371 var neg = false;
1372 if (n.isNegative() && base.isPositive()) {
1373 neg = true;
1374 n = n.abs();
1375 }
1376 if (base.equals(1)) {
1377 if (n.isZero()) return { value: [0], isNegative: false };
1378
1379 return {
1380 value: Array.apply(null, Array(+n))
1381 .map(Number.prototype.valueOf, 1),
1382 isNegative: neg
1383 };
1384 }
1385 var out = [];
1386 var left = n, divmod;
1387 while (left.isNegative() || left.compareAbs(base) >= 0) {
1388 divmod = left.divmod(base);
1389 left = divmod.quotient;
1390 var digit = divmod.remainder;
1391 if (digit.isNegative()) {
1392 digit = base.minus(digit).abs();
1393 left = left.next();
1394 }
1395 out.push(digit.toJSNumber());
1396 }
1397 out.push(left.toJSNumber());
1398 return { value: out.reverse(), isNegative: neg };
1399 }
1400
1401 function toBaseString(n, base) {
1402 var arr = toBase(n, base);
1403 return (arr.isNegative ? "-" : "") + arr.value.map(stringify).join('');
1404 }
1405
1406 BigInteger.prototype.toArray = function (radix) {
1407 return toBase(this, radix);
1408 };
1409
1410 SmallInteger.prototype.toArray = function (radix) {
1411 return toBase(this, radix);
1412 };
1413
1414 BigInteger.prototype.toString = function (radix) {
1415 if (radix === undefined) radix = 10;
1416 if (radix !== 10) return toBaseString(this, radix);
1417 var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
1418 while (--l >= 0) {
1419 digit = String(v[l]);
1420 str += zeros.slice(digit.length) + digit;
1421 }
1422 var sign = this.sign ? "-" : "";
1423 return sign + str;
1424 };
1425
1426 SmallInteger.prototype.toString = function (radix) {
1427 if (radix === undefined) radix = 10;
1428 if (radix != 10) return toBaseString(this, radix);
1429 return String(this.value);
1430 };
1431 BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }
1432
1433 BigInteger.prototype.valueOf = function () {
1434 return parseInt(this.toString(), 10);
1435 };
1436 BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
1437
1438 SmallInteger.prototype.valueOf = function () {
1439 return this.value;
1440 };
1441 SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
1442
1443 function parseStringValue(v) {
1444 if (isPrecise(+v)) {
1445 var x = +v;
1446 if (x === truncate(x))
1447 return new SmallInteger(x);
1448 throw new Error("Invalid integer: " + v);
1449 }
1450 var sign = v[0] === "-";
1451 if (sign) v = v.slice(1);
1452 var split = v.split(/e/i);
1453 if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
1454 if (split.length === 2) {
1455 var exp = split[1];
1456 if (exp[0] === "+") exp = exp.slice(1);
1457 exp = +exp;
1458 if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
1459 var text = split[0];
1460 var decimalPlace = text.indexOf(".");
1461 if (decimalPlace >= 0) {
1462 exp -= text.length - decimalPlace - 1;
1463 text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
1464 }
1465 if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
1466 text += (new Array(exp + 1)).join("0");
1467 v = text;
1468 }
1469 var isValid = /^([0-9][0-9]*)$/.test(v);
1470 if (!isValid) throw new Error("Invalid integer: " + v);
1471 var r = [], max = v.length, l = LOG_BASE, min = max - l;
1472 while (max > 0) {
1473 r.push(+v.slice(min, max));
1474 min -= l;
1475 if (min < 0) min = 0;
1476 max -= l;
1477 }
1478 trim(r);
1479 return new BigInteger(r, sign);
1480 }
1481
1482 function parseNumberValue(v) {
1483 if (isPrecise(v)) {
1484 if (v !== truncate(v)) throw new Error(v + " is not an integer.");
1485 return new SmallInteger(v);
1486 }
1487 return parseStringValue(v.toString());
1488 }
1489
1490 function parseValue(v) {
1491 if (typeof v === "number") {
1492 return parseNumberValue(v);
1493 }
1494 if (typeof v === "string") {
1495 return parseStringValue(v);
1496 }
1497 return v;
1498 }
1499 // Pre-define numbers in range [-999,999]
1500 for (var i = 0; i < 1000; i++) {
1501 Integer[i] = new SmallInteger(i);
1502 if (i > 0) Integer[-i] = new SmallInteger(-i);
1503 }
1504 // Backwards compatibility
1505 Integer.one = Integer[1];
1506 Integer.zero = Integer[0];
1507 Integer.minusOne = Integer[-1];
1508 Integer.max = max;
1509 Integer.min = min;
1510 Integer.gcd = gcd;
1511 Integer.lcm = lcm;
1512 Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; };
1513 Integer.randBetween = randBetween;
1514
1515 Integer.fromArray = function (digits, base, isNegative) {
1516 return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
1517 };
1518
1519 return Integer;
1520})();
1521
1522// Node.js check
1523if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
1524 module.exports = bigInt;
1525}
1526
1527//amd check
1528if (typeof define === "function" && define.amd) {
1529 define("big-integer", [], function () {
1530 return bigInt;
1531 });
1532}
1533
1534},{}],4:[function(require,module,exports){
1535
1536},{}],5:[function(require,module,exports){
1537var basex = require('base-x')
1538var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
1539
1540module.exports = basex(ALPHABET)
1541
1542},{"base-x":1}],6:[function(require,module,exports){
1543'use strict'
1544
1545var base58 = require('bs58')
1546var Buffer = require('safe-buffer').Buffer
1547
1548module.exports = function (checksumFn) {
1549 // Encode a buffer as a base58-check encoded string
1550 function encode (payload) {
1551 var checksum = checksumFn(payload)
1552
1553 return base58.encode(Buffer.concat([
1554 payload,
1555 checksum
1556 ], payload.length + 4))
1557 }
1558
1559 function decodeRaw (buffer) {
1560 var payload = buffer.slice(0, -4)
1561 var checksum = buffer.slice(-4)
1562 var newChecksum = checksumFn(payload)
1563
1564 if (checksum[0] ^ newChecksum[0] |
1565 checksum[1] ^ newChecksum[1] |
1566 checksum[2] ^ newChecksum[2] |
1567 checksum[3] ^ newChecksum[3]) return
1568
1569 return payload
1570 }
1571
1572 // Decode a base58-check encoded string to a buffer, no result if checksum is wrong
1573 function decodeUnsafe (string) {
1574 var buffer = base58.decodeUnsafe(string)
1575 if (!buffer) return
1576
1577 return decodeRaw(buffer)
1578 }
1579
1580 function decode (string) {
1581 var buffer = base58.decode(string)
1582 var payload = decodeRaw(buffer, checksumFn)
1583 if (!payload) throw new Error('Invalid checksum')
1584 return payload
1585 }
1586
1587 return {
1588 encode: encode,
1589 decode: decode,
1590 decodeUnsafe: decodeUnsafe
1591 }
1592}
1593
1594},{"bs58":5,"safe-buffer":8}],7:[function(require,module,exports){
1595'use strict'
1596
1597var createHash = require('create-hash')
1598var bs58checkBase = require('./base')
1599
1600// SHA256(SHA256(buffer))
1601function sha256x2 (buffer) {
1602 var tmp = createHash('sha256').update(buffer).digest()
1603 return createHash('sha256').update(tmp).digest()
1604}
1605
1606module.exports = bs58checkBase(sha256x2)
1607
1608},{"./base":6,"create-hash":16}],8:[function(require,module,exports){
1609/* eslint-disable node/no-deprecated-api */
1610var buffer = require('buffer')
1611var Buffer = buffer.Buffer
1612
1613// alternative to using Object.keys for old browsers
1614function copyProps (src, dst) {
1615 for (var key in src) {
1616 dst[key] = src[key]
1617 }
1618}
1619if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
1620 module.exports = buffer
1621} else {
1622 // Copy properties from require('buffer')
1623 copyProps(buffer, exports)
1624 exports.Buffer = SafeBuffer
1625}
1626
1627function SafeBuffer (arg, encodingOrOffset, length) {
1628 return Buffer(arg, encodingOrOffset, length)
1629}
1630
1631// Copy static methods from Buffer
1632copyProps(Buffer, SafeBuffer)
1633
1634SafeBuffer.from = function (arg, encodingOrOffset, length) {
1635 if (typeof arg === 'number') {
1636 throw new TypeError('Argument must not be a number')
1637 }
1638 return Buffer(arg, encodingOrOffset, length)
1639}
1640
1641SafeBuffer.alloc = function (size, fill, encoding) {
1642 if (typeof size !== 'number') {
1643 throw new TypeError('Argument must be a number')
1644 }
1645 var buf = Buffer(size)
1646 if (fill !== undefined) {
1647 if (typeof encoding === 'string') {
1648 buf.fill(fill, encoding)
1649 } else {
1650 buf.fill(fill)
1651 }
1652 } else {
1653 buf.fill(0)
1654 }
1655 return buf
1656}
1657
1658SafeBuffer.allocUnsafe = function (size) {
1659 if (typeof size !== 'number') {
1660 throw new TypeError('Argument must be a number')
1661 }
1662 return Buffer(size)
1663}
1664
1665SafeBuffer.allocUnsafeSlow = function (size) {
1666 if (typeof size !== 'number') {
1667 throw new TypeError('Argument must be a number')
1668 }
1669 return buffer.SlowBuffer(size)
1670}
1671
1672},{"buffer":9}],9:[function(require,module,exports){
1673/*!
1674 * The buffer module from node.js, for the browser.
1675 *
1676 * @author Feross Aboukhadijeh <https://feross.org>
1677 * @license MIT
1678 */
1679/* eslint-disable no-proto */
1680
1681'use strict'
1682
1683var base64 = require('base64-js')
1684var ieee754 = require('ieee754')
1685
1686exports.Buffer = Buffer
1687exports.SlowBuffer = SlowBuffer
1688exports.INSPECT_MAX_BYTES = 50
1689
1690var K_MAX_LENGTH = 0x7fffffff
1691exports.kMaxLength = K_MAX_LENGTH
1692
1693/**
1694 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1695 * === true Use Uint8Array implementation (fastest)
1696 * === false Print warning and recommend using `buffer` v4.x which has an Object
1697 * implementation (most compatible, even IE6)
1698 *
1699 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1700 * Opera 11.6+, iOS 4.2+.
1701 *
1702 * We report that the browser does not support typed arrays if the are not subclassable
1703 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
1704 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
1705 * for __proto__ and has a buggy typed array implementation.
1706 */
1707Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
1708
1709if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
1710 typeof console.error === 'function') {
1711 console.error(
1712 'This browser lacks typed array (Uint8Array) support which is required by ' +
1713 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
1714 )
1715}
1716
1717function typedArraySupport () {
1718 // Can typed array instances can be augmented?
1719 try {
1720 var arr = new Uint8Array(1)
1721 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
1722 return arr.foo() === 42
1723 } catch (e) {
1724 return false
1725 }
1726}
1727
1728function createBuffer (length) {
1729 if (length > K_MAX_LENGTH) {
1730 throw new RangeError('Invalid typed array length')
1731 }
1732 // Return an augmented `Uint8Array` instance
1733 var buf = new Uint8Array(length)
1734 buf.__proto__ = Buffer.prototype
1735 return buf
1736}
1737
1738/**
1739 * The Buffer constructor returns instances of `Uint8Array` that have their
1740 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
1741 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
1742 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
1743 * returns a single octet.
1744 *
1745 * The `Uint8Array` prototype remains unmodified.
1746 */
1747
1748function Buffer (arg, encodingOrOffset, length) {
1749 // Common case.
1750 if (typeof arg === 'number') {
1751 if (typeof encodingOrOffset === 'string') {
1752 throw new Error(
1753 'If encoding is specified then the first argument must be a string'
1754 )
1755 }
1756 return allocUnsafe(arg)
1757 }
1758 return from(arg, encodingOrOffset, length)
1759}
1760
1761// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
1762if (typeof Symbol !== 'undefined' && Symbol.species &&
1763 Buffer[Symbol.species] === Buffer) {
1764 Object.defineProperty(Buffer, Symbol.species, {
1765 value: null,
1766 configurable: true,
1767 enumerable: false,
1768 writable: false
1769 })
1770}
1771
1772Buffer.poolSize = 8192 // not used by this implementation
1773
1774function from (value, encodingOrOffset, length) {
1775 if (typeof value === 'number') {
1776 throw new TypeError('"value" argument must not be a number')
1777 }
1778
1779 if (isArrayBuffer(value)) {
1780 return fromArrayBuffer(value, encodingOrOffset, length)
1781 }
1782
1783 if (typeof value === 'string') {
1784 return fromString(value, encodingOrOffset)
1785 }
1786
1787 return fromObject(value)
1788}
1789
1790/**
1791 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
1792 * if value is a number.
1793 * Buffer.from(str[, encoding])
1794 * Buffer.from(array)
1795 * Buffer.from(buffer)
1796 * Buffer.from(arrayBuffer[, byteOffset[, length]])
1797 **/
1798Buffer.from = function (value, encodingOrOffset, length) {
1799 return from(value, encodingOrOffset, length)
1800}
1801
1802// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
1803// https://github.com/feross/buffer/pull/148
1804Buffer.prototype.__proto__ = Uint8Array.prototype
1805Buffer.__proto__ = Uint8Array
1806
1807function assertSize (size) {
1808 if (typeof size !== 'number') {
1809 throw new TypeError('"size" argument must be a number')
1810 } else if (size < 0) {
1811 throw new RangeError('"size" argument must not be negative')
1812 }
1813}
1814
1815function alloc (size, fill, encoding) {
1816 assertSize(size)
1817 if (size <= 0) {
1818 return createBuffer(size)
1819 }
1820 if (fill !== undefined) {
1821 // Only pay attention to encoding if it's a string. This
1822 // prevents accidentally sending in a number that would
1823 // be interpretted as a start offset.
1824 return typeof encoding === 'string'
1825 ? createBuffer(size).fill(fill, encoding)
1826 : createBuffer(size).fill(fill)
1827 }
1828 return createBuffer(size)
1829}
1830
1831/**
1832 * Creates a new filled Buffer instance.
1833 * alloc(size[, fill[, encoding]])
1834 **/
1835Buffer.alloc = function (size, fill, encoding) {
1836 return alloc(size, fill, encoding)
1837}
1838
1839function allocUnsafe (size) {
1840 assertSize(size)
1841 return createBuffer(size < 0 ? 0 : checked(size) | 0)
1842}
1843
1844/**
1845 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
1846 * */
1847Buffer.allocUnsafe = function (size) {
1848 return allocUnsafe(size)
1849}
1850/**
1851 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
1852 */
1853Buffer.allocUnsafeSlow = function (size) {
1854 return allocUnsafe(size)
1855}
1856
1857function fromString (string, encoding) {
1858 if (typeof encoding !== 'string' || encoding === '') {
1859 encoding = 'utf8'
1860 }
1861
1862 if (!Buffer.isEncoding(encoding)) {
1863 throw new TypeError('"encoding" must be a valid string encoding')
1864 }
1865
1866 var length = byteLength(string, encoding) | 0
1867 var buf = createBuffer(length)
1868
1869 var actual = buf.write(string, encoding)
1870
1871 if (actual !== length) {
1872 // Writing a hex string, for example, that contains invalid characters will
1873 // cause everything after the first invalid character to be ignored. (e.g.
1874 // 'abxxcd' will be treated as 'ab')
1875 buf = buf.slice(0, actual)
1876 }
1877
1878 return buf
1879}
1880
1881function fromArrayLike (array) {
1882 var length = array.length < 0 ? 0 : checked(array.length) | 0
1883 var buf = createBuffer(length)
1884 for (var i = 0; i < length; i += 1) {
1885 buf[i] = array[i] & 255
1886 }
1887 return buf
1888}
1889
1890function fromArrayBuffer (array, byteOffset, length) {
1891 if (byteOffset < 0 || array.byteLength < byteOffset) {
1892 throw new RangeError('\'offset\' is out of bounds')
1893 }
1894
1895 if (array.byteLength < byteOffset + (length || 0)) {
1896 throw new RangeError('\'length\' is out of bounds')
1897 }
1898
1899 var buf
1900 if (byteOffset === undefined && length === undefined) {
1901 buf = new Uint8Array(array)
1902 } else if (length === undefined) {
1903 buf = new Uint8Array(array, byteOffset)
1904 } else {
1905 buf = new Uint8Array(array, byteOffset, length)
1906 }
1907
1908 // Return an augmented `Uint8Array` instance
1909 buf.__proto__ = Buffer.prototype
1910 return buf
1911}
1912
1913function fromObject (obj) {
1914 if (Buffer.isBuffer(obj)) {
1915 var len = checked(obj.length) | 0
1916 var buf = createBuffer(len)
1917
1918 if (buf.length === 0) {
1919 return buf
1920 }
1921
1922 obj.copy(buf, 0, 0, len)
1923 return buf
1924 }
1925
1926 if (obj) {
1927 if (isArrayBufferView(obj) || 'length' in obj) {
1928 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
1929 return createBuffer(0)
1930 }
1931 return fromArrayLike(obj)
1932 }
1933
1934 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
1935 return fromArrayLike(obj.data)
1936 }
1937 }
1938
1939 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
1940}
1941
1942function checked (length) {
1943 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
1944 // length is NaN (which is otherwise coerced to zero.)
1945 if (length >= K_MAX_LENGTH) {
1946 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1947 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1948 }
1949 return length | 0
1950}
1951
1952function SlowBuffer (length) {
1953 if (+length != length) { // eslint-disable-line eqeqeq
1954 length = 0
1955 }
1956 return Buffer.alloc(+length)
1957}
1958
1959Buffer.isBuffer = function isBuffer (b) {
1960 return b != null && b._isBuffer === true
1961}
1962
1963Buffer.compare = function compare (a, b) {
1964 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1965 throw new TypeError('Arguments must be Buffers')
1966 }
1967
1968 if (a === b) return 0
1969
1970 var x = a.length
1971 var y = b.length
1972
1973 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1974 if (a[i] !== b[i]) {
1975 x = a[i]
1976 y = b[i]
1977 break
1978 }
1979 }
1980
1981 if (x < y) return -1
1982 if (y < x) return 1
1983 return 0
1984}
1985
1986Buffer.isEncoding = function isEncoding (encoding) {
1987 switch (String(encoding).toLowerCase()) {
1988 case 'hex':
1989 case 'utf8':
1990 case 'utf-8':
1991 case 'ascii':
1992 case 'latin1':
1993 case 'binary':
1994 case 'base64':
1995 case 'ucs2':
1996 case 'ucs-2':
1997 case 'utf16le':
1998 case 'utf-16le':
1999 return true
2000 default:
2001 return false
2002 }
2003}
2004
2005Buffer.concat = function concat (list, length) {
2006 if (!Array.isArray(list)) {
2007 throw new TypeError('"list" argument must be an Array of Buffers')
2008 }
2009
2010 if (list.length === 0) {
2011 return Buffer.alloc(0)
2012 }
2013
2014 var i
2015 if (length === undefined) {
2016 length = 0
2017 for (i = 0; i < list.length; ++i) {
2018 length += list[i].length
2019 }
2020 }
2021
2022 var buffer = Buffer.allocUnsafe(length)
2023 var pos = 0
2024 for (i = 0; i < list.length; ++i) {
2025 var buf = list[i]
2026 if (!Buffer.isBuffer(buf)) {
2027 throw new TypeError('"list" argument must be an Array of Buffers')
2028 }
2029 buf.copy(buffer, pos)
2030 pos += buf.length
2031 }
2032 return buffer
2033}
2034
2035function byteLength (string, encoding) {
2036 if (Buffer.isBuffer(string)) {
2037 return string.length
2038 }
2039 if (isArrayBufferView(string) || isArrayBuffer(string)) {
2040 return string.byteLength
2041 }
2042 if (typeof string !== 'string') {
2043 string = '' + string
2044 }
2045
2046 var len = string.length
2047 if (len === 0) return 0
2048
2049 // Use a for loop to avoid recursion
2050 var loweredCase = false
2051 for (;;) {
2052 switch (encoding) {
2053 case 'ascii':
2054 case 'latin1':
2055 case 'binary':
2056 return len
2057 case 'utf8':
2058 case 'utf-8':
2059 case undefined:
2060 return utf8ToBytes(string).length
2061 case 'ucs2':
2062 case 'ucs-2':
2063 case 'utf16le':
2064 case 'utf-16le':
2065 return len * 2
2066 case 'hex':
2067 return len >>> 1
2068 case 'base64':
2069 return base64ToBytes(string).length
2070 default:
2071 if (loweredCase) return utf8ToBytes(string).length // assume utf8
2072 encoding = ('' + encoding).toLowerCase()
2073 loweredCase = true
2074 }
2075 }
2076}
2077Buffer.byteLength = byteLength
2078
2079function slowToString (encoding, start, end) {
2080 var loweredCase = false
2081
2082 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2083 // property of a typed array.
2084
2085 // This behaves neither like String nor Uint8Array in that we set start/end
2086 // to their upper/lower bounds if the value passed is out of range.
2087 // undefined is handled specially as per ECMA-262 6th Edition,
2088 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2089 if (start === undefined || start < 0) {
2090 start = 0
2091 }
2092 // Return early if start > this.length. Done here to prevent potential uint32
2093 // coercion fail below.
2094 if (start > this.length) {
2095 return ''
2096 }
2097
2098 if (end === undefined || end > this.length) {
2099 end = this.length
2100 }
2101
2102 if (end <= 0) {
2103 return ''
2104 }
2105
2106 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
2107 end >>>= 0
2108 start >>>= 0
2109
2110 if (end <= start) {
2111 return ''
2112 }
2113
2114 if (!encoding) encoding = 'utf8'
2115
2116 while (true) {
2117 switch (encoding) {
2118 case 'hex':
2119 return hexSlice(this, start, end)
2120
2121 case 'utf8':
2122 case 'utf-8':
2123 return utf8Slice(this, start, end)
2124
2125 case 'ascii':
2126 return asciiSlice(this, start, end)
2127
2128 case 'latin1':
2129 case 'binary':
2130 return latin1Slice(this, start, end)
2131
2132 case 'base64':
2133 return base64Slice(this, start, end)
2134
2135 case 'ucs2':
2136 case 'ucs-2':
2137 case 'utf16le':
2138 case 'utf-16le':
2139 return utf16leSlice(this, start, end)
2140
2141 default:
2142 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2143 encoding = (encoding + '').toLowerCase()
2144 loweredCase = true
2145 }
2146 }
2147}
2148
2149// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
2150// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
2151// reliably in a browserify context because there could be multiple different
2152// copies of the 'buffer' package in use. This method works even for Buffer
2153// instances that were created from another copy of the `buffer` package.
2154// See: https://github.com/feross/buffer/issues/154
2155Buffer.prototype._isBuffer = true
2156
2157function swap (b, n, m) {
2158 var i = b[n]
2159 b[n] = b[m]
2160 b[m] = i
2161}
2162
2163Buffer.prototype.swap16 = function swap16 () {
2164 var len = this.length
2165 if (len % 2 !== 0) {
2166 throw new RangeError('Buffer size must be a multiple of 16-bits')
2167 }
2168 for (var i = 0; i < len; i += 2) {
2169 swap(this, i, i + 1)
2170 }
2171 return this
2172}
2173
2174Buffer.prototype.swap32 = function swap32 () {
2175 var len = this.length
2176 if (len % 4 !== 0) {
2177 throw new RangeError('Buffer size must be a multiple of 32-bits')
2178 }
2179 for (var i = 0; i < len; i += 4) {
2180 swap(this, i, i + 3)
2181 swap(this, i + 1, i + 2)
2182 }
2183 return this
2184}
2185
2186Buffer.prototype.swap64 = function swap64 () {
2187 var len = this.length
2188 if (len % 8 !== 0) {
2189 throw new RangeError('Buffer size must be a multiple of 64-bits')
2190 }
2191 for (var i = 0; i < len; i += 8) {
2192 swap(this, i, i + 7)
2193 swap(this, i + 1, i + 6)
2194 swap(this, i + 2, i + 5)
2195 swap(this, i + 3, i + 4)
2196 }
2197 return this
2198}
2199
2200Buffer.prototype.toString = function toString () {
2201 var length = this.length
2202 if (length === 0) return ''
2203 if (arguments.length === 0) return utf8Slice(this, 0, length)
2204 return slowToString.apply(this, arguments)
2205}
2206
2207Buffer.prototype.equals = function equals (b) {
2208 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
2209 if (this === b) return true
2210 return Buffer.compare(this, b) === 0
2211}
2212
2213Buffer.prototype.inspect = function inspect () {
2214 var str = ''
2215 var max = exports.INSPECT_MAX_BYTES
2216 if (this.length > 0) {
2217 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
2218 if (this.length > max) str += ' ... '
2219 }
2220 return '<Buffer ' + str + '>'
2221}
2222
2223Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
2224 if (!Buffer.isBuffer(target)) {
2225 throw new TypeError('Argument must be a Buffer')
2226 }
2227
2228 if (start === undefined) {
2229 start = 0
2230 }
2231 if (end === undefined) {
2232 end = target ? target.length : 0
2233 }
2234 if (thisStart === undefined) {
2235 thisStart = 0
2236 }
2237 if (thisEnd === undefined) {
2238 thisEnd = this.length
2239 }
2240
2241 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2242 throw new RangeError('out of range index')
2243 }
2244
2245 if (thisStart >= thisEnd && start >= end) {
2246 return 0
2247 }
2248 if (thisStart >= thisEnd) {
2249 return -1
2250 }
2251 if (start >= end) {
2252 return 1
2253 }
2254
2255 start >>>= 0
2256 end >>>= 0
2257 thisStart >>>= 0
2258 thisEnd >>>= 0
2259
2260 if (this === target) return 0
2261
2262 var x = thisEnd - thisStart
2263 var y = end - start
2264 var len = Math.min(x, y)
2265
2266 var thisCopy = this.slice(thisStart, thisEnd)
2267 var targetCopy = target.slice(start, end)
2268
2269 for (var i = 0; i < len; ++i) {
2270 if (thisCopy[i] !== targetCopy[i]) {
2271 x = thisCopy[i]
2272 y = targetCopy[i]
2273 break
2274 }
2275 }
2276
2277 if (x < y) return -1
2278 if (y < x) return 1
2279 return 0
2280}
2281
2282// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2283// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2284//
2285// Arguments:
2286// - buffer - a Buffer to search
2287// - val - a string, Buffer, or number
2288// - byteOffset - an index into `buffer`; will be clamped to an int32
2289// - encoding - an optional encoding, relevant is val is a string
2290// - dir - true for indexOf, false for lastIndexOf
2291function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
2292 // Empty buffer means no match
2293 if (buffer.length === 0) return -1
2294
2295 // Normalize byteOffset
2296 if (typeof byteOffset === 'string') {
2297 encoding = byteOffset
2298 byteOffset = 0
2299 } else if (byteOffset > 0x7fffffff) {
2300 byteOffset = 0x7fffffff
2301 } else if (byteOffset < -0x80000000) {
2302 byteOffset = -0x80000000
2303 }
2304 byteOffset = +byteOffset // Coerce to Number.
2305 if (numberIsNaN(byteOffset)) {
2306 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2307 byteOffset = dir ? 0 : (buffer.length - 1)
2308 }
2309
2310 // Normalize byteOffset: negative offsets start from the end of the buffer
2311 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
2312 if (byteOffset >= buffer.length) {
2313 if (dir) return -1
2314 else byteOffset = buffer.length - 1
2315 } else if (byteOffset < 0) {
2316 if (dir) byteOffset = 0
2317 else return -1
2318 }
2319
2320 // Normalize val
2321 if (typeof val === 'string') {
2322 val = Buffer.from(val, encoding)
2323 }
2324
2325 // Finally, search either indexOf (if dir is true) or lastIndexOf
2326 if (Buffer.isBuffer(val)) {
2327 // Special case: looking for empty string/buffer always fails
2328 if (val.length === 0) {
2329 return -1
2330 }
2331 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
2332 } else if (typeof val === 'number') {
2333 val = val & 0xFF // Search for a byte value [0-255]
2334 if (typeof Uint8Array.prototype.indexOf === 'function') {
2335 if (dir) {
2336 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
2337 } else {
2338 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
2339 }
2340 }
2341 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
2342 }
2343
2344 throw new TypeError('val must be string, number or Buffer')
2345}
2346
2347function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
2348 var indexSize = 1
2349 var arrLength = arr.length
2350 var valLength = val.length
2351
2352 if (encoding !== undefined) {
2353 encoding = String(encoding).toLowerCase()
2354 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
2355 encoding === 'utf16le' || encoding === 'utf-16le') {
2356 if (arr.length < 2 || val.length < 2) {
2357 return -1
2358 }
2359 indexSize = 2
2360 arrLength /= 2
2361 valLength /= 2
2362 byteOffset /= 2
2363 }
2364 }
2365
2366 function read (buf, i) {
2367 if (indexSize === 1) {
2368 return buf[i]
2369 } else {
2370 return buf.readUInt16BE(i * indexSize)
2371 }
2372 }
2373
2374 var i
2375 if (dir) {
2376 var foundIndex = -1
2377 for (i = byteOffset; i < arrLength; i++) {
2378 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2379 if (foundIndex === -1) foundIndex = i
2380 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
2381 } else {
2382 if (foundIndex !== -1) i -= i - foundIndex
2383 foundIndex = -1
2384 }
2385 }
2386 } else {
2387 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
2388 for (i = byteOffset; i >= 0; i--) {
2389 var found = true
2390 for (var j = 0; j < valLength; j++) {
2391 if (read(arr, i + j) !== read(val, j)) {
2392 found = false
2393 break
2394 }
2395 }
2396 if (found) return i
2397 }
2398 }
2399
2400 return -1
2401}
2402
2403Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
2404 return this.indexOf(val, byteOffset, encoding) !== -1
2405}
2406
2407Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
2408 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
2409}
2410
2411Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
2412 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
2413}
2414
2415function hexWrite (buf, string, offset, length) {
2416 offset = Number(offset) || 0
2417 var remaining = buf.length - offset
2418 if (!length) {
2419 length = remaining
2420 } else {
2421 length = Number(length)
2422 if (length > remaining) {
2423 length = remaining
2424 }
2425 }
2426
2427 // must be an even number of digits
2428 var strLen = string.length
2429 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
2430
2431 if (length > strLen / 2) {
2432 length = strLen / 2
2433 }
2434 for (var i = 0; i < length; ++i) {
2435 var parsed = parseInt(string.substr(i * 2, 2), 16)
2436 if (numberIsNaN(parsed)) return i
2437 buf[offset + i] = parsed
2438 }
2439 return i
2440}
2441
2442function utf8Write (buf, string, offset, length) {
2443 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
2444}
2445
2446function asciiWrite (buf, string, offset, length) {
2447 return blitBuffer(asciiToBytes(string), buf, offset, length)
2448}
2449
2450function latin1Write (buf, string, offset, length) {
2451 return asciiWrite(buf, string, offset, length)
2452}
2453
2454function base64Write (buf, string, offset, length) {
2455 return blitBuffer(base64ToBytes(string), buf, offset, length)
2456}
2457
2458function ucs2Write (buf, string, offset, length) {
2459 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
2460}
2461
2462Buffer.prototype.write = function write (string, offset, length, encoding) {
2463 // Buffer#write(string)
2464 if (offset === undefined) {
2465 encoding = 'utf8'
2466 length = this.length
2467 offset = 0
2468 // Buffer#write(string, encoding)
2469 } else if (length === undefined && typeof offset === 'string') {
2470 encoding = offset
2471 length = this.length
2472 offset = 0
2473 // Buffer#write(string, offset[, length][, encoding])
2474 } else if (isFinite(offset)) {
2475 offset = offset >>> 0
2476 if (isFinite(length)) {
2477 length = length >>> 0
2478 if (encoding === undefined) encoding = 'utf8'
2479 } else {
2480 encoding = length
2481 length = undefined
2482 }
2483 } else {
2484 throw new Error(
2485 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
2486 )
2487 }
2488
2489 var remaining = this.length - offset
2490 if (length === undefined || length > remaining) length = remaining
2491
2492 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
2493 throw new RangeError('Attempt to write outside buffer bounds')
2494 }
2495
2496 if (!encoding) encoding = 'utf8'
2497
2498 var loweredCase = false
2499 for (;;) {
2500 switch (encoding) {
2501 case 'hex':
2502 return hexWrite(this, string, offset, length)
2503
2504 case 'utf8':
2505 case 'utf-8':
2506 return utf8Write(this, string, offset, length)
2507
2508 case 'ascii':
2509 return asciiWrite(this, string, offset, length)
2510
2511 case 'latin1':
2512 case 'binary':
2513 return latin1Write(this, string, offset, length)
2514
2515 case 'base64':
2516 // Warning: maxLength not taken into account in base64Write
2517 return base64Write(this, string, offset, length)
2518
2519 case 'ucs2':
2520 case 'ucs-2':
2521 case 'utf16le':
2522 case 'utf-16le':
2523 return ucs2Write(this, string, offset, length)
2524
2525 default:
2526 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
2527 encoding = ('' + encoding).toLowerCase()
2528 loweredCase = true
2529 }
2530 }
2531}
2532
2533Buffer.prototype.toJSON = function toJSON () {
2534 return {
2535 type: 'Buffer',
2536 data: Array.prototype.slice.call(this._arr || this, 0)
2537 }
2538}
2539
2540function base64Slice (buf, start, end) {
2541 if (start === 0 && end === buf.length) {
2542 return base64.fromByteArray(buf)
2543 } else {
2544 return base64.fromByteArray(buf.slice(start, end))
2545 }
2546}
2547
2548function utf8Slice (buf, start, end) {
2549 end = Math.min(buf.length, end)
2550 var res = []
2551
2552 var i = start
2553 while (i < end) {
2554 var firstByte = buf[i]
2555 var codePoint = null
2556 var bytesPerSequence = (firstByte > 0xEF) ? 4
2557 : (firstByte > 0xDF) ? 3
2558 : (firstByte > 0xBF) ? 2
2559 : 1
2560
2561 if (i + bytesPerSequence <= end) {
2562 var secondByte, thirdByte, fourthByte, tempCodePoint
2563
2564 switch (bytesPerSequence) {
2565 case 1:
2566 if (firstByte < 0x80) {
2567 codePoint = firstByte
2568 }
2569 break
2570 case 2:
2571 secondByte = buf[i + 1]
2572 if ((secondByte & 0xC0) === 0x80) {
2573 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
2574 if (tempCodePoint > 0x7F) {
2575 codePoint = tempCodePoint
2576 }
2577 }
2578 break
2579 case 3:
2580 secondByte = buf[i + 1]
2581 thirdByte = buf[i + 2]
2582 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2583 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
2584 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2585 codePoint = tempCodePoint
2586 }
2587 }
2588 break
2589 case 4:
2590 secondByte = buf[i + 1]
2591 thirdByte = buf[i + 2]
2592 fourthByte = buf[i + 3]
2593 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2594 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
2595 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2596 codePoint = tempCodePoint
2597 }
2598 }
2599 }
2600 }
2601
2602 if (codePoint === null) {
2603 // we did not generate a valid codePoint so insert a
2604 // replacement char (U+FFFD) and advance only 1 byte
2605 codePoint = 0xFFFD
2606 bytesPerSequence = 1
2607 } else if (codePoint > 0xFFFF) {
2608 // encode to utf16 (surrogate pair dance)
2609 codePoint -= 0x10000
2610 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
2611 codePoint = 0xDC00 | codePoint & 0x3FF
2612 }
2613
2614 res.push(codePoint)
2615 i += bytesPerSequence
2616 }
2617
2618 return decodeCodePointsArray(res)
2619}
2620
2621// Based on http://stackoverflow.com/a/22747272/680742, the browser with
2622// the lowest limit is Chrome, with 0x10000 args.
2623// We go 1 magnitude less, for safety
2624var MAX_ARGUMENTS_LENGTH = 0x1000
2625
2626function decodeCodePointsArray (codePoints) {
2627 var len = codePoints.length
2628 if (len <= MAX_ARGUMENTS_LENGTH) {
2629 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
2630 }
2631
2632 // Decode in chunks to avoid "call stack size exceeded".
2633 var res = ''
2634 var i = 0
2635 while (i < len) {
2636 res += String.fromCharCode.apply(
2637 String,
2638 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2639 )
2640 }
2641 return res
2642}
2643
2644function asciiSlice (buf, start, end) {
2645 var ret = ''
2646 end = Math.min(buf.length, end)
2647
2648 for (var i = start; i < end; ++i) {
2649 ret += String.fromCharCode(buf[i] & 0x7F)
2650 }
2651 return ret
2652}
2653
2654function latin1Slice (buf, start, end) {
2655 var ret = ''
2656 end = Math.min(buf.length, end)
2657
2658 for (var i = start; i < end; ++i) {
2659 ret += String.fromCharCode(buf[i])
2660 }
2661 return ret
2662}
2663
2664function hexSlice (buf, start, end) {
2665 var len = buf.length
2666
2667 if (!start || start < 0) start = 0
2668 if (!end || end < 0 || end > len) end = len
2669
2670 var out = ''
2671 for (var i = start; i < end; ++i) {
2672 out += toHex(buf[i])
2673 }
2674 return out
2675}
2676
2677function utf16leSlice (buf, start, end) {
2678 var bytes = buf.slice(start, end)
2679 var res = ''
2680 for (var i = 0; i < bytes.length; i += 2) {
2681 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
2682 }
2683 return res
2684}
2685
2686Buffer.prototype.slice = function slice (start, end) {
2687 var len = this.length
2688 start = ~~start
2689 end = end === undefined ? len : ~~end
2690
2691 if (start < 0) {
2692 start += len
2693 if (start < 0) start = 0
2694 } else if (start > len) {
2695 start = len
2696 }
2697
2698 if (end < 0) {
2699 end += len
2700 if (end < 0) end = 0
2701 } else if (end > len) {
2702 end = len
2703 }
2704
2705 if (end < start) end = start
2706
2707 var newBuf = this.subarray(start, end)
2708 // Return an augmented `Uint8Array` instance
2709 newBuf.__proto__ = Buffer.prototype
2710 return newBuf
2711}
2712
2713/*
2714 * Need to make sure that buffer isn't trying to write out of bounds.
2715 */
2716function checkOffset (offset, ext, length) {
2717 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
2718 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
2719}
2720
2721Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
2722 offset = offset >>> 0
2723 byteLength = byteLength >>> 0
2724 if (!noAssert) checkOffset(offset, byteLength, this.length)
2725
2726 var val = this[offset]
2727 var mul = 1
2728 var i = 0
2729 while (++i < byteLength && (mul *= 0x100)) {
2730 val += this[offset + i] * mul
2731 }
2732
2733 return val
2734}
2735
2736Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
2737 offset = offset >>> 0
2738 byteLength = byteLength >>> 0
2739 if (!noAssert) {
2740 checkOffset(offset, byteLength, this.length)
2741 }
2742
2743 var val = this[offset + --byteLength]
2744 var mul = 1
2745 while (byteLength > 0 && (mul *= 0x100)) {
2746 val += this[offset + --byteLength] * mul
2747 }
2748
2749 return val
2750}
2751
2752Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
2753 offset = offset >>> 0
2754 if (!noAssert) checkOffset(offset, 1, this.length)
2755 return this[offset]
2756}
2757
2758Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
2759 offset = offset >>> 0
2760 if (!noAssert) checkOffset(offset, 2, this.length)
2761 return this[offset] | (this[offset + 1] << 8)
2762}
2763
2764Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
2765 offset = offset >>> 0
2766 if (!noAssert) checkOffset(offset, 2, this.length)
2767 return (this[offset] << 8) | this[offset + 1]
2768}
2769
2770Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
2771 offset = offset >>> 0
2772 if (!noAssert) checkOffset(offset, 4, this.length)
2773
2774 return ((this[offset]) |
2775 (this[offset + 1] << 8) |
2776 (this[offset + 2] << 16)) +
2777 (this[offset + 3] * 0x1000000)
2778}
2779
2780Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
2781 offset = offset >>> 0
2782 if (!noAssert) checkOffset(offset, 4, this.length)
2783
2784 return (this[offset] * 0x1000000) +
2785 ((this[offset + 1] << 16) |
2786 (this[offset + 2] << 8) |
2787 this[offset + 3])
2788}
2789
2790Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
2791 offset = offset >>> 0
2792 byteLength = byteLength >>> 0
2793 if (!noAssert) checkOffset(offset, byteLength, this.length)
2794
2795 var val = this[offset]
2796 var mul = 1
2797 var i = 0
2798 while (++i < byteLength && (mul *= 0x100)) {
2799 val += this[offset + i] * mul
2800 }
2801 mul *= 0x80
2802
2803 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2804
2805 return val
2806}
2807
2808Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
2809 offset = offset >>> 0
2810 byteLength = byteLength >>> 0
2811 if (!noAssert) checkOffset(offset, byteLength, this.length)
2812
2813 var i = byteLength
2814 var mul = 1
2815 var val = this[offset + --i]
2816 while (i > 0 && (mul *= 0x100)) {
2817 val += this[offset + --i] * mul
2818 }
2819 mul *= 0x80
2820
2821 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
2822
2823 return val
2824}
2825
2826Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
2827 offset = offset >>> 0
2828 if (!noAssert) checkOffset(offset, 1, this.length)
2829 if (!(this[offset] & 0x80)) return (this[offset])
2830 return ((0xff - this[offset] + 1) * -1)
2831}
2832
2833Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
2834 offset = offset >>> 0
2835 if (!noAssert) checkOffset(offset, 2, this.length)
2836 var val = this[offset] | (this[offset + 1] << 8)
2837 return (val & 0x8000) ? val | 0xFFFF0000 : val
2838}
2839
2840Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
2841 offset = offset >>> 0
2842 if (!noAssert) checkOffset(offset, 2, this.length)
2843 var val = this[offset + 1] | (this[offset] << 8)
2844 return (val & 0x8000) ? val | 0xFFFF0000 : val
2845}
2846
2847Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
2848 offset = offset >>> 0
2849 if (!noAssert) checkOffset(offset, 4, this.length)
2850
2851 return (this[offset]) |
2852 (this[offset + 1] << 8) |
2853 (this[offset + 2] << 16) |
2854 (this[offset + 3] << 24)
2855}
2856
2857Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
2858 offset = offset >>> 0
2859 if (!noAssert) checkOffset(offset, 4, this.length)
2860
2861 return (this[offset] << 24) |
2862 (this[offset + 1] << 16) |
2863 (this[offset + 2] << 8) |
2864 (this[offset + 3])
2865}
2866
2867Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
2868 offset = offset >>> 0
2869 if (!noAssert) checkOffset(offset, 4, this.length)
2870 return ieee754.read(this, offset, true, 23, 4)
2871}
2872
2873Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
2874 offset = offset >>> 0
2875 if (!noAssert) checkOffset(offset, 4, this.length)
2876 return ieee754.read(this, offset, false, 23, 4)
2877}
2878
2879Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
2880 offset = offset >>> 0
2881 if (!noAssert) checkOffset(offset, 8, this.length)
2882 return ieee754.read(this, offset, true, 52, 8)
2883}
2884
2885Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
2886 offset = offset >>> 0
2887 if (!noAssert) checkOffset(offset, 8, this.length)
2888 return ieee754.read(this, offset, false, 52, 8)
2889}
2890
2891function checkInt (buf, value, offset, ext, max, min) {
2892 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
2893 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
2894 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2895}
2896
2897Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
2898 value = +value
2899 offset = offset >>> 0
2900 byteLength = byteLength >>> 0
2901 if (!noAssert) {
2902 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2903 checkInt(this, value, offset, byteLength, maxBytes, 0)
2904 }
2905
2906 var mul = 1
2907 var i = 0
2908 this[offset] = value & 0xFF
2909 while (++i < byteLength && (mul *= 0x100)) {
2910 this[offset + i] = (value / mul) & 0xFF
2911 }
2912
2913 return offset + byteLength
2914}
2915
2916Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
2917 value = +value
2918 offset = offset >>> 0
2919 byteLength = byteLength >>> 0
2920 if (!noAssert) {
2921 var maxBytes = Math.pow(2, 8 * byteLength) - 1
2922 checkInt(this, value, offset, byteLength, maxBytes, 0)
2923 }
2924
2925 var i = byteLength - 1
2926 var mul = 1
2927 this[offset + i] = value & 0xFF
2928 while (--i >= 0 && (mul *= 0x100)) {
2929 this[offset + i] = (value / mul) & 0xFF
2930 }
2931
2932 return offset + byteLength
2933}
2934
2935Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
2936 value = +value
2937 offset = offset >>> 0
2938 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
2939 this[offset] = (value & 0xff)
2940 return offset + 1
2941}
2942
2943Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
2944 value = +value
2945 offset = offset >>> 0
2946 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2947 this[offset] = (value & 0xff)
2948 this[offset + 1] = (value >>> 8)
2949 return offset + 2
2950}
2951
2952Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2953 value = +value
2954 offset = offset >>> 0
2955 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2956 this[offset] = (value >>> 8)
2957 this[offset + 1] = (value & 0xff)
2958 return offset + 2
2959}
2960
2961Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2962 value = +value
2963 offset = offset >>> 0
2964 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2965 this[offset + 3] = (value >>> 24)
2966 this[offset + 2] = (value >>> 16)
2967 this[offset + 1] = (value >>> 8)
2968 this[offset] = (value & 0xff)
2969 return offset + 4
2970}
2971
2972Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2973 value = +value
2974 offset = offset >>> 0
2975 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2976 this[offset] = (value >>> 24)
2977 this[offset + 1] = (value >>> 16)
2978 this[offset + 2] = (value >>> 8)
2979 this[offset + 3] = (value & 0xff)
2980 return offset + 4
2981}
2982
2983Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2984 value = +value
2985 offset = offset >>> 0
2986 if (!noAssert) {
2987 var limit = Math.pow(2, (8 * byteLength) - 1)
2988
2989 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2990 }
2991
2992 var i = 0
2993 var mul = 1
2994 var sub = 0
2995 this[offset] = value & 0xFF
2996 while (++i < byteLength && (mul *= 0x100)) {
2997 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2998 sub = 1
2999 }
3000 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3001 }
3002
3003 return offset + byteLength
3004}
3005
3006Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
3007 value = +value
3008 offset = offset >>> 0
3009 if (!noAssert) {
3010 var limit = Math.pow(2, (8 * byteLength) - 1)
3011
3012 checkInt(this, value, offset, byteLength, limit - 1, -limit)
3013 }
3014
3015 var i = byteLength - 1
3016 var mul = 1
3017 var sub = 0
3018 this[offset + i] = value & 0xFF
3019 while (--i >= 0 && (mul *= 0x100)) {
3020 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3021 sub = 1
3022 }
3023 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
3024 }
3025
3026 return offset + byteLength
3027}
3028
3029Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
3030 value = +value
3031 offset = offset >>> 0
3032 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
3033 if (value < 0) value = 0xff + value + 1
3034 this[offset] = (value & 0xff)
3035 return offset + 1
3036}
3037
3038Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
3039 value = +value
3040 offset = offset >>> 0
3041 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3042 this[offset] = (value & 0xff)
3043 this[offset + 1] = (value >>> 8)
3044 return offset + 2
3045}
3046
3047Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
3048 value = +value
3049 offset = offset >>> 0
3050 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
3051 this[offset] = (value >>> 8)
3052 this[offset + 1] = (value & 0xff)
3053 return offset + 2
3054}
3055
3056Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
3057 value = +value
3058 offset = offset >>> 0
3059 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3060 this[offset] = (value & 0xff)
3061 this[offset + 1] = (value >>> 8)
3062 this[offset + 2] = (value >>> 16)
3063 this[offset + 3] = (value >>> 24)
3064 return offset + 4
3065}
3066
3067Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
3068 value = +value
3069 offset = offset >>> 0
3070 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
3071 if (value < 0) value = 0xffffffff + value + 1
3072 this[offset] = (value >>> 24)
3073 this[offset + 1] = (value >>> 16)
3074 this[offset + 2] = (value >>> 8)
3075 this[offset + 3] = (value & 0xff)
3076 return offset + 4
3077}
3078
3079function checkIEEE754 (buf, value, offset, ext, max, min) {
3080 if (offset + ext > buf.length) throw new RangeError('Index out of range')
3081 if (offset < 0) throw new RangeError('Index out of range')
3082}
3083
3084function writeFloat (buf, value, offset, littleEndian, noAssert) {
3085 value = +value
3086 offset = offset >>> 0
3087 if (!noAssert) {
3088 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
3089 }
3090 ieee754.write(buf, value, offset, littleEndian, 23, 4)
3091 return offset + 4
3092}
3093
3094Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
3095 return writeFloat(this, value, offset, true, noAssert)
3096}
3097
3098Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
3099 return writeFloat(this, value, offset, false, noAssert)
3100}
3101
3102function writeDouble (buf, value, offset, littleEndian, noAssert) {
3103 value = +value
3104 offset = offset >>> 0
3105 if (!noAssert) {
3106 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
3107 }
3108 ieee754.write(buf, value, offset, littleEndian, 52, 8)
3109 return offset + 8
3110}
3111
3112Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
3113 return writeDouble(this, value, offset, true, noAssert)
3114}
3115
3116Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
3117 return writeDouble(this, value, offset, false, noAssert)
3118}
3119
3120// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3121Buffer.prototype.copy = function copy (target, targetStart, start, end) {
3122 if (!start) start = 0
3123 if (!end && end !== 0) end = this.length
3124 if (targetStart >= target.length) targetStart = target.length
3125 if (!targetStart) targetStart = 0
3126 if (end > 0 && end < start) end = start
3127
3128 // Copy 0 bytes; we're done
3129 if (end === start) return 0
3130 if (target.length === 0 || this.length === 0) return 0
3131
3132 // Fatal error conditions
3133 if (targetStart < 0) {
3134 throw new RangeError('targetStart out of bounds')
3135 }
3136 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
3137 if (end < 0) throw new RangeError('sourceEnd out of bounds')
3138
3139 // Are we oob?
3140 if (end > this.length) end = this.length
3141 if (target.length - targetStart < end - start) {
3142 end = target.length - targetStart + start
3143 }
3144
3145 var len = end - start
3146 var i
3147
3148 if (this === target && start < targetStart && targetStart < end) {
3149 // descending copy from end
3150 for (i = len - 1; i >= 0; --i) {
3151 target[i + targetStart] = this[i + start]
3152 }
3153 } else if (len < 1000) {
3154 // ascending copy from start
3155 for (i = 0; i < len; ++i) {
3156 target[i + targetStart] = this[i + start]
3157 }
3158 } else {
3159 Uint8Array.prototype.set.call(
3160 target,
3161 this.subarray(start, start + len),
3162 targetStart
3163 )
3164 }
3165
3166 return len
3167}
3168
3169// Usage:
3170// buffer.fill(number[, offset[, end]])
3171// buffer.fill(buffer[, offset[, end]])
3172// buffer.fill(string[, offset[, end]][, encoding])
3173Buffer.prototype.fill = function fill (val, start, end, encoding) {
3174 // Handle string cases:
3175 if (typeof val === 'string') {
3176 if (typeof start === 'string') {
3177 encoding = start
3178 start = 0
3179 end = this.length
3180 } else if (typeof end === 'string') {
3181 encoding = end
3182 end = this.length
3183 }
3184 if (val.length === 1) {
3185 var code = val.charCodeAt(0)
3186 if (code < 256) {
3187 val = code
3188 }
3189 }
3190 if (encoding !== undefined && typeof encoding !== 'string') {
3191 throw new TypeError('encoding must be a string')
3192 }
3193 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3194 throw new TypeError('Unknown encoding: ' + encoding)
3195 }
3196 } else if (typeof val === 'number') {
3197 val = val & 255
3198 }
3199
3200 // Invalid ranges are not set to a default, so can range check early.
3201 if (start < 0 || this.length < start || this.length < end) {
3202 throw new RangeError('Out of range index')
3203 }
3204
3205 if (end <= start) {
3206 return this
3207 }
3208
3209 start = start >>> 0
3210 end = end === undefined ? this.length : end >>> 0
3211
3212 if (!val) val = 0
3213
3214 var i
3215 if (typeof val === 'number') {
3216 for (i = start; i < end; ++i) {
3217 this[i] = val
3218 }
3219 } else {
3220 var bytes = Buffer.isBuffer(val)
3221 ? val
3222 : new Buffer(val, encoding)
3223 var len = bytes.length
3224 for (i = 0; i < end - start; ++i) {
3225 this[i + start] = bytes[i % len]
3226 }
3227 }
3228
3229 return this
3230}
3231
3232// HELPER FUNCTIONS
3233// ================
3234
3235var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
3236
3237function base64clean (str) {
3238 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3239 str = str.trim().replace(INVALID_BASE64_RE, '')
3240 // Node converts strings with length < 2 to ''
3241 if (str.length < 2) return ''
3242 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3243 while (str.length % 4 !== 0) {
3244 str = str + '='
3245 }
3246 return str
3247}
3248
3249function toHex (n) {
3250 if (n < 16) return '0' + n.toString(16)
3251 return n.toString(16)
3252}
3253
3254function utf8ToBytes (string, units) {
3255 units = units || Infinity
3256 var codePoint
3257 var length = string.length
3258 var leadSurrogate = null
3259 var bytes = []
3260
3261 for (var i = 0; i < length; ++i) {
3262 codePoint = string.charCodeAt(i)
3263
3264 // is surrogate component
3265 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3266 // last char was a lead
3267 if (!leadSurrogate) {
3268 // no lead yet
3269 if (codePoint > 0xDBFF) {
3270 // unexpected trail
3271 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3272 continue
3273 } else if (i + 1 === length) {
3274 // unpaired lead
3275 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3276 continue
3277 }
3278
3279 // valid lead
3280 leadSurrogate = codePoint
3281
3282 continue
3283 }
3284
3285 // 2 leads in a row
3286 if (codePoint < 0xDC00) {
3287 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3288 leadSurrogate = codePoint
3289 continue
3290 }
3291
3292 // valid surrogate pair
3293 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
3294 } else if (leadSurrogate) {
3295 // valid bmp char, but last char was a lead
3296 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
3297 }
3298
3299 leadSurrogate = null
3300
3301 // encode utf8
3302 if (codePoint < 0x80) {
3303 if ((units -= 1) < 0) break
3304 bytes.push(codePoint)
3305 } else if (codePoint < 0x800) {
3306 if ((units -= 2) < 0) break
3307 bytes.push(
3308 codePoint >> 0x6 | 0xC0,
3309 codePoint & 0x3F | 0x80
3310 )
3311 } else if (codePoint < 0x10000) {
3312 if ((units -= 3) < 0) break
3313 bytes.push(
3314 codePoint >> 0xC | 0xE0,
3315 codePoint >> 0x6 & 0x3F | 0x80,
3316 codePoint & 0x3F | 0x80
3317 )
3318 } else if (codePoint < 0x110000) {
3319 if ((units -= 4) < 0) break
3320 bytes.push(
3321 codePoint >> 0x12 | 0xF0,
3322 codePoint >> 0xC & 0x3F | 0x80,
3323 codePoint >> 0x6 & 0x3F | 0x80,
3324 codePoint & 0x3F | 0x80
3325 )
3326 } else {
3327 throw new Error('Invalid code point')
3328 }
3329 }
3330
3331 return bytes
3332}
3333
3334function asciiToBytes (str) {
3335 var byteArray = []
3336 for (var i = 0; i < str.length; ++i) {
3337 // Node's code seems to be doing this and not & 0x7F..
3338 byteArray.push(str.charCodeAt(i) & 0xFF)
3339 }
3340 return byteArray
3341}
3342
3343function utf16leToBytes (str, units) {
3344 var c, hi, lo
3345 var byteArray = []
3346 for (var i = 0; i < str.length; ++i) {
3347 if ((units -= 2) < 0) break
3348
3349 c = str.charCodeAt(i)
3350 hi = c >> 8
3351 lo = c % 256
3352 byteArray.push(lo)
3353 byteArray.push(hi)
3354 }
3355
3356 return byteArray
3357}
3358
3359function base64ToBytes (str) {
3360 return base64.toByteArray(base64clean(str))
3361}
3362
3363function blitBuffer (src, dst, offset, length) {
3364 for (var i = 0; i < length; ++i) {
3365 if ((i + offset >= dst.length) || (i >= src.length)) break
3366 dst[i + offset] = src[i]
3367 }
3368 return i
3369}
3370
3371// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
3372// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
3373function isArrayBuffer (obj) {
3374 return obj instanceof ArrayBuffer ||
3375 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
3376 typeof obj.byteLength === 'number')
3377}
3378
3379// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
3380function isArrayBufferView (obj) {
3381 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
3382}
3383
3384function numberIsNaN (obj) {
3385 return obj !== obj // eslint-disable-line no-self-compare
3386}
3387
3388},{"base64-js":2,"ieee754":21}],10:[function(require,module,exports){
3389/**
3390 * @license
3391 * https://github.com/bitcoincashjs/cashaddr
3392 * Copyright (c) 2017-2018 Emilio Almansi
3393 * Distributed under the MIT software license, see the accompanying
3394 * file LICENSE or http://www.opensource.org/licenses/mit-license.php.
3395 */
3396
3397'use strict';
3398
3399var validate = require('./validation').validate;
3400
3401/**
3402 * Base32 encoding and decoding.
3403 *
3404 * @module base32
3405 */
3406
3407/**
3408 * Charset containing the 32 symbols used in the base32 encoding.
3409 * @private
3410 */
3411var CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
3412
3413/**
3414 * Inverted index mapping each symbol into its index within the charset.
3415 * @private
3416 */
3417var CHARSET_INVERSE_INDEX = {
3418 'q': 0, 'p': 1, 'z': 2, 'r': 3, 'y': 4, '9': 5, 'x': 6, '8': 7,
3419 'g': 8, 'f': 9, '2': 10, 't': 11, 'v': 12, 'd': 13, 'w': 14, '0': 15,
3420 's': 16, '3': 17, 'j': 18, 'n': 19, '5': 20, '4': 21, 'k': 22, 'h': 23,
3421 'c': 24, 'e': 25, '6': 26, 'm': 27, 'u': 28, 'a': 29, '7': 30, 'l': 31,
3422};
3423
3424/**
3425 * Encodes the given array of 5-bit integers as a base32-encoded string.
3426 *
3427 * @static
3428 * @param {Uint8Array} data Array of integers between 0 and 31 inclusive.
3429 * @returns {string}
3430 * @throws {ValidationError}
3431 */
3432function encode(data) {
3433 validate(data instanceof Uint8Array, 'Invalid data: ' + data + '.');
3434 var base32 = '';
3435 for (var i = 0; i < data.length; ++i) {
3436 var value = data[i];
3437 validate(0 <= value && value < 32, 'Invalid value: ' + value + '.');
3438 base32 += CHARSET[value];
3439 }
3440 return base32;
3441}
3442
3443/**
3444 * Decodes the given base32-encoded string into an array of 5-bit integers.
3445 *
3446 * @static
3447 * @param {string} string
3448 * @returns {Uint8Array}
3449 * @throws {ValidationError}
3450 */
3451function decode(string) {
3452 validate(typeof string === 'string', 'Invalid base32-encoded string: ' + string + '.');
3453 var data = new Uint8Array(string.length);
3454 for (var i = 0; i < string.length; ++i) {
3455 var value = string[i];
3456 validate(value in CHARSET_INVERSE_INDEX, 'Invalid value: ' + value + '.');
3457 data[i] = CHARSET_INVERSE_INDEX[value];
3458 }
3459 return data;
3460}
3461
3462module.exports = {
3463 encode: encode,
3464 decode: decode,
3465};
3466
3467},{"./validation":13}],11:[function(require,module,exports){
3468/**
3469 * @license
3470 * https://github.com/bitcoincashjs/cashaddr
3471 * Copyright (c) 2017-2018 Emilio Almansi
3472 * Distributed under the MIT software license, see the accompanying
3473 * file LICENSE or http://www.opensource.org/licenses/mit-license.php.
3474 */
3475
3476'use strict';
3477
3478var base32 = require('./base32');
3479var bigInt = require('big-integer');
3480var convertBits = require('./convertBits');
3481var validation = require('./validation');
3482var validate = validation.validate;
3483
3484/**
3485 * Encoding and decoding of the new Cash Address format for Bitcoin Cash. <br />
3486 * Compliant with the original cashaddr specification:
3487 * {@link https://github.com/Bitcoin-UAHF/spec/blob/master/cashaddr.md}
3488 * @module cashaddr
3489 */
3490
3491/**
3492 * Encodes a hash from a given type into a Bitcoin Cash address with the given prefix.
3493 *
3494 * @static
3495 * @param {string} prefix Network prefix. E.g.: 'bitcoincash'.
3496 * @param {string} type Type of address to generate. Either 'P2PKH' or 'P2SH'.
3497 * @param {Uint8Array} hash Hash to encode represented as an array of 8-bit integers.
3498 * @returns {string}
3499 * @throws {ValidationError}
3500 */
3501function encode(prefix, type, hash) {
3502 validate(typeof prefix === 'string' && isValidPrefix(prefix), 'Invalid prefix: ' + prefix + '.');
3503 validate(typeof type === 'string', 'Invalid type: ' + type + '.');
3504 validate(hash instanceof Uint8Array, 'Invalid hash: ' + hash + '.');
3505 var prefixData = concat(prefixToUint5Array(prefix), new Uint8Array(1));
3506 var versionByte = getTypeBits(type) + getHashSizeBits(hash);
3507 var payloadData = toUint5Array(concat(new Uint8Array([versionByte]), hash));
3508 var checksumData = concat(concat(prefixData, payloadData), new Uint8Array(8));
3509 var payload = concat(payloadData, checksumToUint5Array(polymod(checksumData)));
3510 return prefix + ':' + base32.encode(payload);
3511}
3512
3513/**
3514 * Decodes the given address into its constituting prefix, type and hash. See [#encode()]{@link encode}.
3515 *
3516 * @static
3517 * @param {string} address Address to decode. E.g.: 'bitcoincash:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a'.
3518 * @returns {object}
3519 * @throws {ValidationError}
3520 */
3521function decode(address) {
3522 validate(typeof address === 'string' && hasSingleCase(address), 'Invalid address: ' + address + '.');
3523 var pieces = address.toLowerCase().split(':');
3524 validate(pieces.length === 2, 'Missing prefix: ' + address + '.');
3525 var prefix = pieces[0];
3526 var payload = base32.decode(pieces[1]);
3527 validate(validChecksum(prefix, payload), 'Invalid checksum: ' + address + '.');
3528 var payloadData = fromUint5Array(payload.subarray(0, -8));
3529 var versionByte = payloadData[0];
3530 var hash = payloadData.subarray(1);
3531 validate(getHashSize(versionByte) === hash.length * 8, 'Invalid hash size: ' + address + '.');
3532 var type = getType(versionByte);
3533 return {
3534 prefix: prefix,
3535 type: type,
3536 hash: hash,
3537 };
3538}
3539
3540/**
3541 * Error thrown when encoding or decoding fail due to invalid input.
3542 *
3543 * @constructor ValidationError
3544 * @param {string} message Error description.
3545 */
3546var ValidationError = validation.ValidationError;
3547
3548/**
3549 * Valid address prefixes.
3550 *
3551 * @private
3552 */
3553var VALID_PREFIXES = ['bitcoincash', 'bchtest', 'bchreg'];
3554
3555/**
3556 * Checks whether a string is a valid prefix; ie., it has a single letter case
3557 * and is one of 'bitcoincash', 'bchtest', or 'bchreg'.
3558 *
3559 * @private
3560 * @param {string} prefix
3561 * @returns {boolean}
3562 */
3563function isValidPrefix(prefix) {
3564 return hasSingleCase(prefix) && VALID_PREFIXES.indexOf(prefix.toLowerCase()) !== -1;
3565}
3566
3567/**
3568 * Derives an array from the given prefix to be used in the computation
3569 * of the address' checksum.
3570 *
3571 * @private
3572 * @param {string} prefix Network prefix. E.g.: 'bitcoincash'.
3573 * @returns {Uint8Array}
3574 */
3575function prefixToUint5Array(prefix) {
3576 var result = new Uint8Array(prefix.length);
3577 for (var i = 0; i < prefix.length; ++i) {
3578 result[i] = prefix[i].charCodeAt(0) & 31;
3579 }
3580 return result;
3581}
3582
3583/**
3584 * Returns an array representation of the given checksum to be encoded
3585 * within the address' payload.
3586 *
3587 * @private
3588 * @param {BigInteger} checksum Computed checksum.
3589 * @returns {Uint8Array}
3590 */
3591function checksumToUint5Array(checksum) {
3592 var result = new Uint8Array(8);
3593 for (var i = 0; i < 8; ++i) {
3594 result[7 - i] = checksum.and(31).toJSNumber();
3595 checksum = checksum.shiftRight(5);
3596 }
3597 return result;
3598}
3599
3600/**
3601 * Returns the bit representation of the given type within the version
3602 * byte.
3603 *
3604 * @private
3605 * @param {string} type Address type. Either 'P2PKH' or 'P2SH'.
3606 * @returns {number}
3607 * @throws {ValidationError}
3608 */
3609function getTypeBits(type) {
3610 switch (type) {
3611 case 'P2PKH':
3612 return 0;
3613 case 'P2SH':
3614 return 8;
3615 default:
3616 throw new ValidationError('Invalid type: ' + type + '.');
3617 }
3618}
3619
3620/**
3621 * Retrieves the address type from its bit representation within the
3622 * version byte.
3623 *
3624 * @private
3625 * @param {number} versionByte
3626 * @returns {string}
3627 * @throws {ValidationError}
3628 */
3629function getType(versionByte) {
3630 switch (versionByte & 120) {
3631 case 0:
3632 return 'P2PKH';
3633 case 8:
3634 return 'P2SH';
3635 default:
3636 throw new ValidationError('Invalid address type in version byte: ' + versionByte + '.');
3637 }
3638}
3639
3640/**
3641 * Returns the bit representation of the length in bits of the given
3642 * hash within the version byte.
3643 *
3644 * @private
3645 * @param {Uint8Array} hash Hash to encode represented as an array of 8-bit integers.
3646 * @returns {number}
3647 * @throws {ValidationError}
3648 */
3649function getHashSizeBits(hash) {
3650 switch (hash.length * 8) {
3651 case 160:
3652 return 0;
3653 case 192:
3654 return 1;
3655 case 224:
3656 return 2;
3657 case 256:
3658 return 3;
3659 case 320:
3660 return 4;
3661 case 384:
3662 return 5;
3663 case 448:
3664 return 6;
3665 case 512:
3666 return 7;
3667 default:
3668 throw new ValidationError('Invalid hash size: ' + hash.length + '.');
3669 }
3670}
3671
3672/**
3673 * Retrieves the the length in bits of the encoded hash from its bit
3674 * representation within the version byte.
3675 *
3676 * @private
3677 * @param {number} versionByte
3678 * @returns {number}
3679 */
3680function getHashSize(versionByte) {
3681 switch (versionByte & 7) {
3682 case 0:
3683 return 160;
3684 case 1:
3685 return 192;
3686 case 2:
3687 return 224;
3688 case 3:
3689 return 256;
3690 case 4:
3691 return 320;
3692 case 5:
3693 return 384;
3694 case 6:
3695 return 448;
3696 case 7:
3697 return 512;
3698 }
3699}
3700
3701/**
3702 * Converts an array of 8-bit integers into an array of 5-bit integers,
3703 * right-padding with zeroes if necessary.
3704 *
3705 * @private
3706 * @param {Uint8Array} data
3707 * @returns {Uint8Array}
3708 */
3709function toUint5Array(data) {
3710 return convertBits(data, 8, 5);
3711}
3712
3713/**
3714 * Converts an array of 5-bit integers back into an array of 8-bit integers,
3715 * removing extra zeroes left from padding if necessary.
3716 * Throws a {@link ValidationError} if input is not a zero-padded array of 8-bit integers.
3717 *
3718 * @private
3719 * @param {Uint8Array} data
3720 * @returns {Uint8Array}
3721 * @throws {ValidationError}
3722 */
3723function fromUint5Array(data) {
3724 return convertBits(data, 5, 8, true);
3725}
3726
3727/**
3728 * Returns the concatenation a and b.
3729 *
3730 * @private
3731 * @param {Uint8Array} a
3732 * @param {Uint8Array} b
3733 * @returns {Uint8Array}
3734 * @throws {ValidationError}
3735 */
3736function concat(a, b) {
3737 var ab = new Uint8Array(a.length + b.length);
3738 ab.set(a);
3739 ab.set(b, a.length);
3740 return ab;
3741}
3742
3743/**
3744 * Computes a checksum from the given input data as specified for the CashAddr
3745 * format: https://github.com/Bitcoin-UAHF/spec/blob/master/cashaddr.md.
3746 *
3747 * @private
3748 * @param {Uint8Array} data Array of 5-bit integers over which the checksum is to be computed.
3749 * @returns {BigInteger}
3750 */
3751function polymod(data) {
3752 var GENERATOR = [0x98f2bc8e61, 0x79b76d99e2, 0xf33e5fb3c4, 0xae2eabe2a8, 0x1e4f43e470];
3753 var checksum = bigInt(1);
3754 for (var i = 0; i < data.length; ++i) {
3755 var value = data[i];
3756 var topBits = checksum.shiftRight(35);
3757 checksum = checksum.and(0x07ffffffff).shiftLeft(5).xor(value);
3758 for (var j = 0; j < GENERATOR.length; ++j) {
3759 if (topBits.shiftRight(j).and(1).equals(1)) {
3760 checksum = checksum.xor(GENERATOR[j]);
3761 }
3762 }
3763 }
3764 return checksum.xor(1);
3765}
3766
3767/**
3768 * Verify that the payload has not been corrupted by checking that the
3769 * checksum is valid.
3770 *
3771 * @private
3772 * @param {string} prefix Network prefix. E.g.: 'bitcoincash'.
3773 * @param {Uint8Array} payload Array of 5-bit integers containing the address' payload.
3774 * @returns {boolean}
3775 */
3776function validChecksum(prefix, payload) {
3777 var prefixData = concat(prefixToUint5Array(prefix), new Uint8Array(1));
3778 var checksumData = concat(prefixData, payload);
3779 return polymod(checksumData).equals(0);
3780}
3781
3782/**
3783 * Returns true if, and only if, the given string contains either uppercase
3784 * or lowercase letters, but not both.
3785 *
3786 * @private
3787 * @param {string} string Input string.
3788 * @returns {boolean}
3789 */
3790function hasSingleCase(string) {
3791 return string === string.toLowerCase() || string === string.toUpperCase();
3792}
3793
3794module.exports = {
3795 encode: encode,
3796 decode: decode,
3797 ValidationError: ValidationError,
3798};
3799
3800},{"./base32":10,"./convertBits":12,"./validation":13,"big-integer":3}],12:[function(require,module,exports){
3801// Copyright (c) 2017-2018 Emilio Almansi
3802// Copyright (c) 2017 Pieter Wuille
3803//
3804// Permission is hereby granted, free of charge, to any person obtaining a copy
3805// of this software and associated documentation files (the "Software"), to deal
3806// in the Software without restriction, including without limitation the rights
3807// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3808// copies of the Software, and to permit persons to whom the Software is
3809// furnished to do so, subject to the following conditions:
3810//
3811// The above copyright notice and this permission notice shall be included in
3812// all copies or substantial portions of the Software.
3813//
3814// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3815// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3816// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3817// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3818// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3819// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3820// THE SOFTWARE.
3821
3822'use strict';
3823
3824var validate = require('./validation').validate;
3825
3826/**
3827 * Converts an array of integers made up of 'from' bits into an
3828 * array of integers made up of 'to' bits. The output array is
3829 * zero-padded if necessary, unless strict mode is true.
3830 * Throws a {@link ValidationError} if input is invalid.
3831 * Original by Pieter Wuille: https://github.com/sipa/bech32.
3832 *
3833 * @param {Uint8Array} data Array of integers made up of 'from' bits.
3834 * @param {number} from Length in bits of elements in the input array.
3835 * @param {number} to Length in bits of elements in the output array.
3836 * @param {bool} strictMode Require the conversion to be completed without padding.
3837 * @returns {Uint8Array}
3838 */
3839module.exports = function(data, from, to, strictMode) {
3840 var length = strictMode
3841 ? Math.floor(data.length * from / to)
3842 : Math.ceil(data.length * from / to);
3843 var mask = (1 << to) - 1;
3844 var result = new Uint8Array(length);
3845 var index = 0;
3846 var accumulator = 0;
3847 var bits = 0;
3848 for (var i = 0; i < data.length; ++i) {
3849 var value = data[i];
3850 validate(0 <= value && (value >> from) === 0, 'Invalid value: ' + value + '.');
3851 accumulator = (accumulator << from) | value;
3852 bits += from;
3853 while (bits >= to) {
3854 bits -= to;
3855 result[index] = (accumulator >> bits) & mask;
3856 ++index;
3857 }
3858 }
3859 if (!strictMode) {
3860 if (bits > 0) {
3861 result[index] = (accumulator << (to - bits)) & mask;
3862 ++index;
3863 }
3864 } else {
3865 validate(
3866 bits < from && ((accumulator << (to - bits)) & mask) === 0,
3867 'Input cannot be converted to ' + to + ' bits without padding, but strict mode was used.'
3868 );
3869 }
3870 return result;
3871};
3872
3873},{"./validation":13}],13:[function(require,module,exports){
3874/**
3875 * @license
3876 * https://github.com/bitcoincashjs/cashaddr
3877 * Copyright (c) 2017-2018 Emilio Almansi
3878 * Distributed under the MIT software license, see the accompanying
3879 * file LICENSE or http://www.opensource.org/licenses/mit-license.php.
3880 */
3881
3882'use strict';
3883
3884/**
3885 * Validation utility.
3886 *
3887 * @module validation
3888 */
3889
3890/**
3891 * Error thrown when encoding or decoding fail due to invalid input.
3892 *
3893 * @constructor ValidationError
3894 * @param {string} message Error description.
3895 */
3896function ValidationError(message) {
3897 var error = new Error();
3898 this.name = error.name = 'ValidationError';
3899 this.message = error.message = message;
3900 this.stack = error.stack;
3901}
3902
3903ValidationError.prototype = Object.create(Error.prototype);
3904
3905/**
3906 * Validates a given condition, throwing a {@link ValidationError} if
3907 * the given condition does not hold.
3908 *
3909 * @static
3910 * @param {boolean} condition Condition to validate.
3911 * @param {string} message Error message in case the condition does not hold.
3912 */
3913function validate(condition, message) {
3914 if (!condition) {
3915 throw new ValidationError(message);
3916 }
3917}
3918
3919module.exports = {
3920 ValidationError: ValidationError,
3921 validate: validate,
3922};
3923
3924},{}],14:[function(require,module,exports){
3925var Buffer = require('safe-buffer').Buffer
3926var Transform = require('stream').Transform
3927var StringDecoder = require('string_decoder').StringDecoder
3928var inherits = require('inherits')
3929
3930function CipherBase (hashMode) {
3931 Transform.call(this)
3932 this.hashMode = typeof hashMode === 'string'
3933 if (this.hashMode) {
3934 this[hashMode] = this._finalOrDigest
3935 } else {
3936 this.final = this._finalOrDigest
3937 }
3938 if (this._final) {
3939 this.__final = this._final
3940 this._final = null
3941 }
3942 this._decoder = null
3943 this._encoding = null
3944}
3945inherits(CipherBase, Transform)
3946
3947CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
3948 if (typeof data === 'string') {
3949 data = Buffer.from(data, inputEnc)
3950 }
3951
3952 var outData = this._update(data)
3953 if (this.hashMode) return this
3954
3955 if (outputEnc) {
3956 outData = this._toString(outData, outputEnc)
3957 }
3958
3959 return outData
3960}
3961
3962CipherBase.prototype.setAutoPadding = function () {}
3963CipherBase.prototype.getAuthTag = function () {
3964 throw new Error('trying to get auth tag in unsupported state')
3965}
3966
3967CipherBase.prototype.setAuthTag = function () {
3968 throw new Error('trying to set auth tag in unsupported state')
3969}
3970
3971CipherBase.prototype.setAAD = function () {
3972 throw new Error('trying to set aad in unsupported state')
3973}
3974
3975CipherBase.prototype._transform = function (data, _, next) {
3976 var err
3977 try {
3978 if (this.hashMode) {
3979 this._update(data)
3980 } else {
3981 this.push(this._update(data))
3982 }
3983 } catch (e) {
3984 err = e
3985 } finally {
3986 next(err)
3987 }
3988}
3989CipherBase.prototype._flush = function (done) {
3990 var err
3991 try {
3992 this.push(this.__final())
3993 } catch (e) {
3994 err = e
3995 }
3996
3997 done(err)
3998}
3999CipherBase.prototype._finalOrDigest = function (outputEnc) {
4000 var outData = this.__final() || Buffer.alloc(0)
4001 if (outputEnc) {
4002 outData = this._toString(outData, outputEnc, true)
4003 }
4004 return outData
4005}
4006
4007CipherBase.prototype._toString = function (value, enc, fin) {
4008 if (!this._decoder) {
4009 this._decoder = new StringDecoder(enc)
4010 this._encoding = enc
4011 }
4012
4013 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
4014
4015 var out = this._decoder.write(value)
4016 if (fin) {
4017 out += this._decoder.end()
4018 }
4019
4020 return out
4021}
4022
4023module.exports = CipherBase
4024
4025},{"inherits":22,"safe-buffer":41,"stream":50,"string_decoder":51}],15:[function(require,module,exports){
4026(function (Buffer){
4027// Copyright Joyent, Inc. and other Node contributors.
4028//
4029// Permission is hereby granted, free of charge, to any person obtaining a
4030// copy of this software and associated documentation files (the
4031// "Software"), to deal in the Software without restriction, including
4032// without limitation the rights to use, copy, modify, merge, publish,
4033// distribute, sublicense, and/or sell copies of the Software, and to permit
4034// persons to whom the Software is furnished to do so, subject to the
4035// following conditions:
4036//
4037// The above copyright notice and this permission notice shall be included
4038// in all copies or substantial portions of the Software.
4039//
4040// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4041// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4042// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4043// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4044// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4045// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4046// USE OR OTHER DEALINGS IN THE SOFTWARE.
4047
4048// NOTE: These type checking functions intentionally don't use `instanceof`
4049// because it is fragile and can be easily faked with `Object.create()`.
4050
4051function isArray(arg) {
4052 if (Array.isArray) {
4053 return Array.isArray(arg);
4054 }
4055 return objectToString(arg) === '[object Array]';
4056}
4057exports.isArray = isArray;
4058
4059function isBoolean(arg) {
4060 return typeof arg === 'boolean';
4061}
4062exports.isBoolean = isBoolean;
4063
4064function isNull(arg) {
4065 return arg === null;
4066}
4067exports.isNull = isNull;
4068
4069function isNullOrUndefined(arg) {
4070 return arg == null;
4071}
4072exports.isNullOrUndefined = isNullOrUndefined;
4073
4074function isNumber(arg) {
4075 return typeof arg === 'number';
4076}
4077exports.isNumber = isNumber;
4078
4079function isString(arg) {
4080 return typeof arg === 'string';
4081}
4082exports.isString = isString;
4083
4084function isSymbol(arg) {
4085 return typeof arg === 'symbol';
4086}
4087exports.isSymbol = isSymbol;
4088
4089function isUndefined(arg) {
4090 return arg === void 0;
4091}
4092exports.isUndefined = isUndefined;
4093
4094function isRegExp(re) {
4095 return objectToString(re) === '[object RegExp]';
4096}
4097exports.isRegExp = isRegExp;
4098
4099function isObject(arg) {
4100 return typeof arg === 'object' && arg !== null;
4101}
4102exports.isObject = isObject;
4103
4104function isDate(d) {
4105 return objectToString(d) === '[object Date]';
4106}
4107exports.isDate = isDate;
4108
4109function isError(e) {
4110 return (objectToString(e) === '[object Error]' || e instanceof Error);
4111}
4112exports.isError = isError;
4113
4114function isFunction(arg) {
4115 return typeof arg === 'function';
4116}
4117exports.isFunction = isFunction;
4118
4119function isPrimitive(arg) {
4120 return arg === null ||
4121 typeof arg === 'boolean' ||
4122 typeof arg === 'number' ||
4123 typeof arg === 'string' ||
4124 typeof arg === 'symbol' || // ES6 symbol
4125 typeof arg === 'undefined';
4126}
4127exports.isPrimitive = isPrimitive;
4128
4129exports.isBuffer = Buffer.isBuffer;
4130
4131function objectToString(o) {
4132 return Object.prototype.toString.call(o);
4133}
4134
4135}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
4136},{"../../is-buffer/index.js":23}],16:[function(require,module,exports){
4137(function (Buffer){
4138'use strict'
4139var inherits = require('inherits')
4140var md5 = require('./md5')
4141var RIPEMD160 = require('ripemd160')
4142var sha = require('sha.js')
4143
4144var Base = require('cipher-base')
4145
4146function HashNoConstructor (hash) {
4147 Base.call(this, 'digest')
4148
4149 this._hash = hash
4150 this.buffers = []
4151}
4152
4153inherits(HashNoConstructor, Base)
4154
4155HashNoConstructor.prototype._update = function (data) {
4156 this.buffers.push(data)
4157}
4158
4159HashNoConstructor.prototype._final = function () {
4160 var buf = Buffer.concat(this.buffers)
4161 var r = this._hash(buf)
4162 this.buffers = null
4163
4164 return r
4165}
4166
4167function Hash (hash) {
4168 Base.call(this, 'digest')
4169
4170 this._hash = hash
4171}
4172
4173inherits(Hash, Base)
4174
4175Hash.prototype._update = function (data) {
4176 this._hash.update(data)
4177}
4178
4179Hash.prototype._final = function () {
4180 return this._hash.digest()
4181}
4182
4183module.exports = function createHash (alg) {
4184 alg = alg.toLowerCase()
4185 if (alg === 'md5') return new HashNoConstructor(md5)
4186 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
4187
4188 return new Hash(sha(alg))
4189}
4190
4191}).call(this,require("buffer").Buffer)
4192},{"./md5":18,"buffer":9,"cipher-base":14,"inherits":22,"ripemd160":40,"sha.js":43}],17:[function(require,module,exports){
4193(function (Buffer){
4194'use strict'
4195var intSize = 4
4196var zeroBuffer = new Buffer(intSize)
4197zeroBuffer.fill(0)
4198
4199var charSize = 8
4200var hashSize = 16
4201
4202function toArray (buf) {
4203 if ((buf.length % intSize) !== 0) {
4204 var len = buf.length + (intSize - (buf.length % intSize))
4205 buf = Buffer.concat([buf, zeroBuffer], len)
4206 }
4207
4208 var arr = new Array(buf.length >>> 2)
4209 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
4210 arr[j] = buf.readInt32LE(i)
4211 }
4212
4213 return arr
4214}
4215
4216module.exports = function hash (buf, fn) {
4217 var arr = fn(toArray(buf), buf.length * charSize)
4218 buf = new Buffer(hashSize)
4219 for (var i = 0; i < arr.length; i++) {
4220 buf.writeInt32LE(arr[i], i << 2, true)
4221 }
4222 return buf
4223}
4224
4225}).call(this,require("buffer").Buffer)
4226},{"buffer":9}],18:[function(require,module,exports){
4227'use strict'
4228/*
4229 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
4230 * Digest Algorithm, as defined in RFC 1321.
4231 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
4232 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
4233 * Distributed under the BSD License
4234 * See http://pajhome.org.uk/crypt/md5 for more info.
4235 */
4236
4237var makeHash = require('./make-hash')
4238
4239/*
4240 * Calculate the MD5 of an array of little-endian words, and a bit length
4241 */
4242function core_md5 (x, len) {
4243 /* append padding */
4244 x[len >> 5] |= 0x80 << ((len) % 32)
4245 x[(((len + 64) >>> 9) << 4) + 14] = len
4246
4247 var a = 1732584193
4248 var b = -271733879
4249 var c = -1732584194
4250 var d = 271733878
4251
4252 for (var i = 0; i < x.length; i += 16) {
4253 var olda = a
4254 var oldb = b
4255 var oldc = c
4256 var oldd = d
4257
4258 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
4259 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
4260 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
4261 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
4262 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
4263 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
4264 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
4265 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
4266 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
4267 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
4268 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
4269 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
4270 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
4271 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
4272 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
4273 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
4274
4275 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
4276 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
4277 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
4278 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
4279 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
4280 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
4281 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
4282 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
4283 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
4284 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
4285 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
4286 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
4287 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
4288 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
4289 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
4290 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
4291
4292 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
4293 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
4294 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
4295 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
4296 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
4297 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
4298 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
4299 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
4300 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
4301 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
4302 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
4303 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
4304 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
4305 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
4306 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
4307 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
4308
4309 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
4310 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
4311 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
4312 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
4313 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
4314 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
4315 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
4316 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
4317 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
4318 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
4319 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
4320 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
4321 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
4322 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
4323 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
4324 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
4325
4326 a = safe_add(a, olda)
4327 b = safe_add(b, oldb)
4328 c = safe_add(c, oldc)
4329 d = safe_add(d, oldd)
4330 }
4331
4332 return [a, b, c, d]
4333}
4334
4335/*
4336 * These functions implement the four basic operations the algorithm uses.
4337 */
4338function md5_cmn (q, a, b, x, s, t) {
4339 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
4340}
4341
4342function md5_ff (a, b, c, d, x, s, t) {
4343 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
4344}
4345
4346function md5_gg (a, b, c, d, x, s, t) {
4347 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
4348}
4349
4350function md5_hh (a, b, c, d, x, s, t) {
4351 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
4352}
4353
4354function md5_ii (a, b, c, d, x, s, t) {
4355 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
4356}
4357
4358/*
4359 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
4360 * to work around bugs in some JS interpreters.
4361 */
4362function safe_add (x, y) {
4363 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
4364 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
4365 return (msw << 16) | (lsw & 0xFFFF)
4366}
4367
4368/*
4369 * Bitwise rotate a 32-bit number to the left.
4370 */
4371function bit_rol (num, cnt) {
4372 return (num << cnt) | (num >>> (32 - cnt))
4373}
4374
4375module.exports = function md5 (buf) {
4376 return makeHash(buf, core_md5)
4377}
4378
4379},{"./make-hash":17}],19:[function(require,module,exports){
4380// Copyright Joyent, Inc. and other Node contributors.
4381//
4382// Permission is hereby granted, free of charge, to any person obtaining a
4383// copy of this software and associated documentation files (the
4384// "Software"), to deal in the Software without restriction, including
4385// without limitation the rights to use, copy, modify, merge, publish,
4386// distribute, sublicense, and/or sell copies of the Software, and to permit
4387// persons to whom the Software is furnished to do so, subject to the
4388// following conditions:
4389//
4390// The above copyright notice and this permission notice shall be included
4391// in all copies or substantial portions of the Software.
4392//
4393// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4394// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4395// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4396// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4397// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4398// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4399// USE OR OTHER DEALINGS IN THE SOFTWARE.
4400
4401function EventEmitter() {
4402 this._events = this._events || {};
4403 this._maxListeners = this._maxListeners || undefined;
4404}
4405module.exports = EventEmitter;
4406
4407// Backwards-compat with node 0.10.x
4408EventEmitter.EventEmitter = EventEmitter;
4409
4410EventEmitter.prototype._events = undefined;
4411EventEmitter.prototype._maxListeners = undefined;
4412
4413// By default EventEmitters will print a warning if more than 10 listeners are
4414// added to it. This is a useful default which helps finding memory leaks.
4415EventEmitter.defaultMaxListeners = 10;
4416
4417// Obviously not all Emitters should be limited to 10. This function allows
4418// that to be increased. Set to zero for unlimited.
4419EventEmitter.prototype.setMaxListeners = function(n) {
4420 if (!isNumber(n) || n < 0 || isNaN(n))
4421 throw TypeError('n must be a positive number');
4422 this._maxListeners = n;
4423 return this;
4424};
4425
4426EventEmitter.prototype.emit = function(type) {
4427 var er, handler, len, args, i, listeners;
4428
4429 if (!this._events)
4430 this._events = {};
4431
4432 // If there is no 'error' event listener then throw.
4433 if (type === 'error') {
4434 if (!this._events.error ||
4435 (isObject(this._events.error) && !this._events.error.length)) {
4436 er = arguments[1];
4437 if (er instanceof Error) {
4438 throw er; // Unhandled 'error' event
4439 } else {
4440 // At least give some kind of context to the user
4441 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
4442 err.context = er;
4443 throw err;
4444 }
4445 }
4446 }
4447
4448 handler = this._events[type];
4449
4450 if (isUndefined(handler))
4451 return false;
4452
4453 if (isFunction(handler)) {
4454 switch (arguments.length) {
4455 // fast cases
4456 case 1:
4457 handler.call(this);
4458 break;
4459 case 2:
4460 handler.call(this, arguments[1]);
4461 break;
4462 case 3:
4463 handler.call(this, arguments[1], arguments[2]);
4464 break;
4465 // slower
4466 default:
4467 args = Array.prototype.slice.call(arguments, 1);
4468 handler.apply(this, args);
4469 }
4470 } else if (isObject(handler)) {
4471 args = Array.prototype.slice.call(arguments, 1);
4472 listeners = handler.slice();
4473 len = listeners.length;
4474 for (i = 0; i < len; i++)
4475 listeners[i].apply(this, args);
4476 }
4477
4478 return true;
4479};
4480
4481EventEmitter.prototype.addListener = function(type, listener) {
4482 var m;
4483
4484 if (!isFunction(listener))
4485 throw TypeError('listener must be a function');
4486
4487 if (!this._events)
4488 this._events = {};
4489
4490 // To avoid recursion in the case that type === "newListener"! Before
4491 // adding it to the listeners, first emit "newListener".
4492 if (this._events.newListener)
4493 this.emit('newListener', type,
4494 isFunction(listener.listener) ?
4495 listener.listener : listener);
4496
4497 if (!this._events[type])
4498 // Optimize the case of one listener. Don't need the extra array object.
4499 this._events[type] = listener;
4500 else if (isObject(this._events[type]))
4501 // If we've already got an array, just append.
4502 this._events[type].push(listener);
4503 else
4504 // Adding the second element, need to change to array.
4505 this._events[type] = [this._events[type], listener];
4506
4507 // Check for listener leak
4508 if (isObject(this._events[type]) && !this._events[type].warned) {
4509 if (!isUndefined(this._maxListeners)) {
4510 m = this._maxListeners;
4511 } else {
4512 m = EventEmitter.defaultMaxListeners;
4513 }
4514
4515 if (m && m > 0 && this._events[type].length > m) {
4516 this._events[type].warned = true;
4517 console.error('(node) warning: possible EventEmitter memory ' +
4518 'leak detected. %d listeners added. ' +
4519 'Use emitter.setMaxListeners() to increase limit.',
4520 this._events[type].length);
4521 if (typeof console.trace === 'function') {
4522 // not supported in IE 10
4523 console.trace();
4524 }
4525 }
4526 }
4527
4528 return this;
4529};
4530
4531EventEmitter.prototype.on = EventEmitter.prototype.addListener;
4532
4533EventEmitter.prototype.once = function(type, listener) {
4534 if (!isFunction(listener))
4535 throw TypeError('listener must be a function');
4536
4537 var fired = false;
4538
4539 function g() {
4540 this.removeListener(type, g);
4541
4542 if (!fired) {
4543 fired = true;
4544 listener.apply(this, arguments);
4545 }
4546 }
4547
4548 g.listener = listener;
4549 this.on(type, g);
4550
4551 return this;
4552};
4553
4554// emits a 'removeListener' event iff the listener was removed
4555EventEmitter.prototype.removeListener = function(type, listener) {
4556 var list, position, length, i;
4557
4558 if (!isFunction(listener))
4559 throw TypeError('listener must be a function');
4560
4561 if (!this._events || !this._events[type])
4562 return this;
4563
4564 list = this._events[type];
4565 length = list.length;
4566 position = -1;
4567
4568 if (list === listener ||
4569 (isFunction(list.listener) && list.listener === listener)) {
4570 delete this._events[type];
4571 if (this._events.removeListener)
4572 this.emit('removeListener', type, listener);
4573
4574 } else if (isObject(list)) {
4575 for (i = length; i-- > 0;) {
4576 if (list[i] === listener ||
4577 (list[i].listener && list[i].listener === listener)) {
4578 position = i;
4579 break;
4580 }
4581 }
4582
4583 if (position < 0)
4584 return this;
4585
4586 if (list.length === 1) {
4587 list.length = 0;
4588 delete this._events[type];
4589 } else {
4590 list.splice(position, 1);
4591 }
4592
4593 if (this._events.removeListener)
4594 this.emit('removeListener', type, listener);
4595 }
4596
4597 return this;
4598};
4599
4600EventEmitter.prototype.removeAllListeners = function(type) {
4601 var key, listeners;
4602
4603 if (!this._events)
4604 return this;
4605
4606 // not listening for removeListener, no need to emit
4607 if (!this._events.removeListener) {
4608 if (arguments.length === 0)
4609 this._events = {};
4610 else if (this._events[type])
4611 delete this._events[type];
4612 return this;
4613 }
4614
4615 // emit removeListener for all listeners on all events
4616 if (arguments.length === 0) {
4617 for (key in this._events) {
4618 if (key === 'removeListener') continue;
4619 this.removeAllListeners(key);
4620 }
4621 this.removeAllListeners('removeListener');
4622 this._events = {};
4623 return this;
4624 }
4625
4626 listeners = this._events[type];
4627
4628 if (isFunction(listeners)) {
4629 this.removeListener(type, listeners);
4630 } else if (listeners) {
4631 // LIFO order
4632 while (listeners.length)
4633 this.removeListener(type, listeners[listeners.length - 1]);
4634 }
4635 delete this._events[type];
4636
4637 return this;
4638};
4639
4640EventEmitter.prototype.listeners = function(type) {
4641 var ret;
4642 if (!this._events || !this._events[type])
4643 ret = [];
4644 else if (isFunction(this._events[type]))
4645 ret = [this._events[type]];
4646 else
4647 ret = this._events[type].slice();
4648 return ret;
4649};
4650
4651EventEmitter.prototype.listenerCount = function(type) {
4652 if (this._events) {
4653 var evlistener = this._events[type];
4654
4655 if (isFunction(evlistener))
4656 return 1;
4657 else if (evlistener)
4658 return evlistener.length;
4659 }
4660 return 0;
4661};
4662
4663EventEmitter.listenerCount = function(emitter, type) {
4664 return emitter.listenerCount(type);
4665};
4666
4667function isFunction(arg) {
4668 return typeof arg === 'function';
4669}
4670
4671function isNumber(arg) {
4672 return typeof arg === 'number';
4673}
4674
4675function isObject(arg) {
4676 return typeof arg === 'object' && arg !== null;
4677}
4678
4679function isUndefined(arg) {
4680 return arg === void 0;
4681}
4682
4683},{}],20:[function(require,module,exports){
4684(function (Buffer){
4685'use strict'
4686var Transform = require('stream').Transform
4687var inherits = require('inherits')
4688
4689function HashBase (blockSize) {
4690 Transform.call(this)
4691
4692 this._block = new Buffer(blockSize)
4693 this._blockSize = blockSize
4694 this._blockOffset = 0
4695 this._length = [0, 0, 0, 0]
4696
4697 this._finalized = false
4698}
4699
4700inherits(HashBase, Transform)
4701
4702HashBase.prototype._transform = function (chunk, encoding, callback) {
4703 var error = null
4704 try {
4705 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
4706 this.update(chunk)
4707 } catch (err) {
4708 error = err
4709 }
4710
4711 callback(error)
4712}
4713
4714HashBase.prototype._flush = function (callback) {
4715 var error = null
4716 try {
4717 this.push(this._digest())
4718 } catch (err) {
4719 error = err
4720 }
4721
4722 callback(error)
4723}
4724
4725HashBase.prototype.update = function (data, encoding) {
4726 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
4727 if (this._finalized) throw new Error('Digest already called')
4728 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
4729
4730 // consume data
4731 var block = this._block
4732 var offset = 0
4733 while (this._blockOffset + data.length - offset >= this._blockSize) {
4734 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
4735 this._update()
4736 this._blockOffset = 0
4737 }
4738 while (offset < data.length) block[this._blockOffset++] = data[offset++]
4739
4740 // update length
4741 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
4742 this._length[j] += carry
4743 carry = (this._length[j] / 0x0100000000) | 0
4744 if (carry > 0) this._length[j] -= 0x0100000000 * carry
4745 }
4746
4747 return this
4748}
4749
4750HashBase.prototype._update = function (data) {
4751 throw new Error('_update is not implemented')
4752}
4753
4754HashBase.prototype.digest = function (encoding) {
4755 if (this._finalized) throw new Error('Digest already called')
4756 this._finalized = true
4757
4758 var digest = this._digest()
4759 if (encoding !== undefined) digest = digest.toString(encoding)
4760 return digest
4761}
4762
4763HashBase.prototype._digest = function () {
4764 throw new Error('_digest is not implemented')
4765}
4766
4767module.exports = HashBase
4768
4769}).call(this,require("buffer").Buffer)
4770},{"buffer":9,"inherits":22,"stream":50}],21:[function(require,module,exports){
4771exports.read = function (buffer, offset, isLE, mLen, nBytes) {
4772 var e, m
4773 var eLen = nBytes * 8 - mLen - 1
4774 var eMax = (1 << eLen) - 1
4775 var eBias = eMax >> 1
4776 var nBits = -7
4777 var i = isLE ? (nBytes - 1) : 0
4778 var d = isLE ? -1 : 1
4779 var s = buffer[offset + i]
4780
4781 i += d
4782
4783 e = s & ((1 << (-nBits)) - 1)
4784 s >>= (-nBits)
4785 nBits += eLen
4786 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
4787
4788 m = e & ((1 << (-nBits)) - 1)
4789 e >>= (-nBits)
4790 nBits += mLen
4791 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
4792
4793 if (e === 0) {
4794 e = 1 - eBias
4795 } else if (e === eMax) {
4796 return m ? NaN : ((s ? -1 : 1) * Infinity)
4797 } else {
4798 m = m + Math.pow(2, mLen)
4799 e = e - eBias
4800 }
4801 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
4802}
4803
4804exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
4805 var e, m, c
4806 var eLen = nBytes * 8 - mLen - 1
4807 var eMax = (1 << eLen) - 1
4808 var eBias = eMax >> 1
4809 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
4810 var i = isLE ? 0 : (nBytes - 1)
4811 var d = isLE ? 1 : -1
4812 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
4813
4814 value = Math.abs(value)
4815
4816 if (isNaN(value) || value === Infinity) {
4817 m = isNaN(value) ? 1 : 0
4818 e = eMax
4819 } else {
4820 e = Math.floor(Math.log(value) / Math.LN2)
4821 if (value * (c = Math.pow(2, -e)) < 1) {
4822 e--
4823 c *= 2
4824 }
4825 if (e + eBias >= 1) {
4826 value += rt / c
4827 } else {
4828 value += rt * Math.pow(2, 1 - eBias)
4829 }
4830 if (value * c >= 2) {
4831 e++
4832 c /= 2
4833 }
4834
4835 if (e + eBias >= eMax) {
4836 m = 0
4837 e = eMax
4838 } else if (e + eBias >= 1) {
4839 m = (value * c - 1) * Math.pow(2, mLen)
4840 e = e + eBias
4841 } else {
4842 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
4843 e = 0
4844 }
4845 }
4846
4847 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
4848
4849 e = (e << mLen) | m
4850 eLen += mLen
4851 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
4852
4853 buffer[offset + i - d] |= s * 128
4854}
4855
4856},{}],22:[function(require,module,exports){
4857if (typeof Object.create === 'function') {
4858 // implementation from standard node.js 'util' module
4859 module.exports = function inherits(ctor, superCtor) {
4860 ctor.super_ = superCtor
4861 ctor.prototype = Object.create(superCtor.prototype, {
4862 constructor: {
4863 value: ctor,
4864 enumerable: false,
4865 writable: true,
4866 configurable: true
4867 }
4868 });
4869 };
4870} else {
4871 // old school shim for old browsers
4872 module.exports = function inherits(ctor, superCtor) {
4873 ctor.super_ = superCtor
4874 var TempCtor = function () {}
4875 TempCtor.prototype = superCtor.prototype
4876 ctor.prototype = new TempCtor()
4877 ctor.prototype.constructor = ctor
4878 }
4879}
4880
4881},{}],23:[function(require,module,exports){
4882/*!
4883 * Determine if an object is a Buffer
4884 *
4885 * @author Feross Aboukhadijeh <https://feross.org>
4886 * @license MIT
4887 */
4888
4889// The _isBuffer check is for Safari 5-7 support, because it's missing
4890// Object.prototype.constructor. Remove this eventually
4891module.exports = function (obj) {
4892 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
4893}
4894
4895function isBuffer (obj) {
4896 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
4897}
4898
4899// For Node v0.10 support. Remove this eventually.
4900function isSlowBuffer (obj) {
4901 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
4902}
4903
4904},{}],24:[function(require,module,exports){
4905var toString = {}.toString;
4906
4907module.exports = Array.isArray || function (arr) {
4908 return toString.call(arr) == '[object Array]';
4909};
4910
4911},{}],25:[function(require,module,exports){
4912(function (process){
4913'use strict';
4914
4915if (!process.version ||
4916 process.version.indexOf('v0.') === 0 ||
4917 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
4918 module.exports = nextTick;
4919} else {
4920 module.exports = process.nextTick;
4921}
4922
4923function nextTick(fn, arg1, arg2, arg3) {
4924 if (typeof fn !== 'function') {
4925 throw new TypeError('"callback" argument must be a function');
4926 }
4927 var len = arguments.length;
4928 var args, i;
4929 switch (len) {
4930 case 0:
4931 case 1:
4932 return process.nextTick(fn);
4933 case 2:
4934 return process.nextTick(function afterTickOne() {
4935 fn.call(null, arg1);
4936 });
4937 case 3:
4938 return process.nextTick(function afterTickTwo() {
4939 fn.call(null, arg1, arg2);
4940 });
4941 case 4:
4942 return process.nextTick(function afterTickThree() {
4943 fn.call(null, arg1, arg2, arg3);
4944 });
4945 default:
4946 args = new Array(len - 1);
4947 i = 0;
4948 while (i < args.length) {
4949 args[i++] = arguments[i];
4950 }
4951 return process.nextTick(function afterTick() {
4952 fn.apply(null, args);
4953 });
4954 }
4955}
4956
4957}).call(this,require('_process'))
4958},{"_process":26}],26:[function(require,module,exports){
4959// shim for using process in browser
4960var process = module.exports = {};
4961
4962// cached from whatever global is present so that test runners that stub it
4963// don't break things. But we need to wrap it in a try catch in case it is
4964// wrapped in strict mode code which doesn't define any globals. It's inside a
4965// function because try/catches deoptimize in certain engines.
4966
4967var cachedSetTimeout;
4968var cachedClearTimeout;
4969
4970function defaultSetTimout() {
4971 throw new Error('setTimeout has not been defined');
4972}
4973function defaultClearTimeout () {
4974 throw new Error('clearTimeout has not been defined');
4975}
4976(function () {
4977 try {
4978 if (typeof setTimeout === 'function') {
4979 cachedSetTimeout = setTimeout;
4980 } else {
4981 cachedSetTimeout = defaultSetTimout;
4982 }
4983 } catch (e) {
4984 cachedSetTimeout = defaultSetTimout;
4985 }
4986 try {
4987 if (typeof clearTimeout === 'function') {
4988 cachedClearTimeout = clearTimeout;
4989 } else {
4990 cachedClearTimeout = defaultClearTimeout;
4991 }
4992 } catch (e) {
4993 cachedClearTimeout = defaultClearTimeout;
4994 }
4995} ())
4996function runTimeout(fun) {
4997 if (cachedSetTimeout === setTimeout) {
4998 //normal enviroments in sane situations
4999 return setTimeout(fun, 0);
5000 }
5001 // if setTimeout wasn't available but was latter defined
5002 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
5003 cachedSetTimeout = setTimeout;
5004 return setTimeout(fun, 0);
5005 }
5006 try {
5007 // when when somebody has screwed with setTimeout but no I.E. maddness
5008 return cachedSetTimeout(fun, 0);
5009 } catch(e){
5010 try {
5011 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
5012 return cachedSetTimeout.call(null, fun, 0);
5013 } catch(e){
5014 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
5015 return cachedSetTimeout.call(this, fun, 0);
5016 }
5017 }
5018
5019
5020}
5021function runClearTimeout(marker) {
5022 if (cachedClearTimeout === clearTimeout) {
5023 //normal enviroments in sane situations
5024 return clearTimeout(marker);
5025 }
5026 // if clearTimeout wasn't available but was latter defined
5027 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
5028 cachedClearTimeout = clearTimeout;
5029 return clearTimeout(marker);
5030 }
5031 try {
5032 // when when somebody has screwed with setTimeout but no I.E. maddness
5033 return cachedClearTimeout(marker);
5034 } catch (e){
5035 try {
5036 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
5037 return cachedClearTimeout.call(null, marker);
5038 } catch (e){
5039 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
5040 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
5041 return cachedClearTimeout.call(this, marker);
5042 }
5043 }
5044
5045
5046
5047}
5048var queue = [];
5049var draining = false;
5050var currentQueue;
5051var queueIndex = -1;
5052
5053function cleanUpNextTick() {
5054 if (!draining || !currentQueue) {
5055 return;
5056 }
5057 draining = false;
5058 if (currentQueue.length) {
5059 queue = currentQueue.concat(queue);
5060 } else {
5061 queueIndex = -1;
5062 }
5063 if (queue.length) {
5064 drainQueue();
5065 }
5066}
5067
5068function drainQueue() {
5069 if (draining) {
5070 return;
5071 }
5072 var timeout = runTimeout(cleanUpNextTick);
5073 draining = true;
5074
5075 var len = queue.length;
5076 while(len) {
5077 currentQueue = queue;
5078 queue = [];
5079 while (++queueIndex < len) {
5080 if (currentQueue) {
5081 currentQueue[queueIndex].run();
5082 }
5083 }
5084 queueIndex = -1;
5085 len = queue.length;
5086 }
5087 currentQueue = null;
5088 draining = false;
5089 runClearTimeout(timeout);
5090}
5091
5092process.nextTick = function (fun) {
5093 var args = new Array(arguments.length - 1);
5094 if (arguments.length > 1) {
5095 for (var i = 1; i < arguments.length; i++) {
5096 args[i - 1] = arguments[i];
5097 }
5098 }
5099 queue.push(new Item(fun, args));
5100 if (queue.length === 1 && !draining) {
5101 runTimeout(drainQueue);
5102 }
5103};
5104
5105// v8 likes predictible objects
5106function Item(fun, array) {
5107 this.fun = fun;
5108 this.array = array;
5109}
5110Item.prototype.run = function () {
5111 this.fun.apply(null, this.array);
5112};
5113process.title = 'browser';
5114process.browser = true;
5115process.env = {};
5116process.argv = [];
5117process.version = ''; // empty string to avoid regexp issues
5118process.versions = {};
5119
5120function noop() {}
5121
5122process.on = noop;
5123process.addListener = noop;
5124process.once = noop;
5125process.off = noop;
5126process.removeListener = noop;
5127process.removeAllListeners = noop;
5128process.emit = noop;
5129process.prependListener = noop;
5130process.prependOnceListener = noop;
5131
5132process.listeners = function (name) { return [] }
5133
5134process.binding = function (name) {
5135 throw new Error('process.binding is not supported');
5136};
5137
5138process.cwd = function () { return '/' };
5139process.chdir = function (dir) {
5140 throw new Error('process.chdir is not supported');
5141};
5142process.umask = function() { return 0; };
5143
5144},{}],27:[function(require,module,exports){
5145module.exports = require('./lib/_stream_duplex.js');
5146
5147},{"./lib/_stream_duplex.js":28}],28:[function(require,module,exports){
5148// Copyright Joyent, Inc. and other Node contributors.
5149//
5150// Permission is hereby granted, free of charge, to any person obtaining a
5151// copy of this software and associated documentation files (the
5152// "Software"), to deal in the Software without restriction, including
5153// without limitation the rights to use, copy, modify, merge, publish,
5154// distribute, sublicense, and/or sell copies of the Software, and to permit
5155// persons to whom the Software is furnished to do so, subject to the
5156// following conditions:
5157//
5158// The above copyright notice and this permission notice shall be included
5159// in all copies or substantial portions of the Software.
5160//
5161// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5162// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5163// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5164// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5165// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5166// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5167// USE OR OTHER DEALINGS IN THE SOFTWARE.
5168
5169// a duplex stream is just a stream that is both readable and writable.
5170// Since JS doesn't have multiple prototypal inheritance, this class
5171// prototypally inherits from Readable, and then parasitically from
5172// Writable.
5173
5174'use strict';
5175
5176/*<replacement>*/
5177
5178var processNextTick = require('process-nextick-args');
5179/*</replacement>*/
5180
5181/*<replacement>*/
5182var objectKeys = Object.keys || function (obj) {
5183 var keys = [];
5184 for (var key in obj) {
5185 keys.push(key);
5186 }return keys;
5187};
5188/*</replacement>*/
5189
5190module.exports = Duplex;
5191
5192/*<replacement>*/
5193var util = require('core-util-is');
5194util.inherits = require('inherits');
5195/*</replacement>*/
5196
5197var Readable = require('./_stream_readable');
5198var Writable = require('./_stream_writable');
5199
5200util.inherits(Duplex, Readable);
5201
5202var keys = objectKeys(Writable.prototype);
5203for (var v = 0; v < keys.length; v++) {
5204 var method = keys[v];
5205 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
5206}
5207
5208function Duplex(options) {
5209 if (!(this instanceof Duplex)) return new Duplex(options);
5210
5211 Readable.call(this, options);
5212 Writable.call(this, options);
5213
5214 if (options && options.readable === false) this.readable = false;
5215
5216 if (options && options.writable === false) this.writable = false;
5217
5218 this.allowHalfOpen = true;
5219 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
5220
5221 this.once('end', onend);
5222}
5223
5224// the no-half-open enforcer
5225function onend() {
5226 // if we allow half-open state, or if the writable side ended,
5227 // then we're ok.
5228 if (this.allowHalfOpen || this._writableState.ended) return;
5229
5230 // no more data can be written.
5231 // But allow more writes to happen in this tick.
5232 processNextTick(onEndNT, this);
5233}
5234
5235function onEndNT(self) {
5236 self.end();
5237}
5238
5239Object.defineProperty(Duplex.prototype, 'destroyed', {
5240 get: function () {
5241 if (this._readableState === undefined || this._writableState === undefined) {
5242 return false;
5243 }
5244 return this._readableState.destroyed && this._writableState.destroyed;
5245 },
5246 set: function (value) {
5247 // we ignore the value if the stream
5248 // has not been initialized yet
5249 if (this._readableState === undefined || this._writableState === undefined) {
5250 return;
5251 }
5252
5253 // backward compatibility, the user is explicitly
5254 // managing destroyed
5255 this._readableState.destroyed = value;
5256 this._writableState.destroyed = value;
5257 }
5258});
5259
5260Duplex.prototype._destroy = function (err, cb) {
5261 this.push(null);
5262 this.end();
5263
5264 processNextTick(cb, err);
5265};
5266
5267function forEach(xs, f) {
5268 for (var i = 0, l = xs.length; i < l; i++) {
5269 f(xs[i], i);
5270 }
5271}
5272},{"./_stream_readable":30,"./_stream_writable":32,"core-util-is":15,"inherits":22,"process-nextick-args":25}],29:[function(require,module,exports){
5273// Copyright Joyent, Inc. and other Node contributors.
5274//
5275// Permission is hereby granted, free of charge, to any person obtaining a
5276// copy of this software and associated documentation files (the
5277// "Software"), to deal in the Software without restriction, including
5278// without limitation the rights to use, copy, modify, merge, publish,
5279// distribute, sublicense, and/or sell copies of the Software, and to permit
5280// persons to whom the Software is furnished to do so, subject to the
5281// following conditions:
5282//
5283// The above copyright notice and this permission notice shall be included
5284// in all copies or substantial portions of the Software.
5285//
5286// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5287// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5288// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5289// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5290// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5291// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5292// USE OR OTHER DEALINGS IN THE SOFTWARE.
5293
5294// a passthrough stream.
5295// basically just the most minimal sort of Transform stream.
5296// Every written chunk gets output as-is.
5297
5298'use strict';
5299
5300module.exports = PassThrough;
5301
5302var Transform = require('./_stream_transform');
5303
5304/*<replacement>*/
5305var util = require('core-util-is');
5306util.inherits = require('inherits');
5307/*</replacement>*/
5308
5309util.inherits(PassThrough, Transform);
5310
5311function PassThrough(options) {
5312 if (!(this instanceof PassThrough)) return new PassThrough(options);
5313
5314 Transform.call(this, options);
5315}
5316
5317PassThrough.prototype._transform = function (chunk, encoding, cb) {
5318 cb(null, chunk);
5319};
5320},{"./_stream_transform":31,"core-util-is":15,"inherits":22}],30:[function(require,module,exports){
5321(function (process,global){
5322// Copyright Joyent, Inc. and other Node contributors.
5323//
5324// Permission is hereby granted, free of charge, to any person obtaining a
5325// copy of this software and associated documentation files (the
5326// "Software"), to deal in the Software without restriction, including
5327// without limitation the rights to use, copy, modify, merge, publish,
5328// distribute, sublicense, and/or sell copies of the Software, and to permit
5329// persons to whom the Software is furnished to do so, subject to the
5330// following conditions:
5331//
5332// The above copyright notice and this permission notice shall be included
5333// in all copies or substantial portions of the Software.
5334//
5335// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5336// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5337// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5338// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5339// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5340// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5341// USE OR OTHER DEALINGS IN THE SOFTWARE.
5342
5343'use strict';
5344
5345/*<replacement>*/
5346
5347var processNextTick = require('process-nextick-args');
5348/*</replacement>*/
5349
5350module.exports = Readable;
5351
5352/*<replacement>*/
5353var isArray = require('isarray');
5354/*</replacement>*/
5355
5356/*<replacement>*/
5357var Duplex;
5358/*</replacement>*/
5359
5360Readable.ReadableState = ReadableState;
5361
5362/*<replacement>*/
5363var EE = require('events').EventEmitter;
5364
5365var EElistenerCount = function (emitter, type) {
5366 return emitter.listeners(type).length;
5367};
5368/*</replacement>*/
5369
5370/*<replacement>*/
5371var Stream = require('./internal/streams/stream');
5372/*</replacement>*/
5373
5374// TODO(bmeurer): Change this back to const once hole checks are
5375// properly optimized away early in Ignition+TurboFan.
5376/*<replacement>*/
5377var Buffer = require('safe-buffer').Buffer;
5378var OurUint8Array = global.Uint8Array || function () {};
5379function _uint8ArrayToBuffer(chunk) {
5380 return Buffer.from(chunk);
5381}
5382function _isUint8Array(obj) {
5383 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
5384}
5385/*</replacement>*/
5386
5387/*<replacement>*/
5388var util = require('core-util-is');
5389util.inherits = require('inherits');
5390/*</replacement>*/
5391
5392/*<replacement>*/
5393var debugUtil = require('util');
5394var debug = void 0;
5395if (debugUtil && debugUtil.debuglog) {
5396 debug = debugUtil.debuglog('stream');
5397} else {
5398 debug = function () {};
5399}
5400/*</replacement>*/
5401
5402var BufferList = require('./internal/streams/BufferList');
5403var destroyImpl = require('./internal/streams/destroy');
5404var StringDecoder;
5405
5406util.inherits(Readable, Stream);
5407
5408var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
5409
5410function prependListener(emitter, event, fn) {
5411 // Sadly this is not cacheable as some libraries bundle their own
5412 // event emitter implementation with them.
5413 if (typeof emitter.prependListener === 'function') {
5414 return emitter.prependListener(event, fn);
5415 } else {
5416 // This is a hack to make sure that our error handler is attached before any
5417 // userland ones. NEVER DO THIS. This is here only because this code needs
5418 // to continue to work with older versions of Node.js that do not include
5419 // the prependListener() method. The goal is to eventually remove this hack.
5420 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
5421 }
5422}
5423
5424function ReadableState(options, stream) {
5425 Duplex = Duplex || require('./_stream_duplex');
5426
5427 options = options || {};
5428
5429 // object stream flag. Used to make read(n) ignore n and to
5430 // make all the buffer merging and length checks go away
5431 this.objectMode = !!options.objectMode;
5432
5433 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
5434
5435 // the point at which it stops calling _read() to fill the buffer
5436 // Note: 0 is a valid value, means "don't call _read preemptively ever"
5437 var hwm = options.highWaterMark;
5438 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
5439 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
5440
5441 // cast to ints.
5442 this.highWaterMark = Math.floor(this.highWaterMark);
5443
5444 // A linked list is used to store data chunks instead of an array because the
5445 // linked list can remove elements from the beginning faster than
5446 // array.shift()
5447 this.buffer = new BufferList();
5448 this.length = 0;
5449 this.pipes = null;
5450 this.pipesCount = 0;
5451 this.flowing = null;
5452 this.ended = false;
5453 this.endEmitted = false;
5454 this.reading = false;
5455
5456 // a flag to be able to tell if the event 'readable'/'data' is emitted
5457 // immediately, or on a later tick. We set this to true at first, because
5458 // any actions that shouldn't happen until "later" should generally also
5459 // not happen before the first read call.
5460 this.sync = true;
5461
5462 // whenever we return null, then we set a flag to say
5463 // that we're awaiting a 'readable' event emission.
5464 this.needReadable = false;
5465 this.emittedReadable = false;
5466 this.readableListening = false;
5467 this.resumeScheduled = false;
5468
5469 // has it been destroyed
5470 this.destroyed = false;
5471
5472 // Crypto is kind of old and crusty. Historically, its default string
5473 // encoding is 'binary' so we have to make this configurable.
5474 // Everything else in the universe uses 'utf8', though.
5475 this.defaultEncoding = options.defaultEncoding || 'utf8';
5476
5477 // the number of writers that are awaiting a drain event in .pipe()s
5478 this.awaitDrain = 0;
5479
5480 // if true, a maybeReadMore has been scheduled
5481 this.readingMore = false;
5482
5483 this.decoder = null;
5484 this.encoding = null;
5485 if (options.encoding) {
5486 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
5487 this.decoder = new StringDecoder(options.encoding);
5488 this.encoding = options.encoding;
5489 }
5490}
5491
5492function Readable(options) {
5493 Duplex = Duplex || require('./_stream_duplex');
5494
5495 if (!(this instanceof Readable)) return new Readable(options);
5496
5497 this._readableState = new ReadableState(options, this);
5498
5499 // legacy
5500 this.readable = true;
5501
5502 if (options) {
5503 if (typeof options.read === 'function') this._read = options.read;
5504
5505 if (typeof options.destroy === 'function') this._destroy = options.destroy;
5506 }
5507
5508 Stream.call(this);
5509}
5510
5511Object.defineProperty(Readable.prototype, 'destroyed', {
5512 get: function () {
5513 if (this._readableState === undefined) {
5514 return false;
5515 }
5516 return this._readableState.destroyed;
5517 },
5518 set: function (value) {
5519 // we ignore the value if the stream
5520 // has not been initialized yet
5521 if (!this._readableState) {
5522 return;
5523 }
5524
5525 // backward compatibility, the user is explicitly
5526 // managing destroyed
5527 this._readableState.destroyed = value;
5528 }
5529});
5530
5531Readable.prototype.destroy = destroyImpl.destroy;
5532Readable.prototype._undestroy = destroyImpl.undestroy;
5533Readable.prototype._destroy = function (err, cb) {
5534 this.push(null);
5535 cb(err);
5536};
5537
5538// Manually shove something into the read() buffer.
5539// This returns true if the highWaterMark has not been hit yet,
5540// similar to how Writable.write() returns true if you should
5541// write() some more.
5542Readable.prototype.push = function (chunk, encoding) {
5543 var state = this._readableState;
5544 var skipChunkCheck;
5545
5546 if (!state.objectMode) {
5547 if (typeof chunk === 'string') {
5548 encoding = encoding || state.defaultEncoding;
5549 if (encoding !== state.encoding) {
5550 chunk = Buffer.from(chunk, encoding);
5551 encoding = '';
5552 }
5553 skipChunkCheck = true;
5554 }
5555 } else {
5556 skipChunkCheck = true;
5557 }
5558
5559 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
5560};
5561
5562// Unshift should *always* be something directly out of read()
5563Readable.prototype.unshift = function (chunk) {
5564 return readableAddChunk(this, chunk, null, true, false);
5565};
5566
5567function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
5568 var state = stream._readableState;
5569 if (chunk === null) {
5570 state.reading = false;
5571 onEofChunk(stream, state);
5572 } else {
5573 var er;
5574 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
5575 if (er) {
5576 stream.emit('error', er);
5577 } else if (state.objectMode || chunk && chunk.length > 0) {
5578 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
5579 chunk = _uint8ArrayToBuffer(chunk);
5580 }
5581
5582 if (addToFront) {
5583 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
5584 } else if (state.ended) {
5585 stream.emit('error', new Error('stream.push() after EOF'));
5586 } else {
5587 state.reading = false;
5588 if (state.decoder && !encoding) {
5589 chunk = state.decoder.write(chunk);
5590 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
5591 } else {
5592 addChunk(stream, state, chunk, false);
5593 }
5594 }
5595 } else if (!addToFront) {
5596 state.reading = false;
5597 }
5598 }
5599
5600 return needMoreData(state);
5601}
5602
5603function addChunk(stream, state, chunk, addToFront) {
5604 if (state.flowing && state.length === 0 && !state.sync) {
5605 stream.emit('data', chunk);
5606 stream.read(0);
5607 } else {
5608 // update the buffer info.
5609 state.length += state.objectMode ? 1 : chunk.length;
5610 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
5611
5612 if (state.needReadable) emitReadable(stream);
5613 }
5614 maybeReadMore(stream, state);
5615}
5616
5617function chunkInvalid(state, chunk) {
5618 var er;
5619 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
5620 er = new TypeError('Invalid non-string/buffer chunk');
5621 }
5622 return er;
5623}
5624
5625// if it's past the high water mark, we can push in some more.
5626// Also, if we have no data yet, we can stand some
5627// more bytes. This is to work around cases where hwm=0,
5628// such as the repl. Also, if the push() triggered a
5629// readable event, and the user called read(largeNumber) such that
5630// needReadable was set, then we ought to push more, so that another
5631// 'readable' event will be triggered.
5632function needMoreData(state) {
5633 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
5634}
5635
5636Readable.prototype.isPaused = function () {
5637 return this._readableState.flowing === false;
5638};
5639
5640// backwards compatibility.
5641Readable.prototype.setEncoding = function (enc) {
5642 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
5643 this._readableState.decoder = new StringDecoder(enc);
5644 this._readableState.encoding = enc;
5645 return this;
5646};
5647
5648// Don't raise the hwm > 8MB
5649var MAX_HWM = 0x800000;
5650function computeNewHighWaterMark(n) {
5651 if (n >= MAX_HWM) {
5652 n = MAX_HWM;
5653 } else {
5654 // Get the next highest power of 2 to prevent increasing hwm excessively in
5655 // tiny amounts
5656 n--;
5657 n |= n >>> 1;
5658 n |= n >>> 2;
5659 n |= n >>> 4;
5660 n |= n >>> 8;
5661 n |= n >>> 16;
5662 n++;
5663 }
5664 return n;
5665}
5666
5667// This function is designed to be inlinable, so please take care when making
5668// changes to the function body.
5669function howMuchToRead(n, state) {
5670 if (n <= 0 || state.length === 0 && state.ended) return 0;
5671 if (state.objectMode) return 1;
5672 if (n !== n) {
5673 // Only flow one buffer at a time
5674 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
5675 }
5676 // If we're asking for more than the current hwm, then raise the hwm.
5677 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
5678 if (n <= state.length) return n;
5679 // Don't have enough
5680 if (!state.ended) {
5681 state.needReadable = true;
5682 return 0;
5683 }
5684 return state.length;
5685}
5686
5687// you can override either this method, or the async _read(n) below.
5688Readable.prototype.read = function (n) {
5689 debug('read', n);
5690 n = parseInt(n, 10);
5691 var state = this._readableState;
5692 var nOrig = n;
5693
5694 if (n !== 0) state.emittedReadable = false;
5695
5696 // if we're doing read(0) to trigger a readable event, but we
5697 // already have a bunch of data in the buffer, then just trigger
5698 // the 'readable' event and move on.
5699 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
5700 debug('read: emitReadable', state.length, state.ended);
5701 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
5702 return null;
5703 }
5704
5705 n = howMuchToRead(n, state);
5706
5707 // if we've ended, and we're now clear, then finish it up.
5708 if (n === 0 && state.ended) {
5709 if (state.length === 0) endReadable(this);
5710 return null;
5711 }
5712
5713 // All the actual chunk generation logic needs to be
5714 // *below* the call to _read. The reason is that in certain
5715 // synthetic stream cases, such as passthrough streams, _read
5716 // may be a completely synchronous operation which may change
5717 // the state of the read buffer, providing enough data when
5718 // before there was *not* enough.
5719 //
5720 // So, the steps are:
5721 // 1. Figure out what the state of things will be after we do
5722 // a read from the buffer.
5723 //
5724 // 2. If that resulting state will trigger a _read, then call _read.
5725 // Note that this may be asynchronous, or synchronous. Yes, it is
5726 // deeply ugly to write APIs this way, but that still doesn't mean
5727 // that the Readable class should behave improperly, as streams are
5728 // designed to be sync/async agnostic.
5729 // Take note if the _read call is sync or async (ie, if the read call
5730 // has returned yet), so that we know whether or not it's safe to emit
5731 // 'readable' etc.
5732 //
5733 // 3. Actually pull the requested chunks out of the buffer and return.
5734
5735 // if we need a readable event, then we need to do some reading.
5736 var doRead = state.needReadable;
5737 debug('need readable', doRead);
5738
5739 // if we currently have less than the highWaterMark, then also read some
5740 if (state.length === 0 || state.length - n < state.highWaterMark) {
5741 doRead = true;
5742 debug('length less than watermark', doRead);
5743 }
5744
5745 // however, if we've ended, then there's no point, and if we're already
5746 // reading, then it's unnecessary.
5747 if (state.ended || state.reading) {
5748 doRead = false;
5749 debug('reading or ended', doRead);
5750 } else if (doRead) {
5751 debug('do read');
5752 state.reading = true;
5753 state.sync = true;
5754 // if the length is currently zero, then we *need* a readable event.
5755 if (state.length === 0) state.needReadable = true;
5756 // call internal read method
5757 this._read(state.highWaterMark);
5758 state.sync = false;
5759 // If _read pushed data synchronously, then `reading` will be false,
5760 // and we need to re-evaluate how much data we can return to the user.
5761 if (!state.reading) n = howMuchToRead(nOrig, state);
5762 }
5763
5764 var ret;
5765 if (n > 0) ret = fromList(n, state);else ret = null;
5766
5767 if (ret === null) {
5768 state.needReadable = true;
5769 n = 0;
5770 } else {
5771 state.length -= n;
5772 }
5773
5774 if (state.length === 0) {
5775 // If we have nothing in the buffer, then we want to know
5776 // as soon as we *do* get something into the buffer.
5777 if (!state.ended) state.needReadable = true;
5778
5779 // If we tried to read() past the EOF, then emit end on the next tick.
5780 if (nOrig !== n && state.ended) endReadable(this);
5781 }
5782
5783 if (ret !== null) this.emit('data', ret);
5784
5785 return ret;
5786};
5787
5788function onEofChunk(stream, state) {
5789 if (state.ended) return;
5790 if (state.decoder) {
5791 var chunk = state.decoder.end();
5792 if (chunk && chunk.length) {
5793 state.buffer.push(chunk);
5794 state.length += state.objectMode ? 1 : chunk.length;
5795 }
5796 }
5797 state.ended = true;
5798
5799 // emit 'readable' now to make sure it gets picked up.
5800 emitReadable(stream);
5801}
5802
5803// Don't emit readable right away in sync mode, because this can trigger
5804// another read() call => stack overflow. This way, it might trigger
5805// a nextTick recursion warning, but that's not so bad.
5806function emitReadable(stream) {
5807 var state = stream._readableState;
5808 state.needReadable = false;
5809 if (!state.emittedReadable) {
5810 debug('emitReadable', state.flowing);
5811 state.emittedReadable = true;
5812 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
5813 }
5814}
5815
5816function emitReadable_(stream) {
5817 debug('emit readable');
5818 stream.emit('readable');
5819 flow(stream);
5820}
5821
5822// at this point, the user has presumably seen the 'readable' event,
5823// and called read() to consume some data. that may have triggered
5824// in turn another _read(n) call, in which case reading = true if
5825// it's in progress.
5826// However, if we're not ended, or reading, and the length < hwm,
5827// then go ahead and try to read some more preemptively.
5828function maybeReadMore(stream, state) {
5829 if (!state.readingMore) {
5830 state.readingMore = true;
5831 processNextTick(maybeReadMore_, stream, state);
5832 }
5833}
5834
5835function maybeReadMore_(stream, state) {
5836 var len = state.length;
5837 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
5838 debug('maybeReadMore read 0');
5839 stream.read(0);
5840 if (len === state.length)
5841 // didn't get any data, stop spinning.
5842 break;else len = state.length;
5843 }
5844 state.readingMore = false;
5845}
5846
5847// abstract method. to be overridden in specific implementation classes.
5848// call cb(er, data) where data is <= n in length.
5849// for virtual (non-string, non-buffer) streams, "length" is somewhat
5850// arbitrary, and perhaps not very meaningful.
5851Readable.prototype._read = function (n) {
5852 this.emit('error', new Error('_read() is not implemented'));
5853};
5854
5855Readable.prototype.pipe = function (dest, pipeOpts) {
5856 var src = this;
5857 var state = this._readableState;
5858
5859 switch (state.pipesCount) {
5860 case 0:
5861 state.pipes = dest;
5862 break;
5863 case 1:
5864 state.pipes = [state.pipes, dest];
5865 break;
5866 default:
5867 state.pipes.push(dest);
5868 break;
5869 }
5870 state.pipesCount += 1;
5871 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
5872
5873 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
5874
5875 var endFn = doEnd ? onend : unpipe;
5876 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
5877
5878 dest.on('unpipe', onunpipe);
5879 function onunpipe(readable, unpipeInfo) {
5880 debug('onunpipe');
5881 if (readable === src) {
5882 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
5883 unpipeInfo.hasUnpiped = true;
5884 cleanup();
5885 }
5886 }
5887 }
5888
5889 function onend() {
5890 debug('onend');
5891 dest.end();
5892 }
5893
5894 // when the dest drains, it reduces the awaitDrain counter
5895 // on the source. This would be more elegant with a .once()
5896 // handler in flow(), but adding and removing repeatedly is
5897 // too slow.
5898 var ondrain = pipeOnDrain(src);
5899 dest.on('drain', ondrain);
5900
5901 var cleanedUp = false;
5902 function cleanup() {
5903 debug('cleanup');
5904 // cleanup event handlers once the pipe is broken
5905 dest.removeListener('close', onclose);
5906 dest.removeListener('finish', onfinish);
5907 dest.removeListener('drain', ondrain);
5908 dest.removeListener('error', onerror);
5909 dest.removeListener('unpipe', onunpipe);
5910 src.removeListener('end', onend);
5911 src.removeListener('end', unpipe);
5912 src.removeListener('data', ondata);
5913
5914 cleanedUp = true;
5915
5916 // if the reader is waiting for a drain event from this
5917 // specific writer, then it would cause it to never start
5918 // flowing again.
5919 // So, if this is awaiting a drain, then we just call it now.
5920 // If we don't know, then assume that we are waiting for one.
5921 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
5922 }
5923
5924 // If the user pushes more data while we're writing to dest then we'll end up
5925 // in ondata again. However, we only want to increase awaitDrain once because
5926 // dest will only emit one 'drain' event for the multiple writes.
5927 // => Introduce a guard on increasing awaitDrain.
5928 var increasedAwaitDrain = false;
5929 src.on('data', ondata);
5930 function ondata(chunk) {
5931 debug('ondata');
5932 increasedAwaitDrain = false;
5933 var ret = dest.write(chunk);
5934 if (false === ret && !increasedAwaitDrain) {
5935 // If the user unpiped during `dest.write()`, it is possible
5936 // to get stuck in a permanently paused state if that write
5937 // also returned false.
5938 // => Check whether `dest` is still a piping destination.
5939 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
5940 debug('false write response, pause', src._readableState.awaitDrain);
5941 src._readableState.awaitDrain++;
5942 increasedAwaitDrain = true;
5943 }
5944 src.pause();
5945 }
5946 }
5947
5948 // if the dest has an error, then stop piping into it.
5949 // however, don't suppress the throwing behavior for this.
5950 function onerror(er) {
5951 debug('onerror', er);
5952 unpipe();
5953 dest.removeListener('error', onerror);
5954 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
5955 }
5956
5957 // Make sure our error handler is attached before userland ones.
5958 prependListener(dest, 'error', onerror);
5959
5960 // Both close and finish should trigger unpipe, but only once.
5961 function onclose() {
5962 dest.removeListener('finish', onfinish);
5963 unpipe();
5964 }
5965 dest.once('close', onclose);
5966 function onfinish() {
5967 debug('onfinish');
5968 dest.removeListener('close', onclose);
5969 unpipe();
5970 }
5971 dest.once('finish', onfinish);
5972
5973 function unpipe() {
5974 debug('unpipe');
5975 src.unpipe(dest);
5976 }
5977
5978 // tell the dest that it's being piped to
5979 dest.emit('pipe', src);
5980
5981 // start the flow if it hasn't been started already.
5982 if (!state.flowing) {
5983 debug('pipe resume');
5984 src.resume();
5985 }
5986
5987 return dest;
5988};
5989
5990function pipeOnDrain(src) {
5991 return function () {
5992 var state = src._readableState;
5993 debug('pipeOnDrain', state.awaitDrain);
5994 if (state.awaitDrain) state.awaitDrain--;
5995 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
5996 state.flowing = true;
5997 flow(src);
5998 }
5999 };
6000}
6001
6002Readable.prototype.unpipe = function (dest) {
6003 var state = this._readableState;
6004 var unpipeInfo = { hasUnpiped: false };
6005
6006 // if we're not piping anywhere, then do nothing.
6007 if (state.pipesCount === 0) return this;
6008
6009 // just one destination. most common case.
6010 if (state.pipesCount === 1) {
6011 // passed in one, but it's not the right one.
6012 if (dest && dest !== state.pipes) return this;
6013
6014 if (!dest) dest = state.pipes;
6015
6016 // got a match.
6017 state.pipes = null;
6018 state.pipesCount = 0;
6019 state.flowing = false;
6020 if (dest) dest.emit('unpipe', this, unpipeInfo);
6021 return this;
6022 }
6023
6024 // slow case. multiple pipe destinations.
6025
6026 if (!dest) {
6027 // remove all.
6028 var dests = state.pipes;
6029 var len = state.pipesCount;
6030 state.pipes = null;
6031 state.pipesCount = 0;
6032 state.flowing = false;
6033
6034 for (var i = 0; i < len; i++) {
6035 dests[i].emit('unpipe', this, unpipeInfo);
6036 }return this;
6037 }
6038
6039 // try to find the right one.
6040 var index = indexOf(state.pipes, dest);
6041 if (index === -1) return this;
6042
6043 state.pipes.splice(index, 1);
6044 state.pipesCount -= 1;
6045 if (state.pipesCount === 1) state.pipes = state.pipes[0];
6046
6047 dest.emit('unpipe', this, unpipeInfo);
6048
6049 return this;
6050};
6051
6052// set up data events if they are asked for
6053// Ensure readable listeners eventually get something
6054Readable.prototype.on = function (ev, fn) {
6055 var res = Stream.prototype.on.call(this, ev, fn);
6056
6057 if (ev === 'data') {
6058 // Start flowing on next tick if stream isn't explicitly paused
6059 if (this._readableState.flowing !== false) this.resume();
6060 } else if (ev === 'readable') {
6061 var state = this._readableState;
6062 if (!state.endEmitted && !state.readableListening) {
6063 state.readableListening = state.needReadable = true;
6064 state.emittedReadable = false;
6065 if (!state.reading) {
6066 processNextTick(nReadingNextTick, this);
6067 } else if (state.length) {
6068 emitReadable(this);
6069 }
6070 }
6071 }
6072
6073 return res;
6074};
6075Readable.prototype.addListener = Readable.prototype.on;
6076
6077function nReadingNextTick(self) {
6078 debug('readable nexttick read 0');
6079 self.read(0);
6080}
6081
6082// pause() and resume() are remnants of the legacy readable stream API
6083// If the user uses them, then switch into old mode.
6084Readable.prototype.resume = function () {
6085 var state = this._readableState;
6086 if (!state.flowing) {
6087 debug('resume');
6088 state.flowing = true;
6089 resume(this, state);
6090 }
6091 return this;
6092};
6093
6094function resume(stream, state) {
6095 if (!state.resumeScheduled) {
6096 state.resumeScheduled = true;
6097 processNextTick(resume_, stream, state);
6098 }
6099}
6100
6101function resume_(stream, state) {
6102 if (!state.reading) {
6103 debug('resume read 0');
6104 stream.read(0);
6105 }
6106
6107 state.resumeScheduled = false;
6108 state.awaitDrain = 0;
6109 stream.emit('resume');
6110 flow(stream);
6111 if (state.flowing && !state.reading) stream.read(0);
6112}
6113
6114Readable.prototype.pause = function () {
6115 debug('call pause flowing=%j', this._readableState.flowing);
6116 if (false !== this._readableState.flowing) {
6117 debug('pause');
6118 this._readableState.flowing = false;
6119 this.emit('pause');
6120 }
6121 return this;
6122};
6123
6124function flow(stream) {
6125 var state = stream._readableState;
6126 debug('flow', state.flowing);
6127 while (state.flowing && stream.read() !== null) {}
6128}
6129
6130// wrap an old-style stream as the async data source.
6131// This is *not* part of the readable stream interface.
6132// It is an ugly unfortunate mess of history.
6133Readable.prototype.wrap = function (stream) {
6134 var state = this._readableState;
6135 var paused = false;
6136
6137 var self = this;
6138 stream.on('end', function () {
6139 debug('wrapped end');
6140 if (state.decoder && !state.ended) {
6141 var chunk = state.decoder.end();
6142 if (chunk && chunk.length) self.push(chunk);
6143 }
6144
6145 self.push(null);
6146 });
6147
6148 stream.on('data', function (chunk) {
6149 debug('wrapped data');
6150 if (state.decoder) chunk = state.decoder.write(chunk);
6151
6152 // don't skip over falsy values in objectMode
6153 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
6154
6155 var ret = self.push(chunk);
6156 if (!ret) {
6157 paused = true;
6158 stream.pause();
6159 }
6160 });
6161
6162 // proxy all the other methods.
6163 // important when wrapping filters and duplexes.
6164 for (var i in stream) {
6165 if (this[i] === undefined && typeof stream[i] === 'function') {
6166 this[i] = function (method) {
6167 return function () {
6168 return stream[method].apply(stream, arguments);
6169 };
6170 }(i);
6171 }
6172 }
6173
6174 // proxy certain important events.
6175 for (var n = 0; n < kProxyEvents.length; n++) {
6176 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
6177 }
6178
6179 // when we try to consume some more bytes, simply unpause the
6180 // underlying stream.
6181 self._read = function (n) {
6182 debug('wrapped _read', n);
6183 if (paused) {
6184 paused = false;
6185 stream.resume();
6186 }
6187 };
6188
6189 return self;
6190};
6191
6192// exposed for testing purposes only.
6193Readable._fromList = fromList;
6194
6195// Pluck off n bytes from an array of buffers.
6196// Length is the combined lengths of all the buffers in the list.
6197// This function is designed to be inlinable, so please take care when making
6198// changes to the function body.
6199function fromList(n, state) {
6200 // nothing buffered
6201 if (state.length === 0) return null;
6202
6203 var ret;
6204 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
6205 // read it all, truncate the list
6206 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
6207 state.buffer.clear();
6208 } else {
6209 // read part of list
6210 ret = fromListPartial(n, state.buffer, state.decoder);
6211 }
6212
6213 return ret;
6214}
6215
6216// Extracts only enough buffered data to satisfy the amount requested.
6217// This function is designed to be inlinable, so please take care when making
6218// changes to the function body.
6219function fromListPartial(n, list, hasStrings) {
6220 var ret;
6221 if (n < list.head.data.length) {
6222 // slice is the same for buffers and strings
6223 ret = list.head.data.slice(0, n);
6224 list.head.data = list.head.data.slice(n);
6225 } else if (n === list.head.data.length) {
6226 // first chunk is a perfect match
6227 ret = list.shift();
6228 } else {
6229 // result spans more than one buffer
6230 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
6231 }
6232 return ret;
6233}
6234
6235// Copies a specified amount of characters from the list of buffered data
6236// chunks.
6237// This function is designed to be inlinable, so please take care when making
6238// changes to the function body.
6239function copyFromBufferString(n, list) {
6240 var p = list.head;
6241 var c = 1;
6242 var ret = p.data;
6243 n -= ret.length;
6244 while (p = p.next) {
6245 var str = p.data;
6246 var nb = n > str.length ? str.length : n;
6247 if (nb === str.length) ret += str;else ret += str.slice(0, n);
6248 n -= nb;
6249 if (n === 0) {
6250 if (nb === str.length) {
6251 ++c;
6252 if (p.next) list.head = p.next;else list.head = list.tail = null;
6253 } else {
6254 list.head = p;
6255 p.data = str.slice(nb);
6256 }
6257 break;
6258 }
6259 ++c;
6260 }
6261 list.length -= c;
6262 return ret;
6263}
6264
6265// Copies a specified amount of bytes from the list of buffered data chunks.
6266// This function is designed to be inlinable, so please take care when making
6267// changes to the function body.
6268function copyFromBuffer(n, list) {
6269 var ret = Buffer.allocUnsafe(n);
6270 var p = list.head;
6271 var c = 1;
6272 p.data.copy(ret);
6273 n -= p.data.length;
6274 while (p = p.next) {
6275 var buf = p.data;
6276 var nb = n > buf.length ? buf.length : n;
6277 buf.copy(ret, ret.length - n, 0, nb);
6278 n -= nb;
6279 if (n === 0) {
6280 if (nb === buf.length) {
6281 ++c;
6282 if (p.next) list.head = p.next;else list.head = list.tail = null;
6283 } else {
6284 list.head = p;
6285 p.data = buf.slice(nb);
6286 }
6287 break;
6288 }
6289 ++c;
6290 }
6291 list.length -= c;
6292 return ret;
6293}
6294
6295function endReadable(stream) {
6296 var state = stream._readableState;
6297
6298 // If we get here before consuming all the bytes, then that is a
6299 // bug in node. Should never happen.
6300 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
6301
6302 if (!state.endEmitted) {
6303 state.ended = true;
6304 processNextTick(endReadableNT, state, stream);
6305 }
6306}
6307
6308function endReadableNT(state, stream) {
6309 // Check that we didn't get one last unshift.
6310 if (!state.endEmitted && state.length === 0) {
6311 state.endEmitted = true;
6312 stream.readable = false;
6313 stream.emit('end');
6314 }
6315}
6316
6317function forEach(xs, f) {
6318 for (var i = 0, l = xs.length; i < l; i++) {
6319 f(xs[i], i);
6320 }
6321}
6322
6323function indexOf(xs, x) {
6324 for (var i = 0, l = xs.length; i < l; i++) {
6325 if (xs[i] === x) return i;
6326 }
6327 return -1;
6328}
6329}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6330},{"./_stream_duplex":28,"./internal/streams/BufferList":33,"./internal/streams/destroy":34,"./internal/streams/stream":35,"_process":26,"core-util-is":15,"events":19,"inherits":22,"isarray":24,"process-nextick-args":25,"safe-buffer":41,"string_decoder/":51,"util":4}],31:[function(require,module,exports){
6331// Copyright Joyent, Inc. and other Node contributors.
6332//
6333// Permission is hereby granted, free of charge, to any person obtaining a
6334// copy of this software and associated documentation files (the
6335// "Software"), to deal in the Software without restriction, including
6336// without limitation the rights to use, copy, modify, merge, publish,
6337// distribute, sublicense, and/or sell copies of the Software, and to permit
6338// persons to whom the Software is furnished to do so, subject to the
6339// following conditions:
6340//
6341// The above copyright notice and this permission notice shall be included
6342// in all copies or substantial portions of the Software.
6343//
6344// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6345// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6346// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6347// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6348// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6349// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6350// USE OR OTHER DEALINGS IN THE SOFTWARE.
6351
6352// a transform stream is a readable/writable stream where you do
6353// something with the data. Sometimes it's called a "filter",
6354// but that's not a great name for it, since that implies a thing where
6355// some bits pass through, and others are simply ignored. (That would
6356// be a valid example of a transform, of course.)
6357//
6358// While the output is causally related to the input, it's not a
6359// necessarily symmetric or synchronous transformation. For example,
6360// a zlib stream might take multiple plain-text writes(), and then
6361// emit a single compressed chunk some time in the future.
6362//
6363// Here's how this works:
6364//
6365// The Transform stream has all the aspects of the readable and writable
6366// stream classes. When you write(chunk), that calls _write(chunk,cb)
6367// internally, and returns false if there's a lot of pending writes
6368// buffered up. When you call read(), that calls _read(n) until
6369// there's enough pending readable data buffered up.
6370//
6371// In a transform stream, the written data is placed in a buffer. When
6372// _read(n) is called, it transforms the queued up data, calling the
6373// buffered _write cb's as it consumes chunks. If consuming a single
6374// written chunk would result in multiple output chunks, then the first
6375// outputted bit calls the readcb, and subsequent chunks just go into
6376// the read buffer, and will cause it to emit 'readable' if necessary.
6377//
6378// This way, back-pressure is actually determined by the reading side,
6379// since _read has to be called to start processing a new chunk. However,
6380// a pathological inflate type of transform can cause excessive buffering
6381// here. For example, imagine a stream where every byte of input is
6382// interpreted as an integer from 0-255, and then results in that many
6383// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
6384// 1kb of data being output. In this case, you could write a very small
6385// amount of input, and end up with a very large amount of output. In
6386// such a pathological inflating mechanism, there'd be no way to tell
6387// the system to stop doing the transform. A single 4MB write could
6388// cause the system to run out of memory.
6389//
6390// However, even in such a pathological case, only a single written chunk
6391// would be consumed, and then the rest would wait (un-transformed) until
6392// the results of the previous transformed chunk were consumed.
6393
6394'use strict';
6395
6396module.exports = Transform;
6397
6398var Duplex = require('./_stream_duplex');
6399
6400/*<replacement>*/
6401var util = require('core-util-is');
6402util.inherits = require('inherits');
6403/*</replacement>*/
6404
6405util.inherits(Transform, Duplex);
6406
6407function TransformState(stream) {
6408 this.afterTransform = function (er, data) {
6409 return afterTransform(stream, er, data);
6410 };
6411
6412 this.needTransform = false;
6413 this.transforming = false;
6414 this.writecb = null;
6415 this.writechunk = null;
6416 this.writeencoding = null;
6417}
6418
6419function afterTransform(stream, er, data) {
6420 var ts = stream._transformState;
6421 ts.transforming = false;
6422
6423 var cb = ts.writecb;
6424
6425 if (!cb) {
6426 return stream.emit('error', new Error('write callback called multiple times'));
6427 }
6428
6429 ts.writechunk = null;
6430 ts.writecb = null;
6431
6432 if (data !== null && data !== undefined) stream.push(data);
6433
6434 cb(er);
6435
6436 var rs = stream._readableState;
6437 rs.reading = false;
6438 if (rs.needReadable || rs.length < rs.highWaterMark) {
6439 stream._read(rs.highWaterMark);
6440 }
6441}
6442
6443function Transform(options) {
6444 if (!(this instanceof Transform)) return new Transform(options);
6445
6446 Duplex.call(this, options);
6447
6448 this._transformState = new TransformState(this);
6449
6450 var stream = this;
6451
6452 // start out asking for a readable event once data is transformed.
6453 this._readableState.needReadable = true;
6454
6455 // we have implemented the _read method, and done the other things
6456 // that Readable wants before the first _read call, so unset the
6457 // sync guard flag.
6458 this._readableState.sync = false;
6459
6460 if (options) {
6461 if (typeof options.transform === 'function') this._transform = options.transform;
6462
6463 if (typeof options.flush === 'function') this._flush = options.flush;
6464 }
6465
6466 // When the writable side finishes, then flush out anything remaining.
6467 this.once('prefinish', function () {
6468 if (typeof this._flush === 'function') this._flush(function (er, data) {
6469 done(stream, er, data);
6470 });else done(stream);
6471 });
6472}
6473
6474Transform.prototype.push = function (chunk, encoding) {
6475 this._transformState.needTransform = false;
6476 return Duplex.prototype.push.call(this, chunk, encoding);
6477};
6478
6479// This is the part where you do stuff!
6480// override this function in implementation classes.
6481// 'chunk' is an input chunk.
6482//
6483// Call `push(newChunk)` to pass along transformed output
6484// to the readable side. You may call 'push' zero or more times.
6485//
6486// Call `cb(err)` when you are done with this chunk. If you pass
6487// an error, then that'll put the hurt on the whole operation. If you
6488// never call cb(), then you'll never get another chunk.
6489Transform.prototype._transform = function (chunk, encoding, cb) {
6490 throw new Error('_transform() is not implemented');
6491};
6492
6493Transform.prototype._write = function (chunk, encoding, cb) {
6494 var ts = this._transformState;
6495 ts.writecb = cb;
6496 ts.writechunk = chunk;
6497 ts.writeencoding = encoding;
6498 if (!ts.transforming) {
6499 var rs = this._readableState;
6500 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
6501 }
6502};
6503
6504// Doesn't matter what the args are here.
6505// _transform does all the work.
6506// That we got here means that the readable side wants more data.
6507Transform.prototype._read = function (n) {
6508 var ts = this._transformState;
6509
6510 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
6511 ts.transforming = true;
6512 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
6513 } else {
6514 // mark that we need a transform, so that any data that comes in
6515 // will get processed, now that we've asked for it.
6516 ts.needTransform = true;
6517 }
6518};
6519
6520Transform.prototype._destroy = function (err, cb) {
6521 var _this = this;
6522
6523 Duplex.prototype._destroy.call(this, err, function (err2) {
6524 cb(err2);
6525 _this.emit('close');
6526 });
6527};
6528
6529function done(stream, er, data) {
6530 if (er) return stream.emit('error', er);
6531
6532 if (data !== null && data !== undefined) stream.push(data);
6533
6534 // if there's nothing in the write buffer, then that means
6535 // that nothing more will ever be provided
6536 var ws = stream._writableState;
6537 var ts = stream._transformState;
6538
6539 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
6540
6541 if (ts.transforming) throw new Error('Calling transform done when still transforming');
6542
6543 return stream.push(null);
6544}
6545},{"./_stream_duplex":28,"core-util-is":15,"inherits":22}],32:[function(require,module,exports){
6546(function (process,global){
6547// Copyright Joyent, Inc. and other Node contributors.
6548//
6549// Permission is hereby granted, free of charge, to any person obtaining a
6550// copy of this software and associated documentation files (the
6551// "Software"), to deal in the Software without restriction, including
6552// without limitation the rights to use, copy, modify, merge, publish,
6553// distribute, sublicense, and/or sell copies of the Software, and to permit
6554// persons to whom the Software is furnished to do so, subject to the
6555// following conditions:
6556//
6557// The above copyright notice and this permission notice shall be included
6558// in all copies or substantial portions of the Software.
6559//
6560// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
6561// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6562// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
6563// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
6564// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
6565// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
6566// USE OR OTHER DEALINGS IN THE SOFTWARE.
6567
6568// A bit simpler than readable streams.
6569// Implement an async ._write(chunk, encoding, cb), and it'll handle all
6570// the drain event emission and buffering.
6571
6572'use strict';
6573
6574/*<replacement>*/
6575
6576var processNextTick = require('process-nextick-args');
6577/*</replacement>*/
6578
6579module.exports = Writable;
6580
6581/* <replacement> */
6582function WriteReq(chunk, encoding, cb) {
6583 this.chunk = chunk;
6584 this.encoding = encoding;
6585 this.callback = cb;
6586 this.next = null;
6587}
6588
6589// It seems a linked list but it is not
6590// there will be only 2 of these for each stream
6591function CorkedRequest(state) {
6592 var _this = this;
6593
6594 this.next = null;
6595 this.entry = null;
6596 this.finish = function () {
6597 onCorkedFinish(_this, state);
6598 };
6599}
6600/* </replacement> */
6601
6602/*<replacement>*/
6603var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
6604/*</replacement>*/
6605
6606/*<replacement>*/
6607var Duplex;
6608/*</replacement>*/
6609
6610Writable.WritableState = WritableState;
6611
6612/*<replacement>*/
6613var util = require('core-util-is');
6614util.inherits = require('inherits');
6615/*</replacement>*/
6616
6617/*<replacement>*/
6618var internalUtil = {
6619 deprecate: require('util-deprecate')
6620};
6621/*</replacement>*/
6622
6623/*<replacement>*/
6624var Stream = require('./internal/streams/stream');
6625/*</replacement>*/
6626
6627/*<replacement>*/
6628var Buffer = require('safe-buffer').Buffer;
6629var OurUint8Array = global.Uint8Array || function () {};
6630function _uint8ArrayToBuffer(chunk) {
6631 return Buffer.from(chunk);
6632}
6633function _isUint8Array(obj) {
6634 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
6635}
6636/*</replacement>*/
6637
6638var destroyImpl = require('./internal/streams/destroy');
6639
6640util.inherits(Writable, Stream);
6641
6642function nop() {}
6643
6644function WritableState(options, stream) {
6645 Duplex = Duplex || require('./_stream_duplex');
6646
6647 options = options || {};
6648
6649 // object stream flag to indicate whether or not this stream
6650 // contains buffers or objects.
6651 this.objectMode = !!options.objectMode;
6652
6653 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
6654
6655 // the point at which write() starts returning false
6656 // Note: 0 is a valid value, means that we always return false if
6657 // the entire buffer is not flushed immediately on write()
6658 var hwm = options.highWaterMark;
6659 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
6660 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
6661
6662 // cast to ints.
6663 this.highWaterMark = Math.floor(this.highWaterMark);
6664
6665 // if _final has been called
6666 this.finalCalled = false;
6667
6668 // drain event flag.
6669 this.needDrain = false;
6670 // at the start of calling end()
6671 this.ending = false;
6672 // when end() has been called, and returned
6673 this.ended = false;
6674 // when 'finish' is emitted
6675 this.finished = false;
6676
6677 // has it been destroyed
6678 this.destroyed = false;
6679
6680 // should we decode strings into buffers before passing to _write?
6681 // this is here so that some node-core streams can optimize string
6682 // handling at a lower level.
6683 var noDecode = options.decodeStrings === false;
6684 this.decodeStrings = !noDecode;
6685
6686 // Crypto is kind of old and crusty. Historically, its default string
6687 // encoding is 'binary' so we have to make this configurable.
6688 // Everything else in the universe uses 'utf8', though.
6689 this.defaultEncoding = options.defaultEncoding || 'utf8';
6690
6691 // not an actual buffer we keep track of, but a measurement
6692 // of how much we're waiting to get pushed to some underlying
6693 // socket or file.
6694 this.length = 0;
6695
6696 // a flag to see when we're in the middle of a write.
6697 this.writing = false;
6698
6699 // when true all writes will be buffered until .uncork() call
6700 this.corked = 0;
6701
6702 // a flag to be able to tell if the onwrite cb is called immediately,
6703 // or on a later tick. We set this to true at first, because any
6704 // actions that shouldn't happen until "later" should generally also
6705 // not happen before the first write call.
6706 this.sync = true;
6707
6708 // a flag to know if we're processing previously buffered items, which
6709 // may call the _write() callback in the same tick, so that we don't
6710 // end up in an overlapped onwrite situation.
6711 this.bufferProcessing = false;
6712
6713 // the callback that's passed to _write(chunk,cb)
6714 this.onwrite = function (er) {
6715 onwrite(stream, er);
6716 };
6717
6718 // the callback that the user supplies to write(chunk,encoding,cb)
6719 this.writecb = null;
6720
6721 // the amount that is being written when _write is called.
6722 this.writelen = 0;
6723
6724 this.bufferedRequest = null;
6725 this.lastBufferedRequest = null;
6726
6727 // number of pending user-supplied write callbacks
6728 // this must be 0 before 'finish' can be emitted
6729 this.pendingcb = 0;
6730
6731 // emit prefinish if the only thing we're waiting for is _write cbs
6732 // This is relevant for synchronous Transform streams
6733 this.prefinished = false;
6734
6735 // True if the error was already emitted and should not be thrown again
6736 this.errorEmitted = false;
6737
6738 // count buffered requests
6739 this.bufferedRequestCount = 0;
6740
6741 // allocate the first CorkedRequest, there is always
6742 // one allocated and free to use, and we maintain at most two
6743 this.corkedRequestsFree = new CorkedRequest(this);
6744}
6745
6746WritableState.prototype.getBuffer = function getBuffer() {
6747 var current = this.bufferedRequest;
6748 var out = [];
6749 while (current) {
6750 out.push(current);
6751 current = current.next;
6752 }
6753 return out;
6754};
6755
6756(function () {
6757 try {
6758 Object.defineProperty(WritableState.prototype, 'buffer', {
6759 get: internalUtil.deprecate(function () {
6760 return this.getBuffer();
6761 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
6762 });
6763 } catch (_) {}
6764})();
6765
6766// Test _writableState for inheritance to account for Duplex streams,
6767// whose prototype chain only points to Readable.
6768var realHasInstance;
6769if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
6770 realHasInstance = Function.prototype[Symbol.hasInstance];
6771 Object.defineProperty(Writable, Symbol.hasInstance, {
6772 value: function (object) {
6773 if (realHasInstance.call(this, object)) return true;
6774
6775 return object && object._writableState instanceof WritableState;
6776 }
6777 });
6778} else {
6779 realHasInstance = function (object) {
6780 return object instanceof this;
6781 };
6782}
6783
6784function Writable(options) {
6785 Duplex = Duplex || require('./_stream_duplex');
6786
6787 // Writable ctor is applied to Duplexes, too.
6788 // `realHasInstance` is necessary because using plain `instanceof`
6789 // would return false, as no `_writableState` property is attached.
6790
6791 // Trying to use the custom `instanceof` for Writable here will also break the
6792 // Node.js LazyTransform implementation, which has a non-trivial getter for
6793 // `_writableState` that would lead to infinite recursion.
6794 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
6795 return new Writable(options);
6796 }
6797
6798 this._writableState = new WritableState(options, this);
6799
6800 // legacy.
6801 this.writable = true;
6802
6803 if (options) {
6804 if (typeof options.write === 'function') this._write = options.write;
6805
6806 if (typeof options.writev === 'function') this._writev = options.writev;
6807
6808 if (typeof options.destroy === 'function') this._destroy = options.destroy;
6809
6810 if (typeof options.final === 'function') this._final = options.final;
6811 }
6812
6813 Stream.call(this);
6814}
6815
6816// Otherwise people can pipe Writable streams, which is just wrong.
6817Writable.prototype.pipe = function () {
6818 this.emit('error', new Error('Cannot pipe, not readable'));
6819};
6820
6821function writeAfterEnd(stream, cb) {
6822 var er = new Error('write after end');
6823 // TODO: defer error events consistently everywhere, not just the cb
6824 stream.emit('error', er);
6825 processNextTick(cb, er);
6826}
6827
6828// Checks that a user-supplied chunk is valid, especially for the particular
6829// mode the stream is in. Currently this means that `null` is never accepted
6830// and undefined/non-string values are only allowed in object mode.
6831function validChunk(stream, state, chunk, cb) {
6832 var valid = true;
6833 var er = false;
6834
6835 if (chunk === null) {
6836 er = new TypeError('May not write null values to stream');
6837 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
6838 er = new TypeError('Invalid non-string/buffer chunk');
6839 }
6840 if (er) {
6841 stream.emit('error', er);
6842 processNextTick(cb, er);
6843 valid = false;
6844 }
6845 return valid;
6846}
6847
6848Writable.prototype.write = function (chunk, encoding, cb) {
6849 var state = this._writableState;
6850 var ret = false;
6851 var isBuf = _isUint8Array(chunk) && !state.objectMode;
6852
6853 if (isBuf && !Buffer.isBuffer(chunk)) {
6854 chunk = _uint8ArrayToBuffer(chunk);
6855 }
6856
6857 if (typeof encoding === 'function') {
6858 cb = encoding;
6859 encoding = null;
6860 }
6861
6862 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
6863
6864 if (typeof cb !== 'function') cb = nop;
6865
6866 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
6867 state.pendingcb++;
6868 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
6869 }
6870
6871 return ret;
6872};
6873
6874Writable.prototype.cork = function () {
6875 var state = this._writableState;
6876
6877 state.corked++;
6878};
6879
6880Writable.prototype.uncork = function () {
6881 var state = this._writableState;
6882
6883 if (state.corked) {
6884 state.corked--;
6885
6886 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
6887 }
6888};
6889
6890Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
6891 // node::ParseEncoding() requires lower case.
6892 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
6893 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
6894 this._writableState.defaultEncoding = encoding;
6895 return this;
6896};
6897
6898function decodeChunk(state, chunk, encoding) {
6899 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
6900 chunk = Buffer.from(chunk, encoding);
6901 }
6902 return chunk;
6903}
6904
6905// if we're already writing something, then just put this
6906// in the queue, and wait our turn. Otherwise, call _write
6907// If we return false, then we need a drain event, so set that flag.
6908function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
6909 if (!isBuf) {
6910 var newChunk = decodeChunk(state, chunk, encoding);
6911 if (chunk !== newChunk) {
6912 isBuf = true;
6913 encoding = 'buffer';
6914 chunk = newChunk;
6915 }
6916 }
6917 var len = state.objectMode ? 1 : chunk.length;
6918
6919 state.length += len;
6920
6921 var ret = state.length < state.highWaterMark;
6922 // we must ensure that previous needDrain will not be reset to false.
6923 if (!ret) state.needDrain = true;
6924
6925 if (state.writing || state.corked) {
6926 var last = state.lastBufferedRequest;
6927 state.lastBufferedRequest = {
6928 chunk: chunk,
6929 encoding: encoding,
6930 isBuf: isBuf,
6931 callback: cb,
6932 next: null
6933 };
6934 if (last) {
6935 last.next = state.lastBufferedRequest;
6936 } else {
6937 state.bufferedRequest = state.lastBufferedRequest;
6938 }
6939 state.bufferedRequestCount += 1;
6940 } else {
6941 doWrite(stream, state, false, len, chunk, encoding, cb);
6942 }
6943
6944 return ret;
6945}
6946
6947function doWrite(stream, state, writev, len, chunk, encoding, cb) {
6948 state.writelen = len;
6949 state.writecb = cb;
6950 state.writing = true;
6951 state.sync = true;
6952 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
6953 state.sync = false;
6954}
6955
6956function onwriteError(stream, state, sync, er, cb) {
6957 --state.pendingcb;
6958
6959 if (sync) {
6960 // defer the callback if we are being called synchronously
6961 // to avoid piling up things on the stack
6962 processNextTick(cb, er);
6963 // this can emit finish, and it will always happen
6964 // after error
6965 processNextTick(finishMaybe, stream, state);
6966 stream._writableState.errorEmitted = true;
6967 stream.emit('error', er);
6968 } else {
6969 // the caller expect this to happen before if
6970 // it is async
6971 cb(er);
6972 stream._writableState.errorEmitted = true;
6973 stream.emit('error', er);
6974 // this can emit finish, but finish must
6975 // always follow error
6976 finishMaybe(stream, state);
6977 }
6978}
6979
6980function onwriteStateUpdate(state) {
6981 state.writing = false;
6982 state.writecb = null;
6983 state.length -= state.writelen;
6984 state.writelen = 0;
6985}
6986
6987function onwrite(stream, er) {
6988 var state = stream._writableState;
6989 var sync = state.sync;
6990 var cb = state.writecb;
6991
6992 onwriteStateUpdate(state);
6993
6994 if (er) onwriteError(stream, state, sync, er, cb);else {
6995 // Check if we're actually ready to finish, but don't emit yet
6996 var finished = needFinish(state);
6997
6998 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
6999 clearBuffer(stream, state);
7000 }
7001
7002 if (sync) {
7003 /*<replacement>*/
7004 asyncWrite(afterWrite, stream, state, finished, cb);
7005 /*</replacement>*/
7006 } else {
7007 afterWrite(stream, state, finished, cb);
7008 }
7009 }
7010}
7011
7012function afterWrite(stream, state, finished, cb) {
7013 if (!finished) onwriteDrain(stream, state);
7014 state.pendingcb--;
7015 cb();
7016 finishMaybe(stream, state);
7017}
7018
7019// Must force callback to be called on nextTick, so that we don't
7020// emit 'drain' before the write() consumer gets the 'false' return
7021// value, and has a chance to attach a 'drain' listener.
7022function onwriteDrain(stream, state) {
7023 if (state.length === 0 && state.needDrain) {
7024 state.needDrain = false;
7025 stream.emit('drain');
7026 }
7027}
7028
7029// if there's something in the buffer waiting, then process it
7030function clearBuffer(stream, state) {
7031 state.bufferProcessing = true;
7032 var entry = state.bufferedRequest;
7033
7034 if (stream._writev && entry && entry.next) {
7035 // Fast case, write everything using _writev()
7036 var l = state.bufferedRequestCount;
7037 var buffer = new Array(l);
7038 var holder = state.corkedRequestsFree;
7039 holder.entry = entry;
7040
7041 var count = 0;
7042 var allBuffers = true;
7043 while (entry) {
7044 buffer[count] = entry;
7045 if (!entry.isBuf) allBuffers = false;
7046 entry = entry.next;
7047 count += 1;
7048 }
7049 buffer.allBuffers = allBuffers;
7050
7051 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
7052
7053 // doWrite is almost always async, defer these to save a bit of time
7054 // as the hot path ends with doWrite
7055 state.pendingcb++;
7056 state.lastBufferedRequest = null;
7057 if (holder.next) {
7058 state.corkedRequestsFree = holder.next;
7059 holder.next = null;
7060 } else {
7061 state.corkedRequestsFree = new CorkedRequest(state);
7062 }
7063 } else {
7064 // Slow case, write chunks one-by-one
7065 while (entry) {
7066 var chunk = entry.chunk;
7067 var encoding = entry.encoding;
7068 var cb = entry.callback;
7069 var len = state.objectMode ? 1 : chunk.length;
7070
7071 doWrite(stream, state, false, len, chunk, encoding, cb);
7072 entry = entry.next;
7073 // if we didn't call the onwrite immediately, then
7074 // it means that we need to wait until it does.
7075 // also, that means that the chunk and cb are currently
7076 // being processed, so move the buffer counter past them.
7077 if (state.writing) {
7078 break;
7079 }
7080 }
7081
7082 if (entry === null) state.lastBufferedRequest = null;
7083 }
7084
7085 state.bufferedRequestCount = 0;
7086 state.bufferedRequest = entry;
7087 state.bufferProcessing = false;
7088}
7089
7090Writable.prototype._write = function (chunk, encoding, cb) {
7091 cb(new Error('_write() is not implemented'));
7092};
7093
7094Writable.prototype._writev = null;
7095
7096Writable.prototype.end = function (chunk, encoding, cb) {
7097 var state = this._writableState;
7098
7099 if (typeof chunk === 'function') {
7100 cb = chunk;
7101 chunk = null;
7102 encoding = null;
7103 } else if (typeof encoding === 'function') {
7104 cb = encoding;
7105 encoding = null;
7106 }
7107
7108 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
7109
7110 // .end() fully uncorks
7111 if (state.corked) {
7112 state.corked = 1;
7113 this.uncork();
7114 }
7115
7116 // ignore unnecessary end() calls.
7117 if (!state.ending && !state.finished) endWritable(this, state, cb);
7118};
7119
7120function needFinish(state) {
7121 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
7122}
7123function callFinal(stream, state) {
7124 stream._final(function (err) {
7125 state.pendingcb--;
7126 if (err) {
7127 stream.emit('error', err);
7128 }
7129 state.prefinished = true;
7130 stream.emit('prefinish');
7131 finishMaybe(stream, state);
7132 });
7133}
7134function prefinish(stream, state) {
7135 if (!state.prefinished && !state.finalCalled) {
7136 if (typeof stream._final === 'function') {
7137 state.pendingcb++;
7138 state.finalCalled = true;
7139 processNextTick(callFinal, stream, state);
7140 } else {
7141 state.prefinished = true;
7142 stream.emit('prefinish');
7143 }
7144 }
7145}
7146
7147function finishMaybe(stream, state) {
7148 var need = needFinish(state);
7149 if (need) {
7150 prefinish(stream, state);
7151 if (state.pendingcb === 0) {
7152 state.finished = true;
7153 stream.emit('finish');
7154 }
7155 }
7156 return need;
7157}
7158
7159function endWritable(stream, state, cb) {
7160 state.ending = true;
7161 finishMaybe(stream, state);
7162 if (cb) {
7163 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
7164 }
7165 state.ended = true;
7166 stream.writable = false;
7167}
7168
7169function onCorkedFinish(corkReq, state, err) {
7170 var entry = corkReq.entry;
7171 corkReq.entry = null;
7172 while (entry) {
7173 var cb = entry.callback;
7174 state.pendingcb--;
7175 cb(err);
7176 entry = entry.next;
7177 }
7178 if (state.corkedRequestsFree) {
7179 state.corkedRequestsFree.next = corkReq;
7180 } else {
7181 state.corkedRequestsFree = corkReq;
7182 }
7183}
7184
7185Object.defineProperty(Writable.prototype, 'destroyed', {
7186 get: function () {
7187 if (this._writableState === undefined) {
7188 return false;
7189 }
7190 return this._writableState.destroyed;
7191 },
7192 set: function (value) {
7193 // we ignore the value if the stream
7194 // has not been initialized yet
7195 if (!this._writableState) {
7196 return;
7197 }
7198
7199 // backward compatibility, the user is explicitly
7200 // managing destroyed
7201 this._writableState.destroyed = value;
7202 }
7203});
7204
7205Writable.prototype.destroy = destroyImpl.destroy;
7206Writable.prototype._undestroy = destroyImpl.undestroy;
7207Writable.prototype._destroy = function (err, cb) {
7208 this.end();
7209 cb(err);
7210};
7211}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7212},{"./_stream_duplex":28,"./internal/streams/destroy":34,"./internal/streams/stream":35,"_process":26,"core-util-is":15,"inherits":22,"process-nextick-args":25,"safe-buffer":41,"util-deprecate":52}],33:[function(require,module,exports){
7213'use strict';
7214
7215/*<replacement>*/
7216
7217function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
7218
7219var Buffer = require('safe-buffer').Buffer;
7220/*</replacement>*/
7221
7222function copyBuffer(src, target, offset) {
7223 src.copy(target, offset);
7224}
7225
7226module.exports = function () {
7227 function BufferList() {
7228 _classCallCheck(this, BufferList);
7229
7230 this.head = null;
7231 this.tail = null;
7232 this.length = 0;
7233 }
7234
7235 BufferList.prototype.push = function push(v) {
7236 var entry = { data: v, next: null };
7237 if (this.length > 0) this.tail.next = entry;else this.head = entry;
7238 this.tail = entry;
7239 ++this.length;
7240 };
7241
7242 BufferList.prototype.unshift = function unshift(v) {
7243 var entry = { data: v, next: this.head };
7244 if (this.length === 0) this.tail = entry;
7245 this.head = entry;
7246 ++this.length;
7247 };
7248
7249 BufferList.prototype.shift = function shift() {
7250 if (this.length === 0) return;
7251 var ret = this.head.data;
7252 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
7253 --this.length;
7254 return ret;
7255 };
7256
7257 BufferList.prototype.clear = function clear() {
7258 this.head = this.tail = null;
7259 this.length = 0;
7260 };
7261
7262 BufferList.prototype.join = function join(s) {
7263 if (this.length === 0) return '';
7264 var p = this.head;
7265 var ret = '' + p.data;
7266 while (p = p.next) {
7267 ret += s + p.data;
7268 }return ret;
7269 };
7270
7271 BufferList.prototype.concat = function concat(n) {
7272 if (this.length === 0) return Buffer.alloc(0);
7273 if (this.length === 1) return this.head.data;
7274 var ret = Buffer.allocUnsafe(n >>> 0);
7275 var p = this.head;
7276 var i = 0;
7277 while (p) {
7278 copyBuffer(p.data, ret, i);
7279 i += p.data.length;
7280 p = p.next;
7281 }
7282 return ret;
7283 };
7284
7285 return BufferList;
7286}();
7287},{"safe-buffer":41}],34:[function(require,module,exports){
7288'use strict';
7289
7290/*<replacement>*/
7291
7292var processNextTick = require('process-nextick-args');
7293/*</replacement>*/
7294
7295// undocumented cb() API, needed for core, not for public API
7296function destroy(err, cb) {
7297 var _this = this;
7298
7299 var readableDestroyed = this._readableState && this._readableState.destroyed;
7300 var writableDestroyed = this._writableState && this._writableState.destroyed;
7301
7302 if (readableDestroyed || writableDestroyed) {
7303 if (cb) {
7304 cb(err);
7305 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
7306 processNextTick(emitErrorNT, this, err);
7307 }
7308 return;
7309 }
7310
7311 // we set destroyed to true before firing error callbacks in order
7312 // to make it re-entrance safe in case destroy() is called within callbacks
7313
7314 if (this._readableState) {
7315 this._readableState.destroyed = true;
7316 }
7317
7318 // if this is a duplex stream mark the writable part as destroyed as well
7319 if (this._writableState) {
7320 this._writableState.destroyed = true;
7321 }
7322
7323 this._destroy(err || null, function (err) {
7324 if (!cb && err) {
7325 processNextTick(emitErrorNT, _this, err);
7326 if (_this._writableState) {
7327 _this._writableState.errorEmitted = true;
7328 }
7329 } else if (cb) {
7330 cb(err);
7331 }
7332 });
7333}
7334
7335function undestroy() {
7336 if (this._readableState) {
7337 this._readableState.destroyed = false;
7338 this._readableState.reading = false;
7339 this._readableState.ended = false;
7340 this._readableState.endEmitted = false;
7341 }
7342
7343 if (this._writableState) {
7344 this._writableState.destroyed = false;
7345 this._writableState.ended = false;
7346 this._writableState.ending = false;
7347 this._writableState.finished = false;
7348 this._writableState.errorEmitted = false;
7349 }
7350}
7351
7352function emitErrorNT(self, err) {
7353 self.emit('error', err);
7354}
7355
7356module.exports = {
7357 destroy: destroy,
7358 undestroy: undestroy
7359};
7360},{"process-nextick-args":25}],35:[function(require,module,exports){
7361module.exports = require('events').EventEmitter;
7362
7363},{"events":19}],36:[function(require,module,exports){
7364module.exports = require('./readable').PassThrough
7365
7366},{"./readable":37}],37:[function(require,module,exports){
7367exports = module.exports = require('./lib/_stream_readable.js');
7368exports.Stream = exports;
7369exports.Readable = exports;
7370exports.Writable = require('./lib/_stream_writable.js');
7371exports.Duplex = require('./lib/_stream_duplex.js');
7372exports.Transform = require('./lib/_stream_transform.js');
7373exports.PassThrough = require('./lib/_stream_passthrough.js');
7374
7375},{"./lib/_stream_duplex.js":28,"./lib/_stream_passthrough.js":29,"./lib/_stream_readable.js":30,"./lib/_stream_transform.js":31,"./lib/_stream_writable.js":32}],38:[function(require,module,exports){
7376module.exports = require('./readable').Transform
7377
7378},{"./readable":37}],39:[function(require,module,exports){
7379module.exports = require('./lib/_stream_writable.js');
7380
7381},{"./lib/_stream_writable.js":32}],40:[function(require,module,exports){
7382(function (Buffer){
7383'use strict'
7384var inherits = require('inherits')
7385var HashBase = require('hash-base')
7386
7387function RIPEMD160 () {
7388 HashBase.call(this, 64)
7389
7390 // state
7391 this._a = 0x67452301
7392 this._b = 0xefcdab89
7393 this._c = 0x98badcfe
7394 this._d = 0x10325476
7395 this._e = 0xc3d2e1f0
7396}
7397
7398inherits(RIPEMD160, HashBase)
7399
7400RIPEMD160.prototype._update = function () {
7401 var m = new Array(16)
7402 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
7403
7404 var al = this._a
7405 var bl = this._b
7406 var cl = this._c
7407 var dl = this._d
7408 var el = this._e
7409
7410 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
7411 // K = 0x00000000
7412 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
7413 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
7414 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
7415 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
7416 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
7417 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
7418 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
7419 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
7420 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
7421 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
7422 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
7423 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
7424 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
7425 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
7426 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
7427 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
7428 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
7429
7430 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
7431 // K = 0x5a827999
7432 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
7433 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
7434 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
7435 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
7436 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
7437 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
7438 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
7439 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
7440 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
7441 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
7442 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
7443 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
7444 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
7445 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
7446 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
7447 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
7448 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
7449
7450 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
7451 // K = 0x6ed9eba1
7452 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
7453 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
7454 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
7455 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
7456 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
7457 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
7458 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
7459 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
7460 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
7461 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
7462 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
7463 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
7464 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
7465 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
7466 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
7467 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
7468 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
7469
7470 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
7471 // K = 0x8f1bbcdc
7472 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
7473 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
7474 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
7475 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
7476 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
7477 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
7478 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
7479 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
7480 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
7481 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
7482 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
7483 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
7484 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
7485 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
7486 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
7487 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
7488 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
7489
7490 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
7491 // K = 0xa953fd4e
7492 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
7493 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
7494 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
7495 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
7496 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
7497 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
7498 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
7499 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
7500 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
7501 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
7502 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
7503 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
7504 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
7505 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
7506 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
7507 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
7508 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
7509
7510 var ar = this._a
7511 var br = this._b
7512 var cr = this._c
7513 var dr = this._d
7514 var er = this._e
7515
7516 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
7517 // K' = 0x50a28be6
7518 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
7519 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
7520 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
7521 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
7522 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
7523 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
7524 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
7525 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
7526 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
7527 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
7528 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
7529 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
7530 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
7531 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
7532 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
7533 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
7534 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
7535
7536 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
7537 // K' = 0x5c4dd124
7538 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
7539 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
7540 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
7541 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
7542 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
7543 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
7544 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
7545 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
7546 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
7547 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
7548 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
7549 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
7550 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
7551 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
7552 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
7553 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
7554 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
7555
7556 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
7557 // K' = 0x6d703ef3
7558 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
7559 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
7560 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
7561 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
7562 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
7563 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
7564 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
7565 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
7566 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
7567 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
7568 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
7569 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
7570 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
7571 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
7572 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
7573 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
7574 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
7575
7576 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
7577 // K' = 0x7a6d76e9
7578 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
7579 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
7580 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
7581 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
7582 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
7583 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
7584 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
7585 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
7586 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
7587 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
7588 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
7589 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
7590 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
7591 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
7592 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
7593 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
7594 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
7595
7596 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
7597 // K' = 0x00000000
7598 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
7599 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
7600 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
7601 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
7602 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
7603 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
7604 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
7605 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
7606 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
7607 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
7608 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
7609 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
7610 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
7611 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
7612 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
7613 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
7614 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
7615
7616 // change state
7617 var t = (this._b + cl + dr) | 0
7618 this._b = (this._c + dl + er) | 0
7619 this._c = (this._d + el + ar) | 0
7620 this._d = (this._e + al + br) | 0
7621 this._e = (this._a + bl + cr) | 0
7622 this._a = t
7623}
7624
7625RIPEMD160.prototype._digest = function () {
7626 // create padding and handle blocks
7627 this._block[this._blockOffset++] = 0x80
7628 if (this._blockOffset > 56) {
7629 this._block.fill(0, this._blockOffset, 64)
7630 this._update()
7631 this._blockOffset = 0
7632 }
7633
7634 this._block.fill(0, this._blockOffset, 56)
7635 this._block.writeUInt32LE(this._length[0], 56)
7636 this._block.writeUInt32LE(this._length[1], 60)
7637 this._update()
7638
7639 // produce result
7640 var buffer = new Buffer(20)
7641 buffer.writeInt32LE(this._a, 0)
7642 buffer.writeInt32LE(this._b, 4)
7643 buffer.writeInt32LE(this._c, 8)
7644 buffer.writeInt32LE(this._d, 12)
7645 buffer.writeInt32LE(this._e, 16)
7646 return buffer
7647}
7648
7649function rotl (x, n) {
7650 return (x << n) | (x >>> (32 - n))
7651}
7652
7653function fn1 (a, b, c, d, e, m, k, s) {
7654 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
7655}
7656
7657function fn2 (a, b, c, d, e, m, k, s) {
7658 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
7659}
7660
7661function fn3 (a, b, c, d, e, m, k, s) {
7662 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
7663}
7664
7665function fn4 (a, b, c, d, e, m, k, s) {
7666 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
7667}
7668
7669function fn5 (a, b, c, d, e, m, k, s) {
7670 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
7671}
7672
7673module.exports = RIPEMD160
7674
7675}).call(this,require("buffer").Buffer)
7676},{"buffer":9,"hash-base":20,"inherits":22}],41:[function(require,module,exports){
7677arguments[4][8][0].apply(exports,arguments)
7678},{"buffer":9,"dup":8}],42:[function(require,module,exports){
7679var Buffer = require('safe-buffer').Buffer
7680
7681// prototype class for hash functions
7682function Hash (blockSize, finalSize) {
7683 this._block = Buffer.alloc(blockSize)
7684 this._finalSize = finalSize
7685 this._blockSize = blockSize
7686 this._len = 0
7687}
7688
7689Hash.prototype.update = function (data, enc) {
7690 if (typeof data === 'string') {
7691 enc = enc || 'utf8'
7692 data = Buffer.from(data, enc)
7693 }
7694
7695 var block = this._block
7696 var blockSize = this._blockSize
7697 var length = data.length
7698 var accum = this._len
7699
7700 for (var offset = 0; offset < length;) {
7701 var assigned = accum % blockSize
7702 var remainder = Math.min(length - offset, blockSize - assigned)
7703
7704 for (var i = 0; i < remainder; i++) {
7705 block[assigned + i] = data[offset + i]
7706 }
7707
7708 accum += remainder
7709 offset += remainder
7710
7711 if ((accum % blockSize) === 0) {
7712 this._update(block)
7713 }
7714 }
7715
7716 this._len += length
7717 return this
7718}
7719
7720Hash.prototype.digest = function (enc) {
7721 var rem = this._len % this._blockSize
7722
7723 this._block[rem] = 0x80
7724
7725 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
7726 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
7727 this._block.fill(0, rem + 1)
7728
7729 if (rem >= this._finalSize) {
7730 this._update(this._block)
7731 this._block.fill(0)
7732 }
7733
7734 var bits = this._len * 8
7735
7736 // uint32
7737 if (bits <= 0xffffffff) {
7738 this._block.writeUInt32BE(bits, this._blockSize - 4)
7739
7740 // uint64
7741 } else {
7742 var lowBits = bits & 0xffffffff
7743 var highBits = (bits - lowBits) / 0x100000000
7744
7745 this._block.writeUInt32BE(highBits, this._blockSize - 8)
7746 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
7747 }
7748
7749 this._update(this._block)
7750 var hash = this._hash()
7751
7752 return enc ? hash.toString(enc) : hash
7753}
7754
7755Hash.prototype._update = function () {
7756 throw new Error('_update must be implemented by subclass')
7757}
7758
7759module.exports = Hash
7760
7761},{"safe-buffer":41}],43:[function(require,module,exports){
7762var exports = module.exports = function SHA (algorithm) {
7763 algorithm = algorithm.toLowerCase()
7764
7765 var Algorithm = exports[algorithm]
7766 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
7767
7768 return new Algorithm()
7769}
7770
7771exports.sha = require('./sha')
7772exports.sha1 = require('./sha1')
7773exports.sha224 = require('./sha224')
7774exports.sha256 = require('./sha256')
7775exports.sha384 = require('./sha384')
7776exports.sha512 = require('./sha512')
7777
7778},{"./sha":44,"./sha1":45,"./sha224":46,"./sha256":47,"./sha384":48,"./sha512":49}],44:[function(require,module,exports){
7779/*
7780 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
7781 * in FIPS PUB 180-1
7782 * This source code is derived from sha1.js of the same repository.
7783 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
7784 * operation was added.
7785 */
7786
7787var inherits = require('inherits')
7788var Hash = require('./hash')
7789var Buffer = require('safe-buffer').Buffer
7790
7791var K = [
7792 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
7793]
7794
7795var W = new Array(80)
7796
7797function Sha () {
7798 this.init()
7799 this._w = W
7800
7801 Hash.call(this, 64, 56)
7802}
7803
7804inherits(Sha, Hash)
7805
7806Sha.prototype.init = function () {
7807 this._a = 0x67452301
7808 this._b = 0xefcdab89
7809 this._c = 0x98badcfe
7810 this._d = 0x10325476
7811 this._e = 0xc3d2e1f0
7812
7813 return this
7814}
7815
7816function rotl5 (num) {
7817 return (num << 5) | (num >>> 27)
7818}
7819
7820function rotl30 (num) {
7821 return (num << 30) | (num >>> 2)
7822}
7823
7824function ft (s, b, c, d) {
7825 if (s === 0) return (b & c) | ((~b) & d)
7826 if (s === 2) return (b & c) | (b & d) | (c & d)
7827 return b ^ c ^ d
7828}
7829
7830Sha.prototype._update = function (M) {
7831 var W = this._w
7832
7833 var a = this._a | 0
7834 var b = this._b | 0
7835 var c = this._c | 0
7836 var d = this._d | 0
7837 var e = this._e | 0
7838
7839 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
7840 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
7841
7842 for (var j = 0; j < 80; ++j) {
7843 var s = ~~(j / 20)
7844 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
7845
7846 e = d
7847 d = c
7848 c = rotl30(b)
7849 b = a
7850 a = t
7851 }
7852
7853 this._a = (a + this._a) | 0
7854 this._b = (b + this._b) | 0
7855 this._c = (c + this._c) | 0
7856 this._d = (d + this._d) | 0
7857 this._e = (e + this._e) | 0
7858}
7859
7860Sha.prototype._hash = function () {
7861 var H = Buffer.allocUnsafe(20)
7862
7863 H.writeInt32BE(this._a | 0, 0)
7864 H.writeInt32BE(this._b | 0, 4)
7865 H.writeInt32BE(this._c | 0, 8)
7866 H.writeInt32BE(this._d | 0, 12)
7867 H.writeInt32BE(this._e | 0, 16)
7868
7869 return H
7870}
7871
7872module.exports = Sha
7873
7874},{"./hash":42,"inherits":22,"safe-buffer":41}],45:[function(require,module,exports){
7875/*
7876 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
7877 * in FIPS PUB 180-1
7878 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
7879 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
7880 * Distributed under the BSD License
7881 * See http://pajhome.org.uk/crypt/md5 for details.
7882 */
7883
7884var inherits = require('inherits')
7885var Hash = require('./hash')
7886var Buffer = require('safe-buffer').Buffer
7887
7888var K = [
7889 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
7890]
7891
7892var W = new Array(80)
7893
7894function Sha1 () {
7895 this.init()
7896 this._w = W
7897
7898 Hash.call(this, 64, 56)
7899}
7900
7901inherits(Sha1, Hash)
7902
7903Sha1.prototype.init = function () {
7904 this._a = 0x67452301
7905 this._b = 0xefcdab89
7906 this._c = 0x98badcfe
7907 this._d = 0x10325476
7908 this._e = 0xc3d2e1f0
7909
7910 return this
7911}
7912
7913function rotl1 (num) {
7914 return (num << 1) | (num >>> 31)
7915}
7916
7917function rotl5 (num) {
7918 return (num << 5) | (num >>> 27)
7919}
7920
7921function rotl30 (num) {
7922 return (num << 30) | (num >>> 2)
7923}
7924
7925function ft (s, b, c, d) {
7926 if (s === 0) return (b & c) | ((~b) & d)
7927 if (s === 2) return (b & c) | (b & d) | (c & d)
7928 return b ^ c ^ d
7929}
7930
7931Sha1.prototype._update = function (M) {
7932 var W = this._w
7933
7934 var a = this._a | 0
7935 var b = this._b | 0
7936 var c = this._c | 0
7937 var d = this._d | 0
7938 var e = this._e | 0
7939
7940 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
7941 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
7942
7943 for (var j = 0; j < 80; ++j) {
7944 var s = ~~(j / 20)
7945 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
7946
7947 e = d
7948 d = c
7949 c = rotl30(b)
7950 b = a
7951 a = t
7952 }
7953
7954 this._a = (a + this._a) | 0
7955 this._b = (b + this._b) | 0
7956 this._c = (c + this._c) | 0
7957 this._d = (d + this._d) | 0
7958 this._e = (e + this._e) | 0
7959}
7960
7961Sha1.prototype._hash = function () {
7962 var H = Buffer.allocUnsafe(20)
7963
7964 H.writeInt32BE(this._a | 0, 0)
7965 H.writeInt32BE(this._b | 0, 4)
7966 H.writeInt32BE(this._c | 0, 8)
7967 H.writeInt32BE(this._d | 0, 12)
7968 H.writeInt32BE(this._e | 0, 16)
7969
7970 return H
7971}
7972
7973module.exports = Sha1
7974
7975},{"./hash":42,"inherits":22,"safe-buffer":41}],46:[function(require,module,exports){
7976/**
7977 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
7978 * in FIPS 180-2
7979 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
7980 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
7981 *
7982 */
7983
7984var inherits = require('inherits')
7985var Sha256 = require('./sha256')
7986var Hash = require('./hash')
7987var Buffer = require('safe-buffer').Buffer
7988
7989var W = new Array(64)
7990
7991function Sha224 () {
7992 this.init()
7993
7994 this._w = W // new Array(64)
7995
7996 Hash.call(this, 64, 56)
7997}
7998
7999inherits(Sha224, Sha256)
8000
8001Sha224.prototype.init = function () {
8002 this._a = 0xc1059ed8
8003 this._b = 0x367cd507
8004 this._c = 0x3070dd17
8005 this._d = 0xf70e5939
8006 this._e = 0xffc00b31
8007 this._f = 0x68581511
8008 this._g = 0x64f98fa7
8009 this._h = 0xbefa4fa4
8010
8011 return this
8012}
8013
8014Sha224.prototype._hash = function () {
8015 var H = Buffer.allocUnsafe(28)
8016
8017 H.writeInt32BE(this._a, 0)
8018 H.writeInt32BE(this._b, 4)
8019 H.writeInt32BE(this._c, 8)
8020 H.writeInt32BE(this._d, 12)
8021 H.writeInt32BE(this._e, 16)
8022 H.writeInt32BE(this._f, 20)
8023 H.writeInt32BE(this._g, 24)
8024
8025 return H
8026}
8027
8028module.exports = Sha224
8029
8030},{"./hash":42,"./sha256":47,"inherits":22,"safe-buffer":41}],47:[function(require,module,exports){
8031/**
8032 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
8033 * in FIPS 180-2
8034 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
8035 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
8036 *
8037 */
8038
8039var inherits = require('inherits')
8040var Hash = require('./hash')
8041var Buffer = require('safe-buffer').Buffer
8042
8043var K = [
8044 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
8045 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
8046 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
8047 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
8048 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
8049 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
8050 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
8051 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
8052 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
8053 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
8054 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
8055 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
8056 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
8057 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
8058 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
8059 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
8060]
8061
8062var W = new Array(64)
8063
8064function Sha256 () {
8065 this.init()
8066
8067 this._w = W // new Array(64)
8068
8069 Hash.call(this, 64, 56)
8070}
8071
8072inherits(Sha256, Hash)
8073
8074Sha256.prototype.init = function () {
8075 this._a = 0x6a09e667
8076 this._b = 0xbb67ae85
8077 this._c = 0x3c6ef372
8078 this._d = 0xa54ff53a
8079 this._e = 0x510e527f
8080 this._f = 0x9b05688c
8081 this._g = 0x1f83d9ab
8082 this._h = 0x5be0cd19
8083
8084 return this
8085}
8086
8087function ch (x, y, z) {
8088 return z ^ (x & (y ^ z))
8089}
8090
8091function maj (x, y, z) {
8092 return (x & y) | (z & (x | y))
8093}
8094
8095function sigma0 (x) {
8096 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
8097}
8098
8099function sigma1 (x) {
8100 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
8101}
8102
8103function gamma0 (x) {
8104 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
8105}
8106
8107function gamma1 (x) {
8108 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
8109}
8110
8111Sha256.prototype._update = function (M) {
8112 var W = this._w
8113
8114 var a = this._a | 0
8115 var b = this._b | 0
8116 var c = this._c | 0
8117 var d = this._d | 0
8118 var e = this._e | 0
8119 var f = this._f | 0
8120 var g = this._g | 0
8121 var h = this._h | 0
8122
8123 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
8124 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
8125
8126 for (var j = 0; j < 64; ++j) {
8127 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
8128 var T2 = (sigma0(a) + maj(a, b, c)) | 0
8129
8130 h = g
8131 g = f
8132 f = e
8133 e = (d + T1) | 0
8134 d = c
8135 c = b
8136 b = a
8137 a = (T1 + T2) | 0
8138 }
8139
8140 this._a = (a + this._a) | 0
8141 this._b = (b + this._b) | 0
8142 this._c = (c + this._c) | 0
8143 this._d = (d + this._d) | 0
8144 this._e = (e + this._e) | 0
8145 this._f = (f + this._f) | 0
8146 this._g = (g + this._g) | 0
8147 this._h = (h + this._h) | 0
8148}
8149
8150Sha256.prototype._hash = function () {
8151 var H = Buffer.allocUnsafe(32)
8152
8153 H.writeInt32BE(this._a, 0)
8154 H.writeInt32BE(this._b, 4)
8155 H.writeInt32BE(this._c, 8)
8156 H.writeInt32BE(this._d, 12)
8157 H.writeInt32BE(this._e, 16)
8158 H.writeInt32BE(this._f, 20)
8159 H.writeInt32BE(this._g, 24)
8160 H.writeInt32BE(this._h, 28)
8161
8162 return H
8163}
8164
8165module.exports = Sha256
8166
8167},{"./hash":42,"inherits":22,"safe-buffer":41}],48:[function(require,module,exports){
8168var inherits = require('inherits')
8169var SHA512 = require('./sha512')
8170var Hash = require('./hash')
8171var Buffer = require('safe-buffer').Buffer
8172
8173var W = new Array(160)
8174
8175function Sha384 () {
8176 this.init()
8177 this._w = W
8178
8179 Hash.call(this, 128, 112)
8180}
8181
8182inherits(Sha384, SHA512)
8183
8184Sha384.prototype.init = function () {
8185 this._ah = 0xcbbb9d5d
8186 this._bh = 0x629a292a
8187 this._ch = 0x9159015a
8188 this._dh = 0x152fecd8
8189 this._eh = 0x67332667
8190 this._fh = 0x8eb44a87
8191 this._gh = 0xdb0c2e0d
8192 this._hh = 0x47b5481d
8193
8194 this._al = 0xc1059ed8
8195 this._bl = 0x367cd507
8196 this._cl = 0x3070dd17
8197 this._dl = 0xf70e5939
8198 this._el = 0xffc00b31
8199 this._fl = 0x68581511
8200 this._gl = 0x64f98fa7
8201 this._hl = 0xbefa4fa4
8202
8203 return this
8204}
8205
8206Sha384.prototype._hash = function () {
8207 var H = Buffer.allocUnsafe(48)
8208
8209 function writeInt64BE (h, l, offset) {
8210 H.writeInt32BE(h, offset)
8211 H.writeInt32BE(l, offset + 4)
8212 }
8213
8214 writeInt64BE(this._ah, this._al, 0)
8215 writeInt64BE(this._bh, this._bl, 8)
8216 writeInt64BE(this._ch, this._cl, 16)
8217 writeInt64BE(this._dh, this._dl, 24)
8218 writeInt64BE(this._eh, this._el, 32)
8219 writeInt64BE(this._fh, this._fl, 40)
8220
8221 return H
8222}
8223
8224module.exports = Sha384
8225
8226},{"./hash":42,"./sha512":49,"inherits":22,"safe-buffer":41}],49:[function(require,module,exports){
8227var inherits = require('inherits')
8228var Hash = require('./hash')
8229var Buffer = require('safe-buffer').Buffer
8230
8231var K = [
8232 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
8233 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
8234 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
8235 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
8236 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
8237 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
8238 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
8239 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
8240 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
8241 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
8242 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
8243 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
8244 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
8245 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
8246 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
8247 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
8248 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
8249 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
8250 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
8251 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
8252 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
8253 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
8254 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
8255 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
8256 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
8257 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
8258 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
8259 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
8260 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
8261 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
8262 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
8263 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
8264 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
8265 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
8266 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
8267 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
8268 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
8269 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
8270 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
8271 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
8272]
8273
8274var W = new Array(160)
8275
8276function Sha512 () {
8277 this.init()
8278 this._w = W
8279
8280 Hash.call(this, 128, 112)
8281}
8282
8283inherits(Sha512, Hash)
8284
8285Sha512.prototype.init = function () {
8286 this._ah = 0x6a09e667
8287 this._bh = 0xbb67ae85
8288 this._ch = 0x3c6ef372
8289 this._dh = 0xa54ff53a
8290 this._eh = 0x510e527f
8291 this._fh = 0x9b05688c
8292 this._gh = 0x1f83d9ab
8293 this._hh = 0x5be0cd19
8294
8295 this._al = 0xf3bcc908
8296 this._bl = 0x84caa73b
8297 this._cl = 0xfe94f82b
8298 this._dl = 0x5f1d36f1
8299 this._el = 0xade682d1
8300 this._fl = 0x2b3e6c1f
8301 this._gl = 0xfb41bd6b
8302 this._hl = 0x137e2179
8303
8304 return this
8305}
8306
8307function Ch (x, y, z) {
8308 return z ^ (x & (y ^ z))
8309}
8310
8311function maj (x, y, z) {
8312 return (x & y) | (z & (x | y))
8313}
8314
8315function sigma0 (x, xl) {
8316 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
8317}
8318
8319function sigma1 (x, xl) {
8320 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
8321}
8322
8323function Gamma0 (x, xl) {
8324 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
8325}
8326
8327function Gamma0l (x, xl) {
8328 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
8329}
8330
8331function Gamma1 (x, xl) {
8332 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
8333}
8334
8335function Gamma1l (x, xl) {
8336 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
8337}
8338
8339function getCarry (a, b) {
8340 return (a >>> 0) < (b >>> 0) ? 1 : 0
8341}
8342
8343Sha512.prototype._update = function (M) {
8344 var W = this._w
8345
8346 var ah = this._ah | 0
8347 var bh = this._bh | 0
8348 var ch = this._ch | 0
8349 var dh = this._dh | 0
8350 var eh = this._eh | 0
8351 var fh = this._fh | 0
8352 var gh = this._gh | 0
8353 var hh = this._hh | 0
8354
8355 var al = this._al | 0
8356 var bl = this._bl | 0
8357 var cl = this._cl | 0
8358 var dl = this._dl | 0
8359 var el = this._el | 0
8360 var fl = this._fl | 0
8361 var gl = this._gl | 0
8362 var hl = this._hl | 0
8363
8364 for (var i = 0; i < 32; i += 2) {
8365 W[i] = M.readInt32BE(i * 4)
8366 W[i + 1] = M.readInt32BE(i * 4 + 4)
8367 }
8368 for (; i < 160; i += 2) {
8369 var xh = W[i - 15 * 2]
8370 var xl = W[i - 15 * 2 + 1]
8371 var gamma0 = Gamma0(xh, xl)
8372 var gamma0l = Gamma0l(xl, xh)
8373
8374 xh = W[i - 2 * 2]
8375 xl = W[i - 2 * 2 + 1]
8376 var gamma1 = Gamma1(xh, xl)
8377 var gamma1l = Gamma1l(xl, xh)
8378
8379 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
8380 var Wi7h = W[i - 7 * 2]
8381 var Wi7l = W[i - 7 * 2 + 1]
8382
8383 var Wi16h = W[i - 16 * 2]
8384 var Wi16l = W[i - 16 * 2 + 1]
8385
8386 var Wil = (gamma0l + Wi7l) | 0
8387 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
8388 Wil = (Wil + gamma1l) | 0
8389 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
8390 Wil = (Wil + Wi16l) | 0
8391 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
8392
8393 W[i] = Wih
8394 W[i + 1] = Wil
8395 }
8396
8397 for (var j = 0; j < 160; j += 2) {
8398 Wih = W[j]
8399 Wil = W[j + 1]
8400
8401 var majh = maj(ah, bh, ch)
8402 var majl = maj(al, bl, cl)
8403
8404 var sigma0h = sigma0(ah, al)
8405 var sigma0l = sigma0(al, ah)
8406 var sigma1h = sigma1(eh, el)
8407 var sigma1l = sigma1(el, eh)
8408
8409 // t1 = h + sigma1 + ch + K[j] + W[j]
8410 var Kih = K[j]
8411 var Kil = K[j + 1]
8412
8413 var chh = Ch(eh, fh, gh)
8414 var chl = Ch(el, fl, gl)
8415
8416 var t1l = (hl + sigma1l) | 0
8417 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
8418 t1l = (t1l + chl) | 0
8419 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
8420 t1l = (t1l + Kil) | 0
8421 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
8422 t1l = (t1l + Wil) | 0
8423 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
8424
8425 // t2 = sigma0 + maj
8426 var t2l = (sigma0l + majl) | 0
8427 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
8428
8429 hh = gh
8430 hl = gl
8431 gh = fh
8432 gl = fl
8433 fh = eh
8434 fl = el
8435 el = (dl + t1l) | 0
8436 eh = (dh + t1h + getCarry(el, dl)) | 0
8437 dh = ch
8438 dl = cl
8439 ch = bh
8440 cl = bl
8441 bh = ah
8442 bl = al
8443 al = (t1l + t2l) | 0
8444 ah = (t1h + t2h + getCarry(al, t1l)) | 0
8445 }
8446
8447 this._al = (this._al + al) | 0
8448 this._bl = (this._bl + bl) | 0
8449 this._cl = (this._cl + cl) | 0
8450 this._dl = (this._dl + dl) | 0
8451 this._el = (this._el + el) | 0
8452 this._fl = (this._fl + fl) | 0
8453 this._gl = (this._gl + gl) | 0
8454 this._hl = (this._hl + hl) | 0
8455
8456 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
8457 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
8458 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
8459 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
8460 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
8461 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
8462 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
8463 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
8464}
8465
8466Sha512.prototype._hash = function () {
8467 var H = Buffer.allocUnsafe(64)
8468
8469 function writeInt64BE (h, l, offset) {
8470 H.writeInt32BE(h, offset)
8471 H.writeInt32BE(l, offset + 4)
8472 }
8473
8474 writeInt64BE(this._ah, this._al, 0)
8475 writeInt64BE(this._bh, this._bl, 8)
8476 writeInt64BE(this._ch, this._cl, 16)
8477 writeInt64BE(this._dh, this._dl, 24)
8478 writeInt64BE(this._eh, this._el, 32)
8479 writeInt64BE(this._fh, this._fl, 40)
8480 writeInt64BE(this._gh, this._gl, 48)
8481 writeInt64BE(this._hh, this._hl, 56)
8482
8483 return H
8484}
8485
8486module.exports = Sha512
8487
8488},{"./hash":42,"inherits":22,"safe-buffer":41}],50:[function(require,module,exports){
8489// Copyright Joyent, Inc. and other Node contributors.
8490//
8491// Permission is hereby granted, free of charge, to any person obtaining a
8492// copy of this software and associated documentation files (the
8493// "Software"), to deal in the Software without restriction, including
8494// without limitation the rights to use, copy, modify, merge, publish,
8495// distribute, sublicense, and/or sell copies of the Software, and to permit
8496// persons to whom the Software is furnished to do so, subject to the
8497// following conditions:
8498//
8499// The above copyright notice and this permission notice shall be included
8500// in all copies or substantial portions of the Software.
8501//
8502// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8503// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
8504// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
8505// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
8506// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
8507// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
8508// USE OR OTHER DEALINGS IN THE SOFTWARE.
8509
8510module.exports = Stream;
8511
8512var EE = require('events').EventEmitter;
8513var inherits = require('inherits');
8514
8515inherits(Stream, EE);
8516Stream.Readable = require('readable-stream/readable.js');
8517Stream.Writable = require('readable-stream/writable.js');
8518Stream.Duplex = require('readable-stream/duplex.js');
8519Stream.Transform = require('readable-stream/transform.js');
8520Stream.PassThrough = require('readable-stream/passthrough.js');
8521
8522// Backwards-compat with node 0.4.x
8523Stream.Stream = Stream;
8524
8525
8526
8527// old-style streams. Note that the pipe method (the only relevant
8528// part of this class) is overridden in the Readable class.
8529
8530function Stream() {
8531 EE.call(this);
8532}
8533
8534Stream.prototype.pipe = function(dest, options) {
8535 var source = this;
8536
8537 function ondata(chunk) {
8538 if (dest.writable) {
8539 if (false === dest.write(chunk) && source.pause) {
8540 source.pause();
8541 }
8542 }
8543 }
8544
8545 source.on('data', ondata);
8546
8547 function ondrain() {
8548 if (source.readable && source.resume) {
8549 source.resume();
8550 }
8551 }
8552
8553 dest.on('drain', ondrain);
8554
8555 // If the 'end' option is not supplied, dest.end() will be called when
8556 // source gets the 'end' or 'close' events. Only dest.end() once.
8557 if (!dest._isStdio && (!options || options.end !== false)) {
8558 source.on('end', onend);
8559 source.on('close', onclose);
8560 }
8561
8562 var didOnEnd = false;
8563 function onend() {
8564 if (didOnEnd) return;
8565 didOnEnd = true;
8566
8567 dest.end();
8568 }
8569
8570
8571 function onclose() {
8572 if (didOnEnd) return;
8573 didOnEnd = true;
8574
8575 if (typeof dest.destroy === 'function') dest.destroy();
8576 }
8577
8578 // don't leave dangling pipes when there are errors.
8579 function onerror(er) {
8580 cleanup();
8581 if (EE.listenerCount(this, 'error') === 0) {
8582 throw er; // Unhandled stream error in pipe.
8583 }
8584 }
8585
8586 source.on('error', onerror);
8587 dest.on('error', onerror);
8588
8589 // remove all the event listeners that were added.
8590 function cleanup() {
8591 source.removeListener('data', ondata);
8592 dest.removeListener('drain', ondrain);
8593
8594 source.removeListener('end', onend);
8595 source.removeListener('close', onclose);
8596
8597 source.removeListener('error', onerror);
8598 dest.removeListener('error', onerror);
8599
8600 source.removeListener('end', cleanup);
8601 source.removeListener('close', cleanup);
8602
8603 dest.removeListener('close', cleanup);
8604 }
8605
8606 source.on('end', cleanup);
8607 source.on('close', cleanup);
8608
8609 dest.on('close', cleanup);
8610
8611 dest.emit('pipe', source);
8612
8613 // Allow for unix-like usage: A.pipe(B).pipe(C)
8614 return dest;
8615};
8616
8617},{"events":19,"inherits":22,"readable-stream/duplex.js":27,"readable-stream/passthrough.js":36,"readable-stream/readable.js":37,"readable-stream/transform.js":38,"readable-stream/writable.js":39}],51:[function(require,module,exports){
8618'use strict';
8619
8620var Buffer = require('safe-buffer').Buffer;
8621
8622var isEncoding = Buffer.isEncoding || function (encoding) {
8623 encoding = '' + encoding;
8624 switch (encoding && encoding.toLowerCase()) {
8625 case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
8626 return true;
8627 default:
8628 return false;
8629 }
8630};
8631
8632function _normalizeEncoding(enc) {
8633 if (!enc) return 'utf8';
8634 var retried;
8635 while (true) {
8636 switch (enc) {
8637 case 'utf8':
8638 case 'utf-8':
8639 return 'utf8';
8640 case 'ucs2':
8641 case 'ucs-2':
8642 case 'utf16le':
8643 case 'utf-16le':
8644 return 'utf16le';
8645 case 'latin1':
8646 case 'binary':
8647 return 'latin1';
8648 case 'base64':
8649 case 'ascii':
8650 case 'hex':
8651 return enc;
8652 default:
8653 if (retried) return; // undefined
8654 enc = ('' + enc).toLowerCase();
8655 retried = true;
8656 }
8657 }
8658};
8659
8660// Do not cache `Buffer.isEncoding` when checking encoding names as some
8661// modules monkey-patch it to support additional encodings
8662function normalizeEncoding(enc) {
8663 var nenc = _normalizeEncoding(enc);
8664 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
8665 return nenc || enc;
8666}
8667
8668// StringDecoder provides an interface for efficiently splitting a series of
8669// buffers into a series of JS strings without breaking apart multi-byte
8670// characters.
8671exports.StringDecoder = StringDecoder;
8672function StringDecoder(encoding) {
8673 this.encoding = normalizeEncoding(encoding);
8674 var nb;
8675 switch (this.encoding) {
8676 case 'utf16le':
8677 this.text = utf16Text;
8678 this.end = utf16End;
8679 nb = 4;
8680 break;
8681 case 'utf8':
8682 this.fillLast = utf8FillLast;
8683 nb = 4;
8684 break;
8685 case 'base64':
8686 this.text = base64Text;
8687 this.end = base64End;
8688 nb = 3;
8689 break;
8690 default:
8691 this.write = simpleWrite;
8692 this.end = simpleEnd;
8693 return;
8694 }
8695 this.lastNeed = 0;
8696 this.lastTotal = 0;
8697 this.lastChar = Buffer.allocUnsafe(nb);
8698}
8699
8700StringDecoder.prototype.write = function (buf) {
8701 if (buf.length === 0) return '';
8702 var r;
8703 var i;
8704 if (this.lastNeed) {
8705 r = this.fillLast(buf);
8706 if (r === undefined) return '';
8707 i = this.lastNeed;
8708 this.lastNeed = 0;
8709 } else {
8710 i = 0;
8711 }
8712 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
8713 return r || '';
8714};
8715
8716StringDecoder.prototype.end = utf8End;
8717
8718// Returns only complete characters in a Buffer
8719StringDecoder.prototype.text = utf8Text;
8720
8721// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
8722StringDecoder.prototype.fillLast = function (buf) {
8723 if (this.lastNeed <= buf.length) {
8724 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
8725 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
8726 }
8727 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
8728 this.lastNeed -= buf.length;
8729};
8730
8731// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
8732// continuation byte.
8733function utf8CheckByte(byte) {
8734 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
8735 return -1;
8736}
8737
8738// Checks at most 3 bytes at the end of a Buffer in order to detect an
8739// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
8740// needed to complete the UTF-8 character (if applicable) are returned.
8741function utf8CheckIncomplete(self, buf, i) {
8742 var j = buf.length - 1;
8743 if (j < i) return 0;
8744 var nb = utf8CheckByte(buf[j]);
8745 if (nb >= 0) {
8746 if (nb > 0) self.lastNeed = nb - 1;
8747 return nb;
8748 }
8749 if (--j < i) return 0;
8750 nb = utf8CheckByte(buf[j]);
8751 if (nb >= 0) {
8752 if (nb > 0) self.lastNeed = nb - 2;
8753 return nb;
8754 }
8755 if (--j < i) return 0;
8756 nb = utf8CheckByte(buf[j]);
8757 if (nb >= 0) {
8758 if (nb > 0) {
8759 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
8760 }
8761 return nb;
8762 }
8763 return 0;
8764}
8765
8766// Validates as many continuation bytes for a multi-byte UTF-8 character as
8767// needed or are available. If we see a non-continuation byte where we expect
8768// one, we "replace" the validated continuation bytes we've seen so far with
8769// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
8770// behavior. The continuation byte check is included three times in the case
8771// where all of the continuation bytes for a character exist in the same buffer.
8772// It is also done this way as a slight performance increase instead of using a
8773// loop.
8774function utf8CheckExtraBytes(self, buf, p) {
8775 if ((buf[0] & 0xC0) !== 0x80) {
8776 self.lastNeed = 0;
8777 return '\ufffd'.repeat(p);
8778 }
8779 if (self.lastNeed > 1 && buf.length > 1) {
8780 if ((buf[1] & 0xC0) !== 0x80) {
8781 self.lastNeed = 1;
8782 return '\ufffd'.repeat(p + 1);
8783 }
8784 if (self.lastNeed > 2 && buf.length > 2) {
8785 if ((buf[2] & 0xC0) !== 0x80) {
8786 self.lastNeed = 2;
8787 return '\ufffd'.repeat(p + 2);
8788 }
8789 }
8790 }
8791}
8792
8793// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
8794function utf8FillLast(buf) {
8795 var p = this.lastTotal - this.lastNeed;
8796 var r = utf8CheckExtraBytes(this, buf, p);
8797 if (r !== undefined) return r;
8798 if (this.lastNeed <= buf.length) {
8799 buf.copy(this.lastChar, p, 0, this.lastNeed);
8800 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
8801 }
8802 buf.copy(this.lastChar, p, 0, buf.length);
8803 this.lastNeed -= buf.length;
8804}
8805
8806// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
8807// partial character, the character's bytes are buffered until the required
8808// number of bytes are available.
8809function utf8Text(buf, i) {
8810 var total = utf8CheckIncomplete(this, buf, i);
8811 if (!this.lastNeed) return buf.toString('utf8', i);
8812 this.lastTotal = total;
8813 var end = buf.length - (total - this.lastNeed);
8814 buf.copy(this.lastChar, 0, end);
8815 return buf.toString('utf8', i, end);
8816}
8817
8818// For UTF-8, a replacement character for each buffered byte of a (partial)
8819// character needs to be added to the output.
8820function utf8End(buf) {
8821 var r = buf && buf.length ? this.write(buf) : '';
8822 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
8823 return r;
8824}
8825
8826// UTF-16LE typically needs two bytes per character, but even if we have an even
8827// number of bytes available, we need to check if we end on a leading/high
8828// surrogate. In that case, we need to wait for the next two bytes in order to
8829// decode the last character properly.
8830function utf16Text(buf, i) {
8831 if ((buf.length - i) % 2 === 0) {
8832 var r = buf.toString('utf16le', i);
8833 if (r) {
8834 var c = r.charCodeAt(r.length - 1);
8835 if (c >= 0xD800 && c <= 0xDBFF) {
8836 this.lastNeed = 2;
8837 this.lastTotal = 4;
8838 this.lastChar[0] = buf[buf.length - 2];
8839 this.lastChar[1] = buf[buf.length - 1];
8840 return r.slice(0, -1);
8841 }
8842 }
8843 return r;
8844 }
8845 this.lastNeed = 1;
8846 this.lastTotal = 2;
8847 this.lastChar[0] = buf[buf.length - 1];
8848 return buf.toString('utf16le', i, buf.length - 1);
8849}
8850
8851// For UTF-16LE we do not explicitly append special replacement characters if we
8852// end on a partial character, we simply let v8 handle that.
8853function utf16End(buf) {
8854 var r = buf && buf.length ? this.write(buf) : '';
8855 if (this.lastNeed) {
8856 var end = this.lastTotal - this.lastNeed;
8857 return r + this.lastChar.toString('utf16le', 0, end);
8858 }
8859 return r;
8860}
8861
8862function base64Text(buf, i) {
8863 var n = (buf.length - i) % 3;
8864 if (n === 0) return buf.toString('base64', i);
8865 this.lastNeed = 3 - n;
8866 this.lastTotal = 3;
8867 if (n === 1) {
8868 this.lastChar[0] = buf[buf.length - 1];
8869 } else {
8870 this.lastChar[0] = buf[buf.length - 2];
8871 this.lastChar[1] = buf[buf.length - 1];
8872 }
8873 return buf.toString('base64', i, buf.length - n);
8874}
8875
8876function base64End(buf) {
8877 var r = buf && buf.length ? this.write(buf) : '';
8878 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
8879 return r;
8880}
8881
8882// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
8883function simpleWrite(buf) {
8884 return buf.toString(this.encoding);
8885}
8886
8887function simpleEnd(buf) {
8888 return buf && buf.length ? this.write(buf) : '';
8889}
8890},{"safe-buffer":41}],52:[function(require,module,exports){
8891(function (global){
8892
8893/**
8894 * Module exports.
8895 */
8896
8897module.exports = deprecate;
8898
8899/**
8900 * Mark that a method should not be used.
8901 * Returns a modified function which warns once by default.
8902 *
8903 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
8904 *
8905 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
8906 * will throw an Error when invoked.
8907 *
8908 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
8909 * will invoke `console.trace()` instead of `console.error()`.
8910 *
8911 * @param {Function} fn - the function to deprecate
8912 * @param {String} msg - the string to print to the console when `fn` is invoked
8913 * @returns {Function} a new "deprecated" version of `fn`
8914 * @api public
8915 */
8916
8917function deprecate (fn, msg) {
8918 if (config('noDeprecation')) {
8919 return fn;
8920 }
8921
8922 var warned = false;
8923 function deprecated() {
8924 if (!warned) {
8925 if (config('throwDeprecation')) {
8926 throw new Error(msg);
8927 } else if (config('traceDeprecation')) {
8928 console.trace(msg);
8929 } else {
8930 console.warn(msg);
8931 }
8932 warned = true;
8933 }
8934 return fn.apply(this, arguments);
8935 }
8936
8937 return deprecated;
8938}
8939
8940/**
8941 * Checks `localStorage` for boolean values for the given `name`.
8942 *
8943 * @param {String} name
8944 * @returns {Boolean}
8945 * @api private
8946 */
8947
8948function config (name) {
8949 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
8950 try {
8951 if (!global.localStorage) return false;
8952 } catch (_) {
8953 return false;
8954 }
8955 var val = global.localStorage[name];
8956 if (null == val) return false;
8957 return String(val).toLowerCase() === 'true';
8958}
8959
8960}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8961},{}],53:[function(require,module,exports){
8962(function (Buffer){
8963/***
8964 * @license
8965 * https://github.com/bitcoincashjs/bchaddr
8966 * Copyright (c) 2018 Emilio Almansi
8967 * Distributed under the MIT software license, see the accompanying
8968 * file LICENSE or http://www.opensource.org/licenses/mit-license.php.
8969 */
8970
8971var bs58check = require('bs58check')
8972var cashaddr = require('cashaddrjs')
8973
8974/**
8975 * General purpose Bitcoin Cash address detection and translation.<br />
8976 * Supports all major Bitcoin Cash address formats.<br />
8977 * Currently:
8978 * <ul>
8979 * <li> Legacy format </li>
8980 * <li> Bitpay format </li>
8981 * <li> Cashaddr format </li>
8982 * </ul>
8983 * @module bchaddr
8984 */
8985
8986/**
8987 * @static
8988 * Supported Bitcoin Cash address formats.
8989 */
8990var Format = {}
8991Format.Legacy = 'legacy'
8992Format.Bitpay = 'bitpay'
8993Format.Cashaddr = 'cashaddr'
8994
8995/**
8996 * @static
8997 * Supported networks.
8998 */
8999var Network = {}
9000Network.Mainnet = 'mainnet'
9001Network.Testnet = 'testnet'
9002
9003/**
9004 * @static
9005 * Supported address types.
9006 */
9007var Type = {}
9008Type.P2PKH = 'p2pkh'
9009Type.P2SH = 'p2sh'
9010
9011/**
9012 * Detects what is the given address' format.
9013 * @static
9014 * @param {string} address - A valid Bitcoin Cash address in any format.
9015 * @return {string}
9016 * @throws {InvalidAddressError}
9017 */
9018function detectAddressFormat (address) {
9019 return decodeAddress(address).format
9020}
9021
9022/**
9023 * Detects what is the given address' network.
9024 * @static
9025 * @param {string} address - A valid Bitcoin Cash address in any format.
9026 * @return {string}
9027 * @throws {InvalidAddressError}
9028 */
9029function detectAddressNetwork (address) {
9030 return decodeAddress(address).network
9031}
9032
9033/**
9034 * Detects what is the given address' type.
9035 * @static
9036 * @param {string} address - A valid Bitcoin Cash address in any format.
9037 * @return {string}
9038 * @throws {InvalidAddressError}
9039 */
9040function detectAddressType (address) {
9041 return decodeAddress(address).type
9042}
9043
9044/**
9045 * Translates the given address into legacy format.
9046 * @static
9047 * @param {string} address - A valid Bitcoin Cash address in any format.
9048 * @return {string}
9049 * @throws {InvalidAddressError}
9050 */
9051function toLegacyAddress (address) {
9052 var decoded = decodeAddress(address)
9053 if (decoded.format === Format.Legacy) {
9054 return address
9055 }
9056 return encodeAsLegacy(decoded)
9057}
9058
9059/**
9060 * Translates the given address into bitpay format.
9061 * @static
9062 * @param {string} address - A valid Bitcoin Cash address in any format.
9063 * @return {string}
9064 * @throws {InvalidAddressError}
9065 */
9066function toBitpayAddress (address) {
9067 var decoded = decodeAddress(address)
9068 if (decoded.format === Format.Bitpay) {
9069 return address
9070 }
9071 return encodeAsBitpay(decoded)
9072}
9073
9074/**
9075 * Translates the given address into cashaddr format.
9076 * @static
9077 * @param {string} address - A valid Bitcoin Cash address in any format.
9078 * @return {string}
9079 * @throws {InvalidAddressError}
9080 */
9081function toCashAddress (address) {
9082 var decoded = decodeAddress(address)
9083 return encodeAsCashaddr(decoded)
9084}
9085
9086/**
9087 * Version byte table for base58 formats.
9088 * @private
9089 */
9090var VERSION_BYTE = {}
9091VERSION_BYTE[Format.Legacy] = {}
9092VERSION_BYTE[Format.Legacy][Network.Mainnet] = {}
9093VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2PKH] = 0
9094VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2SH] = 5
9095VERSION_BYTE[Format.Legacy][Network.Testnet] = {}
9096VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2PKH] = 111
9097VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2SH] = 196
9098VERSION_BYTE[Format.Bitpay] = {}
9099VERSION_BYTE[Format.Bitpay][Network.Mainnet] = {}
9100VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2PKH] = 28
9101VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2SH] = 40
9102VERSION_BYTE[Format.Bitpay][Network.Testnet] = {}
9103VERSION_BYTE[Format.Bitpay][Network.Testnet][Type.P2PKH] = 111
9104VERSION_BYTE[Format.Bitpay][Network.Testnet][Type.P2SH] = 196
9105
9106/**
9107 * Decodes the given address into its constituting hash, format, network and type.
9108 * @private
9109 * @param {string} address - A valid Bitcoin Cash address in any format.
9110 * @return {object}
9111 * @throws {InvalidAddressError}
9112 */
9113function decodeAddress (address) {
9114 try {
9115 return decodeBase58Address(address)
9116 } catch (error) {
9117 }
9118 try {
9119 return decodeCashAddress(address)
9120 } catch (error) {
9121 }
9122 throw new InvalidAddressError()
9123}
9124
9125/**
9126 * Length of a valid base58check encoding payload: 1 byte for
9127 * the version byte plus 20 bytes for a RIPEMD-160 hash.
9128 * @private
9129 */
9130var BASE_58_CHECK_PAYLOAD_LENGTH = 21
9131
9132/**
9133 * Attempts to decode the given address assuming it is a base58 address.
9134 * @private
9135 * @param {string} address - A valid Bitcoin Cash address in any format.
9136 * @return {object}
9137 * @throws {InvalidAddressError}
9138 */
9139function decodeBase58Address (address) {
9140 try {
9141 var payload = bs58check.decode(address)
9142 if (payload.length !== BASE_58_CHECK_PAYLOAD_LENGTH) {
9143 throw new InvalidAddressError()
9144 }
9145 var versionByte = payload[0]
9146 var hash = Array.prototype.slice.call(payload, 1)
9147 switch (versionByte) {
9148 case VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2PKH]:
9149 return {
9150 hash: hash,
9151 format: Format.Legacy,
9152 network: Network.Mainnet,
9153 type: Type.P2PKH
9154 }
9155 case VERSION_BYTE[Format.Legacy][Network.Mainnet][Type.P2SH]:
9156 return {
9157 hash: hash,
9158 format: Format.Legacy,
9159 network: Network.Mainnet,
9160 type: Type.P2SH
9161 }
9162 case VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2PKH]:
9163 return {
9164 hash: hash,
9165 format: Format.Legacy,
9166 network: Network.Testnet,
9167 type: Type.P2PKH
9168 }
9169 case VERSION_BYTE[Format.Legacy][Network.Testnet][Type.P2SH]:
9170 return {
9171 hash: hash,
9172 format: Format.Legacy,
9173 network: Network.Testnet,
9174 type: Type.P2SH
9175 }
9176 case VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2PKH]:
9177 return {
9178 hash: hash,
9179 format: Format.Bitpay,
9180 network: Network.Mainnet,
9181 type: Type.P2PKH
9182 }
9183 case VERSION_BYTE[Format.Bitpay][Network.Mainnet][Type.P2SH]:
9184 return {
9185 hash: hash,
9186 format: Format.Bitpay,
9187 network: Network.Mainnet,
9188 type: Type.P2SH
9189 }
9190 }
9191 } catch (error) {
9192 }
9193 throw new InvalidAddressError()
9194}
9195
9196/**
9197 * Attempts to decode the given address assuming it is a cashaddr address.
9198 * @private
9199 * @param {string} address - A valid Bitcoin Cash address in any format.
9200 * @return {object}
9201 * @throws {InvalidAddressError}
9202 */
9203function decodeCashAddress (address) {
9204 if (address.indexOf(':') !== -1) {
9205 try {
9206 return decodeCashAddressWithPrefix(address)
9207 } catch (error) {
9208 }
9209 } else {
9210 var prefixes = ['bitcoincash', 'bchtest', 'bchreg']
9211 for (var i = 0; i < prefixes.length; ++i) {
9212 try {
9213 var prefix = prefixes[i]
9214 return decodeCashAddressWithPrefix(prefix + ':' + address)
9215 } catch (error) {
9216 }
9217 }
9218 }
9219 throw new InvalidAddressError()
9220}
9221
9222/**
9223 * Attempts to decode the given address assuming it is a cashaddr address with explicit prefix.
9224 * @private
9225 * @param {string} address - A valid Bitcoin Cash address in any format.
9226 * @return {object}
9227 * @throws {InvalidAddressError}
9228 */
9229function decodeCashAddressWithPrefix (address) {
9230 try {
9231 var decoded = cashaddr.decode(address)
9232 var hash = Array.prototype.slice.call(decoded.hash, 0)
9233 var type = decoded.type === 'P2PKH' ? Type.P2PKH : Type.P2SH
9234 switch (decoded.prefix) {
9235 case 'bitcoincash':
9236 return {
9237 hash: hash,
9238 format: Format.Cashaddr,
9239 network: Network.Mainnet,
9240 type: type
9241 }
9242 case 'bchtest':
9243 case 'bchreg':
9244 return {
9245 hash: hash,
9246 format: Format.Cashaddr,
9247 network: Network.Testnet,
9248 type: type
9249 }
9250 }
9251 } catch (error) {
9252 }
9253 throw new InvalidAddressError()
9254}
9255
9256/**
9257 * Encodes the given decoded address into legacy format.
9258 * @private
9259 * @param {object} decoded
9260 * @returns {string}
9261 */
9262function encodeAsLegacy (decoded) {
9263 var versionByte = VERSION_BYTE[Format.Legacy][decoded.network][decoded.type]
9264 var buffer = Buffer.alloc(1 + decoded.hash.length)
9265 buffer[0] = versionByte
9266 buffer.set(decoded.hash, 1)
9267 return bs58check.encode(buffer)
9268}
9269
9270/**
9271 * Encodes the given decoded address into bitpay format.
9272 * @private
9273 * @param {object} decoded
9274 * @returns {string}
9275 */
9276function encodeAsBitpay (decoded) {
9277 var versionByte = VERSION_BYTE[Format.Bitpay][decoded.network][decoded.type]
9278 var buffer = Buffer.alloc(1 + decoded.hash.length)
9279 buffer[0] = versionByte
9280 buffer.set(decoded.hash, 1)
9281 return bs58check.encode(buffer)
9282}
9283
9284/**
9285 * Encodes the given decoded address into cashaddr format.
9286 * @private
9287 * @param {object} decoded
9288 * @returns {string}
9289 */
9290function encodeAsCashaddr (decoded) {
9291 var prefix = decoded.network === Network.Mainnet ? 'bitcoincash' : 'bchtest'
9292 var type = decoded.type === Type.P2PKH ? 'P2PKH' : 'P2SH'
9293 var hash = new Uint8Array(decoded.hash)
9294 return cashaddr.encode(prefix, type, hash)
9295}
9296
9297/**
9298 * Returns a boolean indicating whether the address is in legacy format.
9299 * @static
9300 * @param {string} address - A valid Bitcoin Cash address in any format.
9301 * @returns {boolean}
9302 * @throws {InvalidAddressError}
9303 */
9304function isLegacyAddress (address) {
9305 return detectAddressFormat(address) === Format.Legacy
9306}
9307
9308/**
9309 * Returns a boolean indicating whether the address is in bitpay format.
9310 * @static
9311 * @param {string} address - A valid Bitcoin Cash address in any format.
9312 * @returns {boolean}
9313 * @throws {InvalidAddressError}
9314 */
9315function isBitpayAddress (address) {
9316 return detectAddressFormat(address) === Format.Bitpay
9317}
9318
9319/**
9320 * Returns a boolean indicating whether the address is in cashaddr format.
9321 * @static
9322 * @param {string} address - A valid Bitcoin Cash address in any format.
9323 * @returns {boolean}
9324 * @throws {InvalidAddressError}
9325 */
9326function isCashAddress (address) {
9327 return detectAddressFormat(address) === Format.Cashaddr
9328}
9329
9330/**
9331 * Returns a boolean indicating whether the address is a mainnet address.
9332 * @static
9333 * @param {string} address - A valid Bitcoin Cash address in any format.
9334 * @returns {boolean}
9335 * @throws {InvalidAddressError}
9336 */
9337function isMainnetAddress (address) {
9338 return detectAddressNetwork(address) === Network.Mainnet
9339}
9340
9341/**
9342 * Returns a boolean indicating whether the address is a testnet address.
9343 * @static
9344 * @param {string} address - A valid Bitcoin Cash address in any format.
9345 * @returns {boolean}
9346 * @throws {InvalidAddressError}
9347 */
9348function isTestnetAddress (address) {
9349 return detectAddressNetwork(address) === Network.Testnet
9350}
9351
9352/**
9353 * Returns a boolean indicating whether the address is a p2pkh address.
9354 * @static
9355 * @param {string} address - A valid Bitcoin Cash address in any format.
9356 * @returns {boolean}
9357 * @throws {InvalidAddressError}
9358 */
9359function isP2PKHAddress (address) {
9360 return detectAddressType(address) === Type.P2PKH
9361}
9362
9363/**
9364 * Returns a boolean indicating whether the address is a p2sh address.
9365 * @static
9366 * @param {string} address - A valid Bitcoin Cash address in any format.
9367 * @returns {boolean}
9368 * @throws {InvalidAddressError}
9369 */
9370function isP2SHAddress (address) {
9371 return detectAddressType(address) === Type.P2SH
9372}
9373
9374/**
9375 * Error thrown when the address given as input is not a valid Bitcoin Cash address.
9376 * @constructor
9377 * InvalidAddressError
9378 */
9379function InvalidAddressError () {
9380 var error = new Error()
9381 this.name = error.name = 'InvalidAddressError'
9382 this.message = error.message = 'Received an invalid Bitcoin Cash address as input.'
9383 this.stack = error.stack
9384}
9385
9386InvalidAddressError.prototype = Object.create(Error.prototype)
9387
9388module.exports = {
9389 Format: Format,
9390 Network: Network,
9391 Type: Type,
9392 detectAddressFormat: detectAddressFormat,
9393 detectAddressNetwork: detectAddressNetwork,
9394 detectAddressType: detectAddressType,
9395 toLegacyAddress: toLegacyAddress,
9396 toBitpayAddress: toBitpayAddress,
9397 toCashAddress: toCashAddress,
9398 isLegacyAddress: isLegacyAddress,
9399 isBitpayAddress: isBitpayAddress,
9400 isCashAddress: isCashAddress,
9401 isMainnetAddress: isMainnetAddress,
9402 isTestnetAddress: isTestnetAddress,
9403 isP2PKHAddress: isP2PKHAddress,
9404 isP2SHAddress: isP2SHAddress,
9405 InvalidAddressError: InvalidAddressError
9406}
9407
9408}).call(this,require("buffer").Buffer)
9409},{"bs58check":7,"buffer":9,"cashaddrjs":11}]},{},[53])(53)
9410});
\No newline at end of file