]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/bitcoinjs-3.3.2.js
Merge pull request #287 from sui77/master
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / bitcoinjs-3.3.2.js
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.bitcoinjs = 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 (function (global){
3 'use strict';
4
5 // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
6 // original notice:
7
8 /*!
9 * The buffer module from node.js, for the browser.
10 *
11 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
12 * @license MIT
13 */
14 function compare(a, b) {
15 if (a === b) {
16 return 0;
17 }
18
19 var x = a.length;
20 var y = b.length;
21
22 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
23 if (a[i] !== b[i]) {
24 x = a[i];
25 y = b[i];
26 break;
27 }
28 }
29
30 if (x < y) {
31 return -1;
32 }
33 if (y < x) {
34 return 1;
35 }
36 return 0;
37 }
38 function isBuffer(b) {
39 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
40 return global.Buffer.isBuffer(b);
41 }
42 return !!(b != null && b._isBuffer);
43 }
44
45 // based on node assert, original notice:
46
47 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
48 //
49 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
50 //
51 // Originally from narwhal.js (http://narwhaljs.org)
52 // Copyright (c) 2009 Thomas Robinson <280north.com>
53 //
54 // Permission is hereby granted, free of charge, to any person obtaining a copy
55 // of this software and associated documentation files (the 'Software'), to
56 // deal in the Software without restriction, including without limitation the
57 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
58 // sell copies of the Software, and to permit persons to whom the Software is
59 // furnished to do so, subject to the following conditions:
60 //
61 // The above copyright notice and this permission notice shall be included in
62 // all copies or substantial portions of the Software.
63 //
64 // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
65 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
66 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
67 // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
68 // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
69 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70
71 var util = require('util/');
72 var hasOwn = Object.prototype.hasOwnProperty;
73 var pSlice = Array.prototype.slice;
74 var functionsHaveNames = (function () {
75 return function foo() {}.name === 'foo';
76 }());
77 function pToString (obj) {
78 return Object.prototype.toString.call(obj);
79 }
80 function isView(arrbuf) {
81 if (isBuffer(arrbuf)) {
82 return false;
83 }
84 if (typeof global.ArrayBuffer !== 'function') {
85 return false;
86 }
87 if (typeof ArrayBuffer.isView === 'function') {
88 return ArrayBuffer.isView(arrbuf);
89 }
90 if (!arrbuf) {
91 return false;
92 }
93 if (arrbuf instanceof DataView) {
94 return true;
95 }
96 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
97 return true;
98 }
99 return false;
100 }
101 // 1. The assert module provides functions that throw
102 // AssertionError's when particular conditions are not met. The
103 // assert module must conform to the following interface.
104
105 var assert = module.exports = ok;
106
107 // 2. The AssertionError is defined in assert.
108 // new assert.AssertionError({ message: message,
109 // actual: actual,
110 // expected: expected })
111
112 var regex = /\s*function\s+([^\(\s]*)\s*/;
113 // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
114 function getName(func) {
115 if (!util.isFunction(func)) {
116 return;
117 }
118 if (functionsHaveNames) {
119 return func.name;
120 }
121 var str = func.toString();
122 var match = str.match(regex);
123 return match && match[1];
124 }
125 assert.AssertionError = function AssertionError(options) {
126 this.name = 'AssertionError';
127 this.actual = options.actual;
128 this.expected = options.expected;
129 this.operator = options.operator;
130 if (options.message) {
131 this.message = options.message;
132 this.generatedMessage = false;
133 } else {
134 this.message = getMessage(this);
135 this.generatedMessage = true;
136 }
137 var stackStartFunction = options.stackStartFunction || fail;
138 if (Error.captureStackTrace) {
139 Error.captureStackTrace(this, stackStartFunction);
140 } else {
141 // non v8 browsers so we can have a stacktrace
142 var err = new Error();
143 if (err.stack) {
144 var out = err.stack;
145
146 // try to strip useless frames
147 var fn_name = getName(stackStartFunction);
148 var idx = out.indexOf('\n' + fn_name);
149 if (idx >= 0) {
150 // once we have located the function frame
151 // we need to strip out everything before it (and its line)
152 var next_line = out.indexOf('\n', idx + 1);
153 out = out.substring(next_line + 1);
154 }
155
156 this.stack = out;
157 }
158 }
159 };
160
161 // assert.AssertionError instanceof Error
162 util.inherits(assert.AssertionError, Error);
163
164 function truncate(s, n) {
165 if (typeof s === 'string') {
166 return s.length < n ? s : s.slice(0, n);
167 } else {
168 return s;
169 }
170 }
171 function inspect(something) {
172 if (functionsHaveNames || !util.isFunction(something)) {
173 return util.inspect(something);
174 }
175 var rawname = getName(something);
176 var name = rawname ? ': ' + rawname : '';
177 return '[Function' + name + ']';
178 }
179 function getMessage(self) {
180 return truncate(inspect(self.actual), 128) + ' ' +
181 self.operator + ' ' +
182 truncate(inspect(self.expected), 128);
183 }
184
185 // At present only the three keys mentioned above are used and
186 // understood by the spec. Implementations or sub modules can pass
187 // other keys to the AssertionError's constructor - they will be
188 // ignored.
189
190 // 3. All of the following functions must throw an AssertionError
191 // when a corresponding condition is not met, with a message that
192 // may be undefined if not provided. All assertion methods provide
193 // both the actual and expected values to the assertion error for
194 // display purposes.
195
196 function fail(actual, expected, message, operator, stackStartFunction) {
197 throw new assert.AssertionError({
198 message: message,
199 actual: actual,
200 expected: expected,
201 operator: operator,
202 stackStartFunction: stackStartFunction
203 });
204 }
205
206 // EXTENSION! allows for well behaved errors defined elsewhere.
207 assert.fail = fail;
208
209 // 4. Pure assertion tests whether a value is truthy, as determined
210 // by !!guard.
211 // assert.ok(guard, message_opt);
212 // This statement is equivalent to assert.equal(true, !!guard,
213 // message_opt);. To test strictly for the value true, use
214 // assert.strictEqual(true, guard, message_opt);.
215
216 function ok(value, message) {
217 if (!value) fail(value, true, message, '==', assert.ok);
218 }
219 assert.ok = ok;
220
221 // 5. The equality assertion tests shallow, coercive equality with
222 // ==.
223 // assert.equal(actual, expected, message_opt);
224
225 assert.equal = function equal(actual, expected, message) {
226 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
227 };
228
229 // 6. The non-equality assertion tests for whether two objects are not equal
230 // with != assert.notEqual(actual, expected, message_opt);
231
232 assert.notEqual = function notEqual(actual, expected, message) {
233 if (actual == expected) {
234 fail(actual, expected, message, '!=', assert.notEqual);
235 }
236 };
237
238 // 7. The equivalence assertion tests a deep equality relation.
239 // assert.deepEqual(actual, expected, message_opt);
240
241 assert.deepEqual = function deepEqual(actual, expected, message) {
242 if (!_deepEqual(actual, expected, false)) {
243 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
244 }
245 };
246
247 assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
248 if (!_deepEqual(actual, expected, true)) {
249 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
250 }
251 };
252
253 function _deepEqual(actual, expected, strict, memos) {
254 // 7.1. All identical values are equivalent, as determined by ===.
255 if (actual === expected) {
256 return true;
257 } else if (isBuffer(actual) && isBuffer(expected)) {
258 return compare(actual, expected) === 0;
259
260 // 7.2. If the expected value is a Date object, the actual value is
261 // equivalent if it is also a Date object that refers to the same time.
262 } else if (util.isDate(actual) && util.isDate(expected)) {
263 return actual.getTime() === expected.getTime();
264
265 // 7.3 If the expected value is a RegExp object, the actual value is
266 // equivalent if it is also a RegExp object with the same source and
267 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
268 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
269 return actual.source === expected.source &&
270 actual.global === expected.global &&
271 actual.multiline === expected.multiline &&
272 actual.lastIndex === expected.lastIndex &&
273 actual.ignoreCase === expected.ignoreCase;
274
275 // 7.4. Other pairs that do not both pass typeof value == 'object',
276 // equivalence is determined by ==.
277 } else if ((actual === null || typeof actual !== 'object') &&
278 (expected === null || typeof expected !== 'object')) {
279 return strict ? actual === expected : actual == expected;
280
281 // If both values are instances of typed arrays, wrap their underlying
282 // ArrayBuffers in a Buffer each to increase performance
283 // This optimization requires the arrays to have the same type as checked by
284 // Object.prototype.toString (aka pToString). Never perform binary
285 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
286 // bit patterns are not identical.
287 } else if (isView(actual) && isView(expected) &&
288 pToString(actual) === pToString(expected) &&
289 !(actual instanceof Float32Array ||
290 actual instanceof Float64Array)) {
291 return compare(new Uint8Array(actual.buffer),
292 new Uint8Array(expected.buffer)) === 0;
293
294 // 7.5 For all other Object pairs, including Array objects, equivalence is
295 // determined by having the same number of owned properties (as verified
296 // with Object.prototype.hasOwnProperty.call), the same set of keys
297 // (although not necessarily the same order), equivalent values for every
298 // corresponding key, and an identical 'prototype' property. Note: this
299 // accounts for both named and indexed properties on Arrays.
300 } else if (isBuffer(actual) !== isBuffer(expected)) {
301 return false;
302 } else {
303 memos = memos || {actual: [], expected: []};
304
305 var actualIndex = memos.actual.indexOf(actual);
306 if (actualIndex !== -1) {
307 if (actualIndex === memos.expected.indexOf(expected)) {
308 return true;
309 }
310 }
311
312 memos.actual.push(actual);
313 memos.expected.push(expected);
314
315 return objEquiv(actual, expected, strict, memos);
316 }
317 }
318
319 function isArguments(object) {
320 return Object.prototype.toString.call(object) == '[object Arguments]';
321 }
322
323 function objEquiv(a, b, strict, actualVisitedObjects) {
324 if (a === null || a === undefined || b === null || b === undefined)
325 return false;
326 // if one is a primitive, the other must be same
327 if (util.isPrimitive(a) || util.isPrimitive(b))
328 return a === b;
329 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
330 return false;
331 var aIsArgs = isArguments(a);
332 var bIsArgs = isArguments(b);
333 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
334 return false;
335 if (aIsArgs) {
336 a = pSlice.call(a);
337 b = pSlice.call(b);
338 return _deepEqual(a, b, strict);
339 }
340 var ka = objectKeys(a);
341 var kb = objectKeys(b);
342 var key, i;
343 // having the same number of owned properties (keys incorporates
344 // hasOwnProperty)
345 if (ka.length !== kb.length)
346 return false;
347 //the same set of keys (although not necessarily the same order),
348 ka.sort();
349 kb.sort();
350 //~~~cheap key test
351 for (i = ka.length - 1; i >= 0; i--) {
352 if (ka[i] !== kb[i])
353 return false;
354 }
355 //equivalent values for every corresponding key, and
356 //~~~possibly expensive deep test
357 for (i = ka.length - 1; i >= 0; i--) {
358 key = ka[i];
359 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
360 return false;
361 }
362 return true;
363 }
364
365 // 8. The non-equivalence assertion tests for any deep inequality.
366 // assert.notDeepEqual(actual, expected, message_opt);
367
368 assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
369 if (_deepEqual(actual, expected, false)) {
370 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
371 }
372 };
373
374 assert.notDeepStrictEqual = notDeepStrictEqual;
375 function notDeepStrictEqual(actual, expected, message) {
376 if (_deepEqual(actual, expected, true)) {
377 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
378 }
379 }
380
381
382 // 9. The strict equality assertion tests strict equality, as determined by ===.
383 // assert.strictEqual(actual, expected, message_opt);
384
385 assert.strictEqual = function strictEqual(actual, expected, message) {
386 if (actual !== expected) {
387 fail(actual, expected, message, '===', assert.strictEqual);
388 }
389 };
390
391 // 10. The strict non-equality assertion tests for strict inequality, as
392 // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
393
394 assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
395 if (actual === expected) {
396 fail(actual, expected, message, '!==', assert.notStrictEqual);
397 }
398 };
399
400 function expectedException(actual, expected) {
401 if (!actual || !expected) {
402 return false;
403 }
404
405 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
406 return expected.test(actual);
407 }
408
409 try {
410 if (actual instanceof expected) {
411 return true;
412 }
413 } catch (e) {
414 // Ignore. The instanceof check doesn't work for arrow functions.
415 }
416
417 if (Error.isPrototypeOf(expected)) {
418 return false;
419 }
420
421 return expected.call({}, actual) === true;
422 }
423
424 function _tryBlock(block) {
425 var error;
426 try {
427 block();
428 } catch (e) {
429 error = e;
430 }
431 return error;
432 }
433
434 function _throws(shouldThrow, block, expected, message) {
435 var actual;
436
437 if (typeof block !== 'function') {
438 throw new TypeError('"block" argument must be a function');
439 }
440
441 if (typeof expected === 'string') {
442 message = expected;
443 expected = null;
444 }
445
446 actual = _tryBlock(block);
447
448 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
449 (message ? ' ' + message : '.');
450
451 if (shouldThrow && !actual) {
452 fail(actual, expected, 'Missing expected exception' + message);
453 }
454
455 var userProvidedMessage = typeof message === 'string';
456 var isUnwantedException = !shouldThrow && util.isError(actual);
457 var isUnexpectedException = !shouldThrow && actual && !expected;
458
459 if ((isUnwantedException &&
460 userProvidedMessage &&
461 expectedException(actual, expected)) ||
462 isUnexpectedException) {
463 fail(actual, expected, 'Got unwanted exception' + message);
464 }
465
466 if ((shouldThrow && actual && expected &&
467 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
468 throw actual;
469 }
470 }
471
472 // 11. Expected to throw an error:
473 // assert.throws(block, Error_opt, message_opt);
474
475 assert.throws = function(block, /*optional*/error, /*optional*/message) {
476 _throws(true, block, error, message);
477 };
478
479 // EXTENSION! This is annoying to write outside this module.
480 assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
481 _throws(false, block, error, message);
482 };
483
484 assert.ifError = function(err) { if (err) throw err; };
485
486 var objectKeys = Object.keys || function (obj) {
487 var keys = [];
488 for (var key in obj) {
489 if (hasOwn.call(obj, key)) keys.push(key);
490 }
491 return keys;
492 };
493
494 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
495 },{"util/":33}],2:[function(require,module,exports){
496 'use strict'
497
498 exports.byteLength = byteLength
499 exports.toByteArray = toByteArray
500 exports.fromByteArray = fromByteArray
501
502 var lookup = []
503 var revLookup = []
504 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
505
506 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
507 for (var i = 0, len = code.length; i < len; ++i) {
508 lookup[i] = code[i]
509 revLookup[code.charCodeAt(i)] = i
510 }
511
512 revLookup['-'.charCodeAt(0)] = 62
513 revLookup['_'.charCodeAt(0)] = 63
514
515 function placeHoldersCount (b64) {
516 var len = b64.length
517 if (len % 4 > 0) {
518 throw new Error('Invalid string. Length must be a multiple of 4')
519 }
520
521 // the number of equal signs (place holders)
522 // if there are two placeholders, than the two characters before it
523 // represent one byte
524 // if there is only one, then the three characters before it represent 2 bytes
525 // this is just a cheap hack to not do indexOf twice
526 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
527 }
528
529 function byteLength (b64) {
530 // base64 is 4/3 + up to two characters of the original data
531 return b64.length * 3 / 4 - placeHoldersCount(b64)
532 }
533
534 function toByteArray (b64) {
535 var i, j, l, tmp, placeHolders, arr
536 var len = b64.length
537 placeHolders = placeHoldersCount(b64)
538
539 arr = new Arr(len * 3 / 4 - placeHolders)
540
541 // if there are placeholders, only get up to the last complete 4 chars
542 l = placeHolders > 0 ? len - 4 : len
543
544 var L = 0
545
546 for (i = 0, j = 0; i < l; i += 4, j += 3) {
547 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
548 arr[L++] = (tmp >> 16) & 0xFF
549 arr[L++] = (tmp >> 8) & 0xFF
550 arr[L++] = tmp & 0xFF
551 }
552
553 if (placeHolders === 2) {
554 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
555 arr[L++] = tmp & 0xFF
556 } else if (placeHolders === 1) {
557 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
558 arr[L++] = (tmp >> 8) & 0xFF
559 arr[L++] = tmp & 0xFF
560 }
561
562 return arr
563 }
564
565 function tripletToBase64 (num) {
566 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
567 }
568
569 function encodeChunk (uint8, start, end) {
570 var tmp
571 var output = []
572 for (var i = start; i < end; i += 3) {
573 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
574 output.push(tripletToBase64(tmp))
575 }
576 return output.join('')
577 }
578
579 function fromByteArray (uint8) {
580 var tmp
581 var len = uint8.length
582 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
583 var output = ''
584 var parts = []
585 var maxChunkLength = 16383 // must be multiple of 3
586
587 // go through the array every three bytes, we'll deal with trailing stuff later
588 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
589 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
590 }
591
592 // pad the end with zeros, but make sure to not forget the extra bytes
593 if (extraBytes === 1) {
594 tmp = uint8[len - 1]
595 output += lookup[tmp >> 2]
596 output += lookup[(tmp << 4) & 0x3F]
597 output += '=='
598 } else if (extraBytes === 2) {
599 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
600 output += lookup[tmp >> 10]
601 output += lookup[(tmp >> 4) & 0x3F]
602 output += lookup[(tmp << 2) & 0x3F]
603 output += '='
604 }
605
606 parts.push(output)
607
608 return parts.join('')
609 }
610
611 },{}],3:[function(require,module,exports){
612
613 },{}],4:[function(require,module,exports){
614 (function (global){
615 'use strict';
616
617 var buffer = require('buffer');
618 var Buffer = buffer.Buffer;
619 var SlowBuffer = buffer.SlowBuffer;
620 var MAX_LEN = buffer.kMaxLength || 2147483647;
621 exports.alloc = function alloc(size, fill, encoding) {
622 if (typeof Buffer.alloc === 'function') {
623 return Buffer.alloc(size, fill, encoding);
624 }
625 if (typeof encoding === 'number') {
626 throw new TypeError('encoding must not be number');
627 }
628 if (typeof size !== 'number') {
629 throw new TypeError('size must be a number');
630 }
631 if (size > MAX_LEN) {
632 throw new RangeError('size is too large');
633 }
634 var enc = encoding;
635 var _fill = fill;
636 if (_fill === undefined) {
637 enc = undefined;
638 _fill = 0;
639 }
640 var buf = new Buffer(size);
641 if (typeof _fill === 'string') {
642 var fillBuf = new Buffer(_fill, enc);
643 var flen = fillBuf.length;
644 var i = -1;
645 while (++i < size) {
646 buf[i] = fillBuf[i % flen];
647 }
648 } else {
649 buf.fill(_fill);
650 }
651 return buf;
652 }
653 exports.allocUnsafe = function allocUnsafe(size) {
654 if (typeof Buffer.allocUnsafe === 'function') {
655 return Buffer.allocUnsafe(size);
656 }
657 if (typeof size !== 'number') {
658 throw new TypeError('size must be a number');
659 }
660 if (size > MAX_LEN) {
661 throw new RangeError('size is too large');
662 }
663 return new Buffer(size);
664 }
665 exports.from = function from(value, encodingOrOffset, length) {
666 if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
667 return Buffer.from(value, encodingOrOffset, length);
668 }
669 if (typeof value === 'number') {
670 throw new TypeError('"value" argument must not be a number');
671 }
672 if (typeof value === 'string') {
673 return new Buffer(value, encodingOrOffset);
674 }
675 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
676 var offset = encodingOrOffset;
677 if (arguments.length === 1) {
678 return new Buffer(value);
679 }
680 if (typeof offset === 'undefined') {
681 offset = 0;
682 }
683 var len = length;
684 if (typeof len === 'undefined') {
685 len = value.byteLength - offset;
686 }
687 if (offset >= value.byteLength) {
688 throw new RangeError('\'offset\' is out of bounds');
689 }
690 if (len > value.byteLength - offset) {
691 throw new RangeError('\'length\' is out of bounds');
692 }
693 return new Buffer(value.slice(offset, offset + len));
694 }
695 if (Buffer.isBuffer(value)) {
696 var out = new Buffer(value.length);
697 value.copy(out, 0, 0, value.length);
698 return out;
699 }
700 if (value) {
701 if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
702 return new Buffer(value);
703 }
704 if (value.type === 'Buffer' && Array.isArray(value.data)) {
705 return new Buffer(value.data);
706 }
707 }
708
709 throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
710 }
711 exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
712 if (typeof Buffer.allocUnsafeSlow === 'function') {
713 return Buffer.allocUnsafeSlow(size);
714 }
715 if (typeof size !== 'number') {
716 throw new TypeError('size must be a number');
717 }
718 if (size >= MAX_LEN) {
719 throw new RangeError('size is too large');
720 }
721 return new SlowBuffer(size);
722 }
723
724 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
725 },{"buffer":5}],5:[function(require,module,exports){
726 /*!
727 * The buffer module from node.js, for the browser.
728 *
729 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
730 * @license MIT
731 */
732 /* eslint-disable no-proto */
733
734 'use strict'
735
736 var base64 = require('base64-js')
737 var ieee754 = require('ieee754')
738
739 exports.Buffer = Buffer
740 exports.SlowBuffer = SlowBuffer
741 exports.INSPECT_MAX_BYTES = 50
742
743 var K_MAX_LENGTH = 0x7fffffff
744 exports.kMaxLength = K_MAX_LENGTH
745
746 /**
747 * If `Buffer.TYPED_ARRAY_SUPPORT`:
748 * === true Use Uint8Array implementation (fastest)
749 * === false Print warning and recommend using `buffer` v4.x which has an Object
750 * implementation (most compatible, even IE6)
751 *
752 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
753 * Opera 11.6+, iOS 4.2+.
754 *
755 * We report that the browser does not support typed arrays if the are not subclassable
756 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
757 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
758 * for __proto__ and has a buggy typed array implementation.
759 */
760 Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
761
762 if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
763 typeof console.error === 'function') {
764 console.error(
765 'This browser lacks typed array (Uint8Array) support which is required by ' +
766 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
767 )
768 }
769
770 function typedArraySupport () {
771 // Can typed array instances can be augmented?
772 try {
773 var arr = new Uint8Array(1)
774 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
775 return arr.foo() === 42
776 } catch (e) {
777 return false
778 }
779 }
780
781 function createBuffer (length) {
782 if (length > K_MAX_LENGTH) {
783 throw new RangeError('Invalid typed array length')
784 }
785 // Return an augmented `Uint8Array` instance
786 var buf = new Uint8Array(length)
787 buf.__proto__ = Buffer.prototype
788 return buf
789 }
790
791 /**
792 * The Buffer constructor returns instances of `Uint8Array` that have their
793 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
794 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
795 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
796 * returns a single octet.
797 *
798 * The `Uint8Array` prototype remains unmodified.
799 */
800
801 function Buffer (arg, encodingOrOffset, length) {
802 // Common case.
803 if (typeof arg === 'number') {
804 if (typeof encodingOrOffset === 'string') {
805 throw new Error(
806 'If encoding is specified then the first argument must be a string'
807 )
808 }
809 return allocUnsafe(arg)
810 }
811 return from(arg, encodingOrOffset, length)
812 }
813
814 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
815 if (typeof Symbol !== 'undefined' && Symbol.species &&
816 Buffer[Symbol.species] === Buffer) {
817 Object.defineProperty(Buffer, Symbol.species, {
818 value: null,
819 configurable: true,
820 enumerable: false,
821 writable: false
822 })
823 }
824
825 Buffer.poolSize = 8192 // not used by this implementation
826
827 function from (value, encodingOrOffset, length) {
828 if (typeof value === 'number') {
829 throw new TypeError('"value" argument must not be a number')
830 }
831
832 if (value instanceof ArrayBuffer) {
833 return fromArrayBuffer(value, encodingOrOffset, length)
834 }
835
836 if (typeof value === 'string') {
837 return fromString(value, encodingOrOffset)
838 }
839
840 return fromObject(value)
841 }
842
843 /**
844 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
845 * if value is a number.
846 * Buffer.from(str[, encoding])
847 * Buffer.from(array)
848 * Buffer.from(buffer)
849 * Buffer.from(arrayBuffer[, byteOffset[, length]])
850 **/
851 Buffer.from = function (value, encodingOrOffset, length) {
852 return from(value, encodingOrOffset, length)
853 }
854
855 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
856 // https://github.com/feross/buffer/pull/148
857 Buffer.prototype.__proto__ = Uint8Array.prototype
858 Buffer.__proto__ = Uint8Array
859
860 function assertSize (size) {
861 if (typeof size !== 'number') {
862 throw new TypeError('"size" argument must be a number')
863 } else if (size < 0) {
864 throw new RangeError('"size" argument must not be negative')
865 }
866 }
867
868 function alloc (size, fill, encoding) {
869 assertSize(size)
870 if (size <= 0) {
871 return createBuffer(size)
872 }
873 if (fill !== undefined) {
874 // Only pay attention to encoding if it's a string. This
875 // prevents accidentally sending in a number that would
876 // be interpretted as a start offset.
877 return typeof encoding === 'string'
878 ? createBuffer(size).fill(fill, encoding)
879 : createBuffer(size).fill(fill)
880 }
881 return createBuffer(size)
882 }
883
884 /**
885 * Creates a new filled Buffer instance.
886 * alloc(size[, fill[, encoding]])
887 **/
888 Buffer.alloc = function (size, fill, encoding) {
889 return alloc(size, fill, encoding)
890 }
891
892 function allocUnsafe (size) {
893 assertSize(size)
894 return createBuffer(size < 0 ? 0 : checked(size) | 0)
895 }
896
897 /**
898 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
899 * */
900 Buffer.allocUnsafe = function (size) {
901 return allocUnsafe(size)
902 }
903 /**
904 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
905 */
906 Buffer.allocUnsafeSlow = function (size) {
907 return allocUnsafe(size)
908 }
909
910 function fromString (string, encoding) {
911 if (typeof encoding !== 'string' || encoding === '') {
912 encoding = 'utf8'
913 }
914
915 if (!Buffer.isEncoding(encoding)) {
916 throw new TypeError('"encoding" must be a valid string encoding')
917 }
918
919 var length = byteLength(string, encoding) | 0
920 var buf = createBuffer(length)
921
922 var actual = buf.write(string, encoding)
923
924 if (actual !== length) {
925 // Writing a hex string, for example, that contains invalid characters will
926 // cause everything after the first invalid character to be ignored. (e.g.
927 // 'abxxcd' will be treated as 'ab')
928 buf = buf.slice(0, actual)
929 }
930
931 return buf
932 }
933
934 function fromArrayLike (array) {
935 var length = array.length < 0 ? 0 : checked(array.length) | 0
936 var buf = createBuffer(length)
937 for (var i = 0; i < length; i += 1) {
938 buf[i] = array[i] & 255
939 }
940 return buf
941 }
942
943 function fromArrayBuffer (array, byteOffset, length) {
944 if (byteOffset < 0 || array.byteLength < byteOffset) {
945 throw new RangeError('\'offset\' is out of bounds')
946 }
947
948 if (array.byteLength < byteOffset + (length || 0)) {
949 throw new RangeError('\'length\' is out of bounds')
950 }
951
952 var buf
953 if (byteOffset === undefined && length === undefined) {
954 buf = new Uint8Array(array)
955 } else if (length === undefined) {
956 buf = new Uint8Array(array, byteOffset)
957 } else {
958 buf = new Uint8Array(array, byteOffset, length)
959 }
960
961 // Return an augmented `Uint8Array` instance
962 buf.__proto__ = Buffer.prototype
963 return buf
964 }
965
966 function fromObject (obj) {
967 if (Buffer.isBuffer(obj)) {
968 var len = checked(obj.length) | 0
969 var buf = createBuffer(len)
970
971 if (buf.length === 0) {
972 return buf
973 }
974
975 obj.copy(buf, 0, 0, len)
976 return buf
977 }
978
979 if (obj) {
980 if (isArrayBufferView(obj) || 'length' in obj) {
981 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
982 return createBuffer(0)
983 }
984 return fromArrayLike(obj)
985 }
986
987 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
988 return fromArrayLike(obj.data)
989 }
990 }
991
992 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
993 }
994
995 function checked (length) {
996 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
997 // length is NaN (which is otherwise coerced to zero.)
998 if (length >= K_MAX_LENGTH) {
999 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1000 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
1001 }
1002 return length | 0
1003 }
1004
1005 function SlowBuffer (length) {
1006 if (+length != length) { // eslint-disable-line eqeqeq
1007 length = 0
1008 }
1009 return Buffer.alloc(+length)
1010 }
1011
1012 Buffer.isBuffer = function isBuffer (b) {
1013 return b != null && b._isBuffer === true
1014 }
1015
1016 Buffer.compare = function compare (a, b) {
1017 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
1018 throw new TypeError('Arguments must be Buffers')
1019 }
1020
1021 if (a === b) return 0
1022
1023 var x = a.length
1024 var y = b.length
1025
1026 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1027 if (a[i] !== b[i]) {
1028 x = a[i]
1029 y = b[i]
1030 break
1031 }
1032 }
1033
1034 if (x < y) return -1
1035 if (y < x) return 1
1036 return 0
1037 }
1038
1039 Buffer.isEncoding = function isEncoding (encoding) {
1040 switch (String(encoding).toLowerCase()) {
1041 case 'hex':
1042 case 'utf8':
1043 case 'utf-8':
1044 case 'ascii':
1045 case 'latin1':
1046 case 'binary':
1047 case 'base64':
1048 case 'ucs2':
1049 case 'ucs-2':
1050 case 'utf16le':
1051 case 'utf-16le':
1052 return true
1053 default:
1054 return false
1055 }
1056 }
1057
1058 Buffer.concat = function concat (list, length) {
1059 if (!Array.isArray(list)) {
1060 throw new TypeError('"list" argument must be an Array of Buffers')
1061 }
1062
1063 if (list.length === 0) {
1064 return Buffer.alloc(0)
1065 }
1066
1067 var i
1068 if (length === undefined) {
1069 length = 0
1070 for (i = 0; i < list.length; ++i) {
1071 length += list[i].length
1072 }
1073 }
1074
1075 var buffer = Buffer.allocUnsafe(length)
1076 var pos = 0
1077 for (i = 0; i < list.length; ++i) {
1078 var buf = list[i]
1079 if (!Buffer.isBuffer(buf)) {
1080 throw new TypeError('"list" argument must be an Array of Buffers')
1081 }
1082 buf.copy(buffer, pos)
1083 pos += buf.length
1084 }
1085 return buffer
1086 }
1087
1088 function byteLength (string, encoding) {
1089 if (Buffer.isBuffer(string)) {
1090 return string.length
1091 }
1092 if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
1093 return string.byteLength
1094 }
1095 if (typeof string !== 'string') {
1096 string = '' + string
1097 }
1098
1099 var len = string.length
1100 if (len === 0) return 0
1101
1102 // Use a for loop to avoid recursion
1103 var loweredCase = false
1104 for (;;) {
1105 switch (encoding) {
1106 case 'ascii':
1107 case 'latin1':
1108 case 'binary':
1109 return len
1110 case 'utf8':
1111 case 'utf-8':
1112 case undefined:
1113 return utf8ToBytes(string).length
1114 case 'ucs2':
1115 case 'ucs-2':
1116 case 'utf16le':
1117 case 'utf-16le':
1118 return len * 2
1119 case 'hex':
1120 return len >>> 1
1121 case 'base64':
1122 return base64ToBytes(string).length
1123 default:
1124 if (loweredCase) return utf8ToBytes(string).length // assume utf8
1125 encoding = ('' + encoding).toLowerCase()
1126 loweredCase = true
1127 }
1128 }
1129 }
1130 Buffer.byteLength = byteLength
1131
1132 function slowToString (encoding, start, end) {
1133 var loweredCase = false
1134
1135 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1136 // property of a typed array.
1137
1138 // This behaves neither like String nor Uint8Array in that we set start/end
1139 // to their upper/lower bounds if the value passed is out of range.
1140 // undefined is handled specially as per ECMA-262 6th Edition,
1141 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
1142 if (start === undefined || start < 0) {
1143 start = 0
1144 }
1145 // Return early if start > this.length. Done here to prevent potential uint32
1146 // coercion fail below.
1147 if (start > this.length) {
1148 return ''
1149 }
1150
1151 if (end === undefined || end > this.length) {
1152 end = this.length
1153 }
1154
1155 if (end <= 0) {
1156 return ''
1157 }
1158
1159 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1160 end >>>= 0
1161 start >>>= 0
1162
1163 if (end <= start) {
1164 return ''
1165 }
1166
1167 if (!encoding) encoding = 'utf8'
1168
1169 while (true) {
1170 switch (encoding) {
1171 case 'hex':
1172 return hexSlice(this, start, end)
1173
1174 case 'utf8':
1175 case 'utf-8':
1176 return utf8Slice(this, start, end)
1177
1178 case 'ascii':
1179 return asciiSlice(this, start, end)
1180
1181 case 'latin1':
1182 case 'binary':
1183 return latin1Slice(this, start, end)
1184
1185 case 'base64':
1186 return base64Slice(this, start, end)
1187
1188 case 'ucs2':
1189 case 'ucs-2':
1190 case 'utf16le':
1191 case 'utf-16le':
1192 return utf16leSlice(this, start, end)
1193
1194 default:
1195 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1196 encoding = (encoding + '').toLowerCase()
1197 loweredCase = true
1198 }
1199 }
1200 }
1201
1202 // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1203 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1204 // reliably in a browserify context because there could be multiple different
1205 // copies of the 'buffer' package in use. This method works even for Buffer
1206 // instances that were created from another copy of the `buffer` package.
1207 // See: https://github.com/feross/buffer/issues/154
1208 Buffer.prototype._isBuffer = true
1209
1210 function swap (b, n, m) {
1211 var i = b[n]
1212 b[n] = b[m]
1213 b[m] = i
1214 }
1215
1216 Buffer.prototype.swap16 = function swap16 () {
1217 var len = this.length
1218 if (len % 2 !== 0) {
1219 throw new RangeError('Buffer size must be a multiple of 16-bits')
1220 }
1221 for (var i = 0; i < len; i += 2) {
1222 swap(this, i, i + 1)
1223 }
1224 return this
1225 }
1226
1227 Buffer.prototype.swap32 = function swap32 () {
1228 var len = this.length
1229 if (len % 4 !== 0) {
1230 throw new RangeError('Buffer size must be a multiple of 32-bits')
1231 }
1232 for (var i = 0; i < len; i += 4) {
1233 swap(this, i, i + 3)
1234 swap(this, i + 1, i + 2)
1235 }
1236 return this
1237 }
1238
1239 Buffer.prototype.swap64 = function swap64 () {
1240 var len = this.length
1241 if (len % 8 !== 0) {
1242 throw new RangeError('Buffer size must be a multiple of 64-bits')
1243 }
1244 for (var i = 0; i < len; i += 8) {
1245 swap(this, i, i + 7)
1246 swap(this, i + 1, i + 6)
1247 swap(this, i + 2, i + 5)
1248 swap(this, i + 3, i + 4)
1249 }
1250 return this
1251 }
1252
1253 Buffer.prototype.toString = function toString () {
1254 var length = this.length
1255 if (length === 0) return ''
1256 if (arguments.length === 0) return utf8Slice(this, 0, length)
1257 return slowToString.apply(this, arguments)
1258 }
1259
1260 Buffer.prototype.equals = function equals (b) {
1261 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
1262 if (this === b) return true
1263 return Buffer.compare(this, b) === 0
1264 }
1265
1266 Buffer.prototype.inspect = function inspect () {
1267 var str = ''
1268 var max = exports.INSPECT_MAX_BYTES
1269 if (this.length > 0) {
1270 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
1271 if (this.length > max) str += ' ... '
1272 }
1273 return '<Buffer ' + str + '>'
1274 }
1275
1276 Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
1277 if (!Buffer.isBuffer(target)) {
1278 throw new TypeError('Argument must be a Buffer')
1279 }
1280
1281 if (start === undefined) {
1282 start = 0
1283 }
1284 if (end === undefined) {
1285 end = target ? target.length : 0
1286 }
1287 if (thisStart === undefined) {
1288 thisStart = 0
1289 }
1290 if (thisEnd === undefined) {
1291 thisEnd = this.length
1292 }
1293
1294 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1295 throw new RangeError('out of range index')
1296 }
1297
1298 if (thisStart >= thisEnd && start >= end) {
1299 return 0
1300 }
1301 if (thisStart >= thisEnd) {
1302 return -1
1303 }
1304 if (start >= end) {
1305 return 1
1306 }
1307
1308 start >>>= 0
1309 end >>>= 0
1310 thisStart >>>= 0
1311 thisEnd >>>= 0
1312
1313 if (this === target) return 0
1314
1315 var x = thisEnd - thisStart
1316 var y = end - start
1317 var len = Math.min(x, y)
1318
1319 var thisCopy = this.slice(thisStart, thisEnd)
1320 var targetCopy = target.slice(start, end)
1321
1322 for (var i = 0; i < len; ++i) {
1323 if (thisCopy[i] !== targetCopy[i]) {
1324 x = thisCopy[i]
1325 y = targetCopy[i]
1326 break
1327 }
1328 }
1329
1330 if (x < y) return -1
1331 if (y < x) return 1
1332 return 0
1333 }
1334
1335 // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
1336 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
1337 //
1338 // Arguments:
1339 // - buffer - a Buffer to search
1340 // - val - a string, Buffer, or number
1341 // - byteOffset - an index into `buffer`; will be clamped to an int32
1342 // - encoding - an optional encoding, relevant is val is a string
1343 // - dir - true for indexOf, false for lastIndexOf
1344 function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
1345 // Empty buffer means no match
1346 if (buffer.length === 0) return -1
1347
1348 // Normalize byteOffset
1349 if (typeof byteOffset === 'string') {
1350 encoding = byteOffset
1351 byteOffset = 0
1352 } else if (byteOffset > 0x7fffffff) {
1353 byteOffset = 0x7fffffff
1354 } else if (byteOffset < -0x80000000) {
1355 byteOffset = -0x80000000
1356 }
1357 byteOffset = +byteOffset // Coerce to Number.
1358 if (numberIsNaN(byteOffset)) {
1359 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
1360 byteOffset = dir ? 0 : (buffer.length - 1)
1361 }
1362
1363 // Normalize byteOffset: negative offsets start from the end of the buffer
1364 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
1365 if (byteOffset >= buffer.length) {
1366 if (dir) return -1
1367 else byteOffset = buffer.length - 1
1368 } else if (byteOffset < 0) {
1369 if (dir) byteOffset = 0
1370 else return -1
1371 }
1372
1373 // Normalize val
1374 if (typeof val === 'string') {
1375 val = Buffer.from(val, encoding)
1376 }
1377
1378 // Finally, search either indexOf (if dir is true) or lastIndexOf
1379 if (Buffer.isBuffer(val)) {
1380 // Special case: looking for empty string/buffer always fails
1381 if (val.length === 0) {
1382 return -1
1383 }
1384 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
1385 } else if (typeof val === 'number') {
1386 val = val & 0xFF // Search for a byte value [0-255]
1387 if (typeof Uint8Array.prototype.indexOf === 'function') {
1388 if (dir) {
1389 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
1390 } else {
1391 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
1392 }
1393 }
1394 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
1395 }
1396
1397 throw new TypeError('val must be string, number or Buffer')
1398 }
1399
1400 function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
1401 var indexSize = 1
1402 var arrLength = arr.length
1403 var valLength = val.length
1404
1405 if (encoding !== undefined) {
1406 encoding = String(encoding).toLowerCase()
1407 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
1408 encoding === 'utf16le' || encoding === 'utf-16le') {
1409 if (arr.length < 2 || val.length < 2) {
1410 return -1
1411 }
1412 indexSize = 2
1413 arrLength /= 2
1414 valLength /= 2
1415 byteOffset /= 2
1416 }
1417 }
1418
1419 function read (buf, i) {
1420 if (indexSize === 1) {
1421 return buf[i]
1422 } else {
1423 return buf.readUInt16BE(i * indexSize)
1424 }
1425 }
1426
1427 var i
1428 if (dir) {
1429 var foundIndex = -1
1430 for (i = byteOffset; i < arrLength; i++) {
1431 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1432 if (foundIndex === -1) foundIndex = i
1433 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
1434 } else {
1435 if (foundIndex !== -1) i -= i - foundIndex
1436 foundIndex = -1
1437 }
1438 }
1439 } else {
1440 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
1441 for (i = byteOffset; i >= 0; i--) {
1442 var found = true
1443 for (var j = 0; j < valLength; j++) {
1444 if (read(arr, i + j) !== read(val, j)) {
1445 found = false
1446 break
1447 }
1448 }
1449 if (found) return i
1450 }
1451 }
1452
1453 return -1
1454 }
1455
1456 Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1457 return this.indexOf(val, byteOffset, encoding) !== -1
1458 }
1459
1460 Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1461 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1462 }
1463
1464 Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1465 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1466 }
1467
1468 function hexWrite (buf, string, offset, length) {
1469 offset = Number(offset) || 0
1470 var remaining = buf.length - offset
1471 if (!length) {
1472 length = remaining
1473 } else {
1474 length = Number(length)
1475 if (length > remaining) {
1476 length = remaining
1477 }
1478 }
1479
1480 // must be an even number of digits
1481 var strLen = string.length
1482 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
1483
1484 if (length > strLen / 2) {
1485 length = strLen / 2
1486 }
1487 for (var i = 0; i < length; ++i) {
1488 var parsed = parseInt(string.substr(i * 2, 2), 16)
1489 if (numberIsNaN(parsed)) return i
1490 buf[offset + i] = parsed
1491 }
1492 return i
1493 }
1494
1495 function utf8Write (buf, string, offset, length) {
1496 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1497 }
1498
1499 function asciiWrite (buf, string, offset, length) {
1500 return blitBuffer(asciiToBytes(string), buf, offset, length)
1501 }
1502
1503 function latin1Write (buf, string, offset, length) {
1504 return asciiWrite(buf, string, offset, length)
1505 }
1506
1507 function base64Write (buf, string, offset, length) {
1508 return blitBuffer(base64ToBytes(string), buf, offset, length)
1509 }
1510
1511 function ucs2Write (buf, string, offset, length) {
1512 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1513 }
1514
1515 Buffer.prototype.write = function write (string, offset, length, encoding) {
1516 // Buffer#write(string)
1517 if (offset === undefined) {
1518 encoding = 'utf8'
1519 length = this.length
1520 offset = 0
1521 // Buffer#write(string, encoding)
1522 } else if (length === undefined && typeof offset === 'string') {
1523 encoding = offset
1524 length = this.length
1525 offset = 0
1526 // Buffer#write(string, offset[, length][, encoding])
1527 } else if (isFinite(offset)) {
1528 offset = offset >>> 0
1529 if (isFinite(length)) {
1530 length = length >>> 0
1531 if (encoding === undefined) encoding = 'utf8'
1532 } else {
1533 encoding = length
1534 length = undefined
1535 }
1536 } else {
1537 throw new Error(
1538 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1539 )
1540 }
1541
1542 var remaining = this.length - offset
1543 if (length === undefined || length > remaining) length = remaining
1544
1545 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
1546 throw new RangeError('Attempt to write outside buffer bounds')
1547 }
1548
1549 if (!encoding) encoding = 'utf8'
1550
1551 var loweredCase = false
1552 for (;;) {
1553 switch (encoding) {
1554 case 'hex':
1555 return hexWrite(this, string, offset, length)
1556
1557 case 'utf8':
1558 case 'utf-8':
1559 return utf8Write(this, string, offset, length)
1560
1561 case 'ascii':
1562 return asciiWrite(this, string, offset, length)
1563
1564 case 'latin1':
1565 case 'binary':
1566 return latin1Write(this, string, offset, length)
1567
1568 case 'base64':
1569 // Warning: maxLength not taken into account in base64Write
1570 return base64Write(this, string, offset, length)
1571
1572 case 'ucs2':
1573 case 'ucs-2':
1574 case 'utf16le':
1575 case 'utf-16le':
1576 return ucs2Write(this, string, offset, length)
1577
1578 default:
1579 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
1580 encoding = ('' + encoding).toLowerCase()
1581 loweredCase = true
1582 }
1583 }
1584 }
1585
1586 Buffer.prototype.toJSON = function toJSON () {
1587 return {
1588 type: 'Buffer',
1589 data: Array.prototype.slice.call(this._arr || this, 0)
1590 }
1591 }
1592
1593 function base64Slice (buf, start, end) {
1594 if (start === 0 && end === buf.length) {
1595 return base64.fromByteArray(buf)
1596 } else {
1597 return base64.fromByteArray(buf.slice(start, end))
1598 }
1599 }
1600
1601 function utf8Slice (buf, start, end) {
1602 end = Math.min(buf.length, end)
1603 var res = []
1604
1605 var i = start
1606 while (i < end) {
1607 var firstByte = buf[i]
1608 var codePoint = null
1609 var bytesPerSequence = (firstByte > 0xEF) ? 4
1610 : (firstByte > 0xDF) ? 3
1611 : (firstByte > 0xBF) ? 2
1612 : 1
1613
1614 if (i + bytesPerSequence <= end) {
1615 var secondByte, thirdByte, fourthByte, tempCodePoint
1616
1617 switch (bytesPerSequence) {
1618 case 1:
1619 if (firstByte < 0x80) {
1620 codePoint = firstByte
1621 }
1622 break
1623 case 2:
1624 secondByte = buf[i + 1]
1625 if ((secondByte & 0xC0) === 0x80) {
1626 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
1627 if (tempCodePoint > 0x7F) {
1628 codePoint = tempCodePoint
1629 }
1630 }
1631 break
1632 case 3:
1633 secondByte = buf[i + 1]
1634 thirdByte = buf[i + 2]
1635 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
1636 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
1637 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
1638 codePoint = tempCodePoint
1639 }
1640 }
1641 break
1642 case 4:
1643 secondByte = buf[i + 1]
1644 thirdByte = buf[i + 2]
1645 fourthByte = buf[i + 3]
1646 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1647 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1648 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1649 codePoint = tempCodePoint
1650 }
1651 }
1652 }
1653 }
1654
1655 if (codePoint === null) {
1656 // we did not generate a valid codePoint so insert a
1657 // replacement char (U+FFFD) and advance only 1 byte
1658 codePoint = 0xFFFD
1659 bytesPerSequence = 1
1660 } else if (codePoint > 0xFFFF) {
1661 // encode to utf16 (surrogate pair dance)
1662 codePoint -= 0x10000
1663 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1664 codePoint = 0xDC00 | codePoint & 0x3FF
1665 }
1666
1667 res.push(codePoint)
1668 i += bytesPerSequence
1669 }
1670
1671 return decodeCodePointsArray(res)
1672 }
1673
1674 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1675 // the lowest limit is Chrome, with 0x10000 args.
1676 // We go 1 magnitude less, for safety
1677 var MAX_ARGUMENTS_LENGTH = 0x1000
1678
1679 function decodeCodePointsArray (codePoints) {
1680 var len = codePoints.length
1681 if (len <= MAX_ARGUMENTS_LENGTH) {
1682 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
1683 }
1684
1685 // Decode in chunks to avoid "call stack size exceeded".
1686 var res = ''
1687 var i = 0
1688 while (i < len) {
1689 res += String.fromCharCode.apply(
1690 String,
1691 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
1692 )
1693 }
1694 return res
1695 }
1696
1697 function asciiSlice (buf, start, end) {
1698 var ret = ''
1699 end = Math.min(buf.length, end)
1700
1701 for (var i = start; i < end; ++i) {
1702 ret += String.fromCharCode(buf[i] & 0x7F)
1703 }
1704 return ret
1705 }
1706
1707 function latin1Slice (buf, start, end) {
1708 var ret = ''
1709 end = Math.min(buf.length, end)
1710
1711 for (var i = start; i < end; ++i) {
1712 ret += String.fromCharCode(buf[i])
1713 }
1714 return ret
1715 }
1716
1717 function hexSlice (buf, start, end) {
1718 var len = buf.length
1719
1720 if (!start || start < 0) start = 0
1721 if (!end || end < 0 || end > len) end = len
1722
1723 var out = ''
1724 for (var i = start; i < end; ++i) {
1725 out += toHex(buf[i])
1726 }
1727 return out
1728 }
1729
1730 function utf16leSlice (buf, start, end) {
1731 var bytes = buf.slice(start, end)
1732 var res = ''
1733 for (var i = 0; i < bytes.length; i += 2) {
1734 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
1735 }
1736 return res
1737 }
1738
1739 Buffer.prototype.slice = function slice (start, end) {
1740 var len = this.length
1741 start = ~~start
1742 end = end === undefined ? len : ~~end
1743
1744 if (start < 0) {
1745 start += len
1746 if (start < 0) start = 0
1747 } else if (start > len) {
1748 start = len
1749 }
1750
1751 if (end < 0) {
1752 end += len
1753 if (end < 0) end = 0
1754 } else if (end > len) {
1755 end = len
1756 }
1757
1758 if (end < start) end = start
1759
1760 var newBuf = this.subarray(start, end)
1761 // Return an augmented `Uint8Array` instance
1762 newBuf.__proto__ = Buffer.prototype
1763 return newBuf
1764 }
1765
1766 /*
1767 * Need to make sure that buffer isn't trying to write out of bounds.
1768 */
1769 function checkOffset (offset, ext, length) {
1770 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1771 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1772 }
1773
1774 Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1775 offset = offset >>> 0
1776 byteLength = byteLength >>> 0
1777 if (!noAssert) checkOffset(offset, byteLength, this.length)
1778
1779 var val = this[offset]
1780 var mul = 1
1781 var i = 0
1782 while (++i < byteLength && (mul *= 0x100)) {
1783 val += this[offset + i] * mul
1784 }
1785
1786 return val
1787 }
1788
1789 Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1790 offset = offset >>> 0
1791 byteLength = byteLength >>> 0
1792 if (!noAssert) {
1793 checkOffset(offset, byteLength, this.length)
1794 }
1795
1796 var val = this[offset + --byteLength]
1797 var mul = 1
1798 while (byteLength > 0 && (mul *= 0x100)) {
1799 val += this[offset + --byteLength] * mul
1800 }
1801
1802 return val
1803 }
1804
1805 Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1806 offset = offset >>> 0
1807 if (!noAssert) checkOffset(offset, 1, this.length)
1808 return this[offset]
1809 }
1810
1811 Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1812 offset = offset >>> 0
1813 if (!noAssert) checkOffset(offset, 2, this.length)
1814 return this[offset] | (this[offset + 1] << 8)
1815 }
1816
1817 Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1818 offset = offset >>> 0
1819 if (!noAssert) checkOffset(offset, 2, this.length)
1820 return (this[offset] << 8) | this[offset + 1]
1821 }
1822
1823 Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1824 offset = offset >>> 0
1825 if (!noAssert) checkOffset(offset, 4, this.length)
1826
1827 return ((this[offset]) |
1828 (this[offset + 1] << 8) |
1829 (this[offset + 2] << 16)) +
1830 (this[offset + 3] * 0x1000000)
1831 }
1832
1833 Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1834 offset = offset >>> 0
1835 if (!noAssert) checkOffset(offset, 4, this.length)
1836
1837 return (this[offset] * 0x1000000) +
1838 ((this[offset + 1] << 16) |
1839 (this[offset + 2] << 8) |
1840 this[offset + 3])
1841 }
1842
1843 Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1844 offset = offset >>> 0
1845 byteLength = byteLength >>> 0
1846 if (!noAssert) checkOffset(offset, byteLength, this.length)
1847
1848 var val = this[offset]
1849 var mul = 1
1850 var i = 0
1851 while (++i < byteLength && (mul *= 0x100)) {
1852 val += this[offset + i] * mul
1853 }
1854 mul *= 0x80
1855
1856 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1857
1858 return val
1859 }
1860
1861 Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1862 offset = offset >>> 0
1863 byteLength = byteLength >>> 0
1864 if (!noAssert) checkOffset(offset, byteLength, this.length)
1865
1866 var i = byteLength
1867 var mul = 1
1868 var val = this[offset + --i]
1869 while (i > 0 && (mul *= 0x100)) {
1870 val += this[offset + --i] * mul
1871 }
1872 mul *= 0x80
1873
1874 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1875
1876 return val
1877 }
1878
1879 Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1880 offset = offset >>> 0
1881 if (!noAssert) checkOffset(offset, 1, this.length)
1882 if (!(this[offset] & 0x80)) return (this[offset])
1883 return ((0xff - this[offset] + 1) * -1)
1884 }
1885
1886 Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1887 offset = offset >>> 0
1888 if (!noAssert) checkOffset(offset, 2, this.length)
1889 var val = this[offset] | (this[offset + 1] << 8)
1890 return (val & 0x8000) ? val | 0xFFFF0000 : val
1891 }
1892
1893 Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1894 offset = offset >>> 0
1895 if (!noAssert) checkOffset(offset, 2, this.length)
1896 var val = this[offset + 1] | (this[offset] << 8)
1897 return (val & 0x8000) ? val | 0xFFFF0000 : val
1898 }
1899
1900 Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1901 offset = offset >>> 0
1902 if (!noAssert) checkOffset(offset, 4, this.length)
1903
1904 return (this[offset]) |
1905 (this[offset + 1] << 8) |
1906 (this[offset + 2] << 16) |
1907 (this[offset + 3] << 24)
1908 }
1909
1910 Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1911 offset = offset >>> 0
1912 if (!noAssert) checkOffset(offset, 4, this.length)
1913
1914 return (this[offset] << 24) |
1915 (this[offset + 1] << 16) |
1916 (this[offset + 2] << 8) |
1917 (this[offset + 3])
1918 }
1919
1920 Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1921 offset = offset >>> 0
1922 if (!noAssert) checkOffset(offset, 4, this.length)
1923 return ieee754.read(this, offset, true, 23, 4)
1924 }
1925
1926 Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1927 offset = offset >>> 0
1928 if (!noAssert) checkOffset(offset, 4, this.length)
1929 return ieee754.read(this, offset, false, 23, 4)
1930 }
1931
1932 Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1933 offset = offset >>> 0
1934 if (!noAssert) checkOffset(offset, 8, this.length)
1935 return ieee754.read(this, offset, true, 52, 8)
1936 }
1937
1938 Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1939 offset = offset >>> 0
1940 if (!noAssert) checkOffset(offset, 8, this.length)
1941 return ieee754.read(this, offset, false, 52, 8)
1942 }
1943
1944 function checkInt (buf, value, offset, ext, max, min) {
1945 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
1946 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
1947 if (offset + ext > buf.length) throw new RangeError('Index out of range')
1948 }
1949
1950 Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1951 value = +value
1952 offset = offset >>> 0
1953 byteLength = byteLength >>> 0
1954 if (!noAssert) {
1955 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1956 checkInt(this, value, offset, byteLength, maxBytes, 0)
1957 }
1958
1959 var mul = 1
1960 var i = 0
1961 this[offset] = value & 0xFF
1962 while (++i < byteLength && (mul *= 0x100)) {
1963 this[offset + i] = (value / mul) & 0xFF
1964 }
1965
1966 return offset + byteLength
1967 }
1968
1969 Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1970 value = +value
1971 offset = offset >>> 0
1972 byteLength = byteLength >>> 0
1973 if (!noAssert) {
1974 var maxBytes = Math.pow(2, 8 * byteLength) - 1
1975 checkInt(this, value, offset, byteLength, maxBytes, 0)
1976 }
1977
1978 var i = byteLength - 1
1979 var mul = 1
1980 this[offset + i] = value & 0xFF
1981 while (--i >= 0 && (mul *= 0x100)) {
1982 this[offset + i] = (value / mul) & 0xFF
1983 }
1984
1985 return offset + byteLength
1986 }
1987
1988 Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1989 value = +value
1990 offset = offset >>> 0
1991 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1992 this[offset] = (value & 0xff)
1993 return offset + 1
1994 }
1995
1996 Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1997 value = +value
1998 offset = offset >>> 0
1999 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2000 this[offset] = (value & 0xff)
2001 this[offset + 1] = (value >>> 8)
2002 return offset + 2
2003 }
2004
2005 Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
2006 value = +value
2007 offset = offset >>> 0
2008 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
2009 this[offset] = (value >>> 8)
2010 this[offset + 1] = (value & 0xff)
2011 return offset + 2
2012 }
2013
2014 Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
2015 value = +value
2016 offset = offset >>> 0
2017 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2018 this[offset + 3] = (value >>> 24)
2019 this[offset + 2] = (value >>> 16)
2020 this[offset + 1] = (value >>> 8)
2021 this[offset] = (value & 0xff)
2022 return offset + 4
2023 }
2024
2025 Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
2026 value = +value
2027 offset = offset >>> 0
2028 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
2029 this[offset] = (value >>> 24)
2030 this[offset + 1] = (value >>> 16)
2031 this[offset + 2] = (value >>> 8)
2032 this[offset + 3] = (value & 0xff)
2033 return offset + 4
2034 }
2035
2036 Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
2037 value = +value
2038 offset = offset >>> 0
2039 if (!noAssert) {
2040 var limit = Math.pow(2, (8 * byteLength) - 1)
2041
2042 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2043 }
2044
2045 var i = 0
2046 var mul = 1
2047 var sub = 0
2048 this[offset] = value & 0xFF
2049 while (++i < byteLength && (mul *= 0x100)) {
2050 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2051 sub = 1
2052 }
2053 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2054 }
2055
2056 return offset + byteLength
2057 }
2058
2059 Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
2060 value = +value
2061 offset = offset >>> 0
2062 if (!noAssert) {
2063 var limit = Math.pow(2, (8 * byteLength) - 1)
2064
2065 checkInt(this, value, offset, byteLength, limit - 1, -limit)
2066 }
2067
2068 var i = byteLength - 1
2069 var mul = 1
2070 var sub = 0
2071 this[offset + i] = value & 0xFF
2072 while (--i >= 0 && (mul *= 0x100)) {
2073 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2074 sub = 1
2075 }
2076 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
2077 }
2078
2079 return offset + byteLength
2080 }
2081
2082 Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
2083 value = +value
2084 offset = offset >>> 0
2085 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
2086 if (value < 0) value = 0xff + value + 1
2087 this[offset] = (value & 0xff)
2088 return offset + 1
2089 }
2090
2091 Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
2092 value = +value
2093 offset = offset >>> 0
2094 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2095 this[offset] = (value & 0xff)
2096 this[offset + 1] = (value >>> 8)
2097 return offset + 2
2098 }
2099
2100 Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
2101 value = +value
2102 offset = offset >>> 0
2103 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
2104 this[offset] = (value >>> 8)
2105 this[offset + 1] = (value & 0xff)
2106 return offset + 2
2107 }
2108
2109 Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
2110 value = +value
2111 offset = offset >>> 0
2112 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2113 this[offset] = (value & 0xff)
2114 this[offset + 1] = (value >>> 8)
2115 this[offset + 2] = (value >>> 16)
2116 this[offset + 3] = (value >>> 24)
2117 return offset + 4
2118 }
2119
2120 Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
2121 value = +value
2122 offset = offset >>> 0
2123 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
2124 if (value < 0) value = 0xffffffff + value + 1
2125 this[offset] = (value >>> 24)
2126 this[offset + 1] = (value >>> 16)
2127 this[offset + 2] = (value >>> 8)
2128 this[offset + 3] = (value & 0xff)
2129 return offset + 4
2130 }
2131
2132 function checkIEEE754 (buf, value, offset, ext, max, min) {
2133 if (offset + ext > buf.length) throw new RangeError('Index out of range')
2134 if (offset < 0) throw new RangeError('Index out of range')
2135 }
2136
2137 function writeFloat (buf, value, offset, littleEndian, noAssert) {
2138 value = +value
2139 offset = offset >>> 0
2140 if (!noAssert) {
2141 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2142 }
2143 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2144 return offset + 4
2145 }
2146
2147 Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2148 return writeFloat(this, value, offset, true, noAssert)
2149 }
2150
2151 Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2152 return writeFloat(this, value, offset, false, noAssert)
2153 }
2154
2155 function writeDouble (buf, value, offset, littleEndian, noAssert) {
2156 value = +value
2157 offset = offset >>> 0
2158 if (!noAssert) {
2159 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2160 }
2161 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2162 return offset + 8
2163 }
2164
2165 Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2166 return writeDouble(this, value, offset, true, noAssert)
2167 }
2168
2169 Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
2170 return writeDouble(this, value, offset, false, noAssert)
2171 }
2172
2173 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2174 Buffer.prototype.copy = function copy (target, targetStart, start, end) {
2175 if (!start) start = 0
2176 if (!end && end !== 0) end = this.length
2177 if (targetStart >= target.length) targetStart = target.length
2178 if (!targetStart) targetStart = 0
2179 if (end > 0 && end < start) end = start
2180
2181 // Copy 0 bytes; we're done
2182 if (end === start) return 0
2183 if (target.length === 0 || this.length === 0) return 0
2184
2185 // Fatal error conditions
2186 if (targetStart < 0) {
2187 throw new RangeError('targetStart out of bounds')
2188 }
2189 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
2190 if (end < 0) throw new RangeError('sourceEnd out of bounds')
2191
2192 // Are we oob?
2193 if (end > this.length) end = this.length
2194 if (target.length - targetStart < end - start) {
2195 end = target.length - targetStart + start
2196 }
2197
2198 var len = end - start
2199 var i
2200
2201 if (this === target && start < targetStart && targetStart < end) {
2202 // descending copy from end
2203 for (i = len - 1; i >= 0; --i) {
2204 target[i + targetStart] = this[i + start]
2205 }
2206 } else if (len < 1000) {
2207 // ascending copy from start
2208 for (i = 0; i < len; ++i) {
2209 target[i + targetStart] = this[i + start]
2210 }
2211 } else {
2212 Uint8Array.prototype.set.call(
2213 target,
2214 this.subarray(start, start + len),
2215 targetStart
2216 )
2217 }
2218
2219 return len
2220 }
2221
2222 // Usage:
2223 // buffer.fill(number[, offset[, end]])
2224 // buffer.fill(buffer[, offset[, end]])
2225 // buffer.fill(string[, offset[, end]][, encoding])
2226 Buffer.prototype.fill = function fill (val, start, end, encoding) {
2227 // Handle string cases:
2228 if (typeof val === 'string') {
2229 if (typeof start === 'string') {
2230 encoding = start
2231 start = 0
2232 end = this.length
2233 } else if (typeof end === 'string') {
2234 encoding = end
2235 end = this.length
2236 }
2237 if (val.length === 1) {
2238 var code = val.charCodeAt(0)
2239 if (code < 256) {
2240 val = code
2241 }
2242 }
2243 if (encoding !== undefined && typeof encoding !== 'string') {
2244 throw new TypeError('encoding must be a string')
2245 }
2246 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
2247 throw new TypeError('Unknown encoding: ' + encoding)
2248 }
2249 } else if (typeof val === 'number') {
2250 val = val & 255
2251 }
2252
2253 // Invalid ranges are not set to a default, so can range check early.
2254 if (start < 0 || this.length < start || this.length < end) {
2255 throw new RangeError('Out of range index')
2256 }
2257
2258 if (end <= start) {
2259 return this
2260 }
2261
2262 start = start >>> 0
2263 end = end === undefined ? this.length : end >>> 0
2264
2265 if (!val) val = 0
2266
2267 var i
2268 if (typeof val === 'number') {
2269 for (i = start; i < end; ++i) {
2270 this[i] = val
2271 }
2272 } else {
2273 var bytes = Buffer.isBuffer(val)
2274 ? val
2275 : new Buffer(val, encoding)
2276 var len = bytes.length
2277 for (i = 0; i < end - start; ++i) {
2278 this[i + start] = bytes[i % len]
2279 }
2280 }
2281
2282 return this
2283 }
2284
2285 // HELPER FUNCTIONS
2286 // ================
2287
2288 var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2289
2290 function base64clean (str) {
2291 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2292 str = str.trim().replace(INVALID_BASE64_RE, '')
2293 // Node converts strings with length < 2 to ''
2294 if (str.length < 2) return ''
2295 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2296 while (str.length % 4 !== 0) {
2297 str = str + '='
2298 }
2299 return str
2300 }
2301
2302 function toHex (n) {
2303 if (n < 16) return '0' + n.toString(16)
2304 return n.toString(16)
2305 }
2306
2307 function utf8ToBytes (string, units) {
2308 units = units || Infinity
2309 var codePoint
2310 var length = string.length
2311 var leadSurrogate = null
2312 var bytes = []
2313
2314 for (var i = 0; i < length; ++i) {
2315 codePoint = string.charCodeAt(i)
2316
2317 // is surrogate component
2318 if (codePoint > 0xD7FF && codePoint < 0xE000) {
2319 // last char was a lead
2320 if (!leadSurrogate) {
2321 // no lead yet
2322 if (codePoint > 0xDBFF) {
2323 // unexpected trail
2324 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2325 continue
2326 } else if (i + 1 === length) {
2327 // unpaired lead
2328 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2329 continue
2330 }
2331
2332 // valid lead
2333 leadSurrogate = codePoint
2334
2335 continue
2336 }
2337
2338 // 2 leads in a row
2339 if (codePoint < 0xDC00) {
2340 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2341 leadSurrogate = codePoint
2342 continue
2343 }
2344
2345 // valid surrogate pair
2346 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
2347 } else if (leadSurrogate) {
2348 // valid bmp char, but last char was a lead
2349 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
2350 }
2351
2352 leadSurrogate = null
2353
2354 // encode utf8
2355 if (codePoint < 0x80) {
2356 if ((units -= 1) < 0) break
2357 bytes.push(codePoint)
2358 } else if (codePoint < 0x800) {
2359 if ((units -= 2) < 0) break
2360 bytes.push(
2361 codePoint >> 0x6 | 0xC0,
2362 codePoint & 0x3F | 0x80
2363 )
2364 } else if (codePoint < 0x10000) {
2365 if ((units -= 3) < 0) break
2366 bytes.push(
2367 codePoint >> 0xC | 0xE0,
2368 codePoint >> 0x6 & 0x3F | 0x80,
2369 codePoint & 0x3F | 0x80
2370 )
2371 } else if (codePoint < 0x110000) {
2372 if ((units -= 4) < 0) break
2373 bytes.push(
2374 codePoint >> 0x12 | 0xF0,
2375 codePoint >> 0xC & 0x3F | 0x80,
2376 codePoint >> 0x6 & 0x3F | 0x80,
2377 codePoint & 0x3F | 0x80
2378 )
2379 } else {
2380 throw new Error('Invalid code point')
2381 }
2382 }
2383
2384 return bytes
2385 }
2386
2387 function asciiToBytes (str) {
2388 var byteArray = []
2389 for (var i = 0; i < str.length; ++i) {
2390 // Node's code seems to be doing this and not & 0x7F..
2391 byteArray.push(str.charCodeAt(i) & 0xFF)
2392 }
2393 return byteArray
2394 }
2395
2396 function utf16leToBytes (str, units) {
2397 var c, hi, lo
2398 var byteArray = []
2399 for (var i = 0; i < str.length; ++i) {
2400 if ((units -= 2) < 0) break
2401
2402 c = str.charCodeAt(i)
2403 hi = c >> 8
2404 lo = c % 256
2405 byteArray.push(lo)
2406 byteArray.push(hi)
2407 }
2408
2409 return byteArray
2410 }
2411
2412 function base64ToBytes (str) {
2413 return base64.toByteArray(base64clean(str))
2414 }
2415
2416 function blitBuffer (src, dst, offset, length) {
2417 for (var i = 0; i < length; ++i) {
2418 if ((i + offset >= dst.length) || (i >= src.length)) break
2419 dst[i + offset] = src[i]
2420 }
2421 return i
2422 }
2423
2424 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2425 function isArrayBufferView (obj) {
2426 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2427 }
2428
2429 function numberIsNaN (obj) {
2430 return obj !== obj // eslint-disable-line no-self-compare
2431 }
2432
2433 },{"base64-js":2,"ieee754":8}],6:[function(require,module,exports){
2434 (function (Buffer){
2435 // Copyright Joyent, Inc. and other Node contributors.
2436 //
2437 // Permission is hereby granted, free of charge, to any person obtaining a
2438 // copy of this software and associated documentation files (the
2439 // "Software"), to deal in the Software without restriction, including
2440 // without limitation the rights to use, copy, modify, merge, publish,
2441 // distribute, sublicense, and/or sell copies of the Software, and to permit
2442 // persons to whom the Software is furnished to do so, subject to the
2443 // following conditions:
2444 //
2445 // The above copyright notice and this permission notice shall be included
2446 // in all copies or substantial portions of the Software.
2447 //
2448 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2449 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2450 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2451 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2452 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2453 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2454 // USE OR OTHER DEALINGS IN THE SOFTWARE.
2455
2456 // NOTE: These type checking functions intentionally don't use `instanceof`
2457 // because it is fragile and can be easily faked with `Object.create()`.
2458
2459 function isArray(arg) {
2460 if (Array.isArray) {
2461 return Array.isArray(arg);
2462 }
2463 return objectToString(arg) === '[object Array]';
2464 }
2465 exports.isArray = isArray;
2466
2467 function isBoolean(arg) {
2468 return typeof arg === 'boolean';
2469 }
2470 exports.isBoolean = isBoolean;
2471
2472 function isNull(arg) {
2473 return arg === null;
2474 }
2475 exports.isNull = isNull;
2476
2477 function isNullOrUndefined(arg) {
2478 return arg == null;
2479 }
2480 exports.isNullOrUndefined = isNullOrUndefined;
2481
2482 function isNumber(arg) {
2483 return typeof arg === 'number';
2484 }
2485 exports.isNumber = isNumber;
2486
2487 function isString(arg) {
2488 return typeof arg === 'string';
2489 }
2490 exports.isString = isString;
2491
2492 function isSymbol(arg) {
2493 return typeof arg === 'symbol';
2494 }
2495 exports.isSymbol = isSymbol;
2496
2497 function isUndefined(arg) {
2498 return arg === void 0;
2499 }
2500 exports.isUndefined = isUndefined;
2501
2502 function isRegExp(re) {
2503 return objectToString(re) === '[object RegExp]';
2504 }
2505 exports.isRegExp = isRegExp;
2506
2507 function isObject(arg) {
2508 return typeof arg === 'object' && arg !== null;
2509 }
2510 exports.isObject = isObject;
2511
2512 function isDate(d) {
2513 return objectToString(d) === '[object Date]';
2514 }
2515 exports.isDate = isDate;
2516
2517 function isError(e) {
2518 return (objectToString(e) === '[object Error]' || e instanceof Error);
2519 }
2520 exports.isError = isError;
2521
2522 function isFunction(arg) {
2523 return typeof arg === 'function';
2524 }
2525 exports.isFunction = isFunction;
2526
2527 function isPrimitive(arg) {
2528 return arg === null ||
2529 typeof arg === 'boolean' ||
2530 typeof arg === 'number' ||
2531 typeof arg === 'string' ||
2532 typeof arg === 'symbol' || // ES6 symbol
2533 typeof arg === 'undefined';
2534 }
2535 exports.isPrimitive = isPrimitive;
2536
2537 exports.isBuffer = Buffer.isBuffer;
2538
2539 function objectToString(o) {
2540 return Object.prototype.toString.call(o);
2541 }
2542
2543 }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
2544 },{"../../is-buffer/index.js":10}],7:[function(require,module,exports){
2545 // Copyright Joyent, Inc. and other Node contributors.
2546 //
2547 // Permission is hereby granted, free of charge, to any person obtaining a
2548 // copy of this software and associated documentation files (the
2549 // "Software"), to deal in the Software without restriction, including
2550 // without limitation the rights to use, copy, modify, merge, publish,
2551 // distribute, sublicense, and/or sell copies of the Software, and to permit
2552 // persons to whom the Software is furnished to do so, subject to the
2553 // following conditions:
2554 //
2555 // The above copyright notice and this permission notice shall be included
2556 // in all copies or substantial portions of the Software.
2557 //
2558 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
2559 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2560 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
2561 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2562 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2563 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
2564 // USE OR OTHER DEALINGS IN THE SOFTWARE.
2565
2566 function EventEmitter() {
2567 this._events = this._events || {};
2568 this._maxListeners = this._maxListeners || undefined;
2569 }
2570 module.exports = EventEmitter;
2571
2572 // Backwards-compat with node 0.10.x
2573 EventEmitter.EventEmitter = EventEmitter;
2574
2575 EventEmitter.prototype._events = undefined;
2576 EventEmitter.prototype._maxListeners = undefined;
2577
2578 // By default EventEmitters will print a warning if more than 10 listeners are
2579 // added to it. This is a useful default which helps finding memory leaks.
2580 EventEmitter.defaultMaxListeners = 10;
2581
2582 // Obviously not all Emitters should be limited to 10. This function allows
2583 // that to be increased. Set to zero for unlimited.
2584 EventEmitter.prototype.setMaxListeners = function(n) {
2585 if (!isNumber(n) || n < 0 || isNaN(n))
2586 throw TypeError('n must be a positive number');
2587 this._maxListeners = n;
2588 return this;
2589 };
2590
2591 EventEmitter.prototype.emit = function(type) {
2592 var er, handler, len, args, i, listeners;
2593
2594 if (!this._events)
2595 this._events = {};
2596
2597 // If there is no 'error' event listener then throw.
2598 if (type === 'error') {
2599 if (!this._events.error ||
2600 (isObject(this._events.error) && !this._events.error.length)) {
2601 er = arguments[1];
2602 if (er instanceof Error) {
2603 throw er; // Unhandled 'error' event
2604 } else {
2605 // At least give some kind of context to the user
2606 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
2607 err.context = er;
2608 throw err;
2609 }
2610 }
2611 }
2612
2613 handler = this._events[type];
2614
2615 if (isUndefined(handler))
2616 return false;
2617
2618 if (isFunction(handler)) {
2619 switch (arguments.length) {
2620 // fast cases
2621 case 1:
2622 handler.call(this);
2623 break;
2624 case 2:
2625 handler.call(this, arguments[1]);
2626 break;
2627 case 3:
2628 handler.call(this, arguments[1], arguments[2]);
2629 break;
2630 // slower
2631 default:
2632 args = Array.prototype.slice.call(arguments, 1);
2633 handler.apply(this, args);
2634 }
2635 } else if (isObject(handler)) {
2636 args = Array.prototype.slice.call(arguments, 1);
2637 listeners = handler.slice();
2638 len = listeners.length;
2639 for (i = 0; i < len; i++)
2640 listeners[i].apply(this, args);
2641 }
2642
2643 return true;
2644 };
2645
2646 EventEmitter.prototype.addListener = function(type, listener) {
2647 var m;
2648
2649 if (!isFunction(listener))
2650 throw TypeError('listener must be a function');
2651
2652 if (!this._events)
2653 this._events = {};
2654
2655 // To avoid recursion in the case that type === "newListener"! Before
2656 // adding it to the listeners, first emit "newListener".
2657 if (this._events.newListener)
2658 this.emit('newListener', type,
2659 isFunction(listener.listener) ?
2660 listener.listener : listener);
2661
2662 if (!this._events[type])
2663 // Optimize the case of one listener. Don't need the extra array object.
2664 this._events[type] = listener;
2665 else if (isObject(this._events[type]))
2666 // If we've already got an array, just append.
2667 this._events[type].push(listener);
2668 else
2669 // Adding the second element, need to change to array.
2670 this._events[type] = [this._events[type], listener];
2671
2672 // Check for listener leak
2673 if (isObject(this._events[type]) && !this._events[type].warned) {
2674 if (!isUndefined(this._maxListeners)) {
2675 m = this._maxListeners;
2676 } else {
2677 m = EventEmitter.defaultMaxListeners;
2678 }
2679
2680 if (m && m > 0 && this._events[type].length > m) {
2681 this._events[type].warned = true;
2682 console.error('(node) warning: possible EventEmitter memory ' +
2683 'leak detected. %d listeners added. ' +
2684 'Use emitter.setMaxListeners() to increase limit.',
2685 this._events[type].length);
2686 if (typeof console.trace === 'function') {
2687 // not supported in IE 10
2688 console.trace();
2689 }
2690 }
2691 }
2692
2693 return this;
2694 };
2695
2696 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2697
2698 EventEmitter.prototype.once = function(type, listener) {
2699 if (!isFunction(listener))
2700 throw TypeError('listener must be a function');
2701
2702 var fired = false;
2703
2704 function g() {
2705 this.removeListener(type, g);
2706
2707 if (!fired) {
2708 fired = true;
2709 listener.apply(this, arguments);
2710 }
2711 }
2712
2713 g.listener = listener;
2714 this.on(type, g);
2715
2716 return this;
2717 };
2718
2719 // emits a 'removeListener' event iff the listener was removed
2720 EventEmitter.prototype.removeListener = function(type, listener) {
2721 var list, position, length, i;
2722
2723 if (!isFunction(listener))
2724 throw TypeError('listener must be a function');
2725
2726 if (!this._events || !this._events[type])
2727 return this;
2728
2729 list = this._events[type];
2730 length = list.length;
2731 position = -1;
2732
2733 if (list === listener ||
2734 (isFunction(list.listener) && list.listener === listener)) {
2735 delete this._events[type];
2736 if (this._events.removeListener)
2737 this.emit('removeListener', type, listener);
2738
2739 } else if (isObject(list)) {
2740 for (i = length; i-- > 0;) {
2741 if (list[i] === listener ||
2742 (list[i].listener && list[i].listener === listener)) {
2743 position = i;
2744 break;
2745 }
2746 }
2747
2748 if (position < 0)
2749 return this;
2750
2751 if (list.length === 1) {
2752 list.length = 0;
2753 delete this._events[type];
2754 } else {
2755 list.splice(position, 1);
2756 }
2757
2758 if (this._events.removeListener)
2759 this.emit('removeListener', type, listener);
2760 }
2761
2762 return this;
2763 };
2764
2765 EventEmitter.prototype.removeAllListeners = function(type) {
2766 var key, listeners;
2767
2768 if (!this._events)
2769 return this;
2770
2771 // not listening for removeListener, no need to emit
2772 if (!this._events.removeListener) {
2773 if (arguments.length === 0)
2774 this._events = {};
2775 else if (this._events[type])
2776 delete this._events[type];
2777 return this;
2778 }
2779
2780 // emit removeListener for all listeners on all events
2781 if (arguments.length === 0) {
2782 for (key in this._events) {
2783 if (key === 'removeListener') continue;
2784 this.removeAllListeners(key);
2785 }
2786 this.removeAllListeners('removeListener');
2787 this._events = {};
2788 return this;
2789 }
2790
2791 listeners = this._events[type];
2792
2793 if (isFunction(listeners)) {
2794 this.removeListener(type, listeners);
2795 } else if (listeners) {
2796 // LIFO order
2797 while (listeners.length)
2798 this.removeListener(type, listeners[listeners.length - 1]);
2799 }
2800 delete this._events[type];
2801
2802 return this;
2803 };
2804
2805 EventEmitter.prototype.listeners = function(type) {
2806 var ret;
2807 if (!this._events || !this._events[type])
2808 ret = [];
2809 else if (isFunction(this._events[type]))
2810 ret = [this._events[type]];
2811 else
2812 ret = this._events[type].slice();
2813 return ret;
2814 };
2815
2816 EventEmitter.prototype.listenerCount = function(type) {
2817 if (this._events) {
2818 var evlistener = this._events[type];
2819
2820 if (isFunction(evlistener))
2821 return 1;
2822 else if (evlistener)
2823 return evlistener.length;
2824 }
2825 return 0;
2826 };
2827
2828 EventEmitter.listenerCount = function(emitter, type) {
2829 return emitter.listenerCount(type);
2830 };
2831
2832 function isFunction(arg) {
2833 return typeof arg === 'function';
2834 }
2835
2836 function isNumber(arg) {
2837 return typeof arg === 'number';
2838 }
2839
2840 function isObject(arg) {
2841 return typeof arg === 'object' && arg !== null;
2842 }
2843
2844 function isUndefined(arg) {
2845 return arg === void 0;
2846 }
2847
2848 },{}],8:[function(require,module,exports){
2849 exports.read = function (buffer, offset, isLE, mLen, nBytes) {
2850 var e, m
2851 var eLen = nBytes * 8 - mLen - 1
2852 var eMax = (1 << eLen) - 1
2853 var eBias = eMax >> 1
2854 var nBits = -7
2855 var i = isLE ? (nBytes - 1) : 0
2856 var d = isLE ? -1 : 1
2857 var s = buffer[offset + i]
2858
2859 i += d
2860
2861 e = s & ((1 << (-nBits)) - 1)
2862 s >>= (-nBits)
2863 nBits += eLen
2864 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2865
2866 m = e & ((1 << (-nBits)) - 1)
2867 e >>= (-nBits)
2868 nBits += mLen
2869 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2870
2871 if (e === 0) {
2872 e = 1 - eBias
2873 } else if (e === eMax) {
2874 return m ? NaN : ((s ? -1 : 1) * Infinity)
2875 } else {
2876 m = m + Math.pow(2, mLen)
2877 e = e - eBias
2878 }
2879 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
2880 }
2881
2882 exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
2883 var e, m, c
2884 var eLen = nBytes * 8 - mLen - 1
2885 var eMax = (1 << eLen) - 1
2886 var eBias = eMax >> 1
2887 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
2888 var i = isLE ? 0 : (nBytes - 1)
2889 var d = isLE ? 1 : -1
2890 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
2891
2892 value = Math.abs(value)
2893
2894 if (isNaN(value) || value === Infinity) {
2895 m = isNaN(value) ? 1 : 0
2896 e = eMax
2897 } else {
2898 e = Math.floor(Math.log(value) / Math.LN2)
2899 if (value * (c = Math.pow(2, -e)) < 1) {
2900 e--
2901 c *= 2
2902 }
2903 if (e + eBias >= 1) {
2904 value += rt / c
2905 } else {
2906 value += rt * Math.pow(2, 1 - eBias)
2907 }
2908 if (value * c >= 2) {
2909 e++
2910 c /= 2
2911 }
2912
2913 if (e + eBias >= eMax) {
2914 m = 0
2915 e = eMax
2916 } else if (e + eBias >= 1) {
2917 m = (value * c - 1) * Math.pow(2, mLen)
2918 e = e + eBias
2919 } else {
2920 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
2921 e = 0
2922 }
2923 }
2924
2925 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2926
2927 e = (e << mLen) | m
2928 eLen += mLen
2929 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2930
2931 buffer[offset + i - d] |= s * 128
2932 }
2933
2934 },{}],9:[function(require,module,exports){
2935 if (typeof Object.create === 'function') {
2936 // implementation from standard node.js 'util' module
2937 module.exports = function inherits(ctor, superCtor) {
2938 ctor.super_ = superCtor
2939 ctor.prototype = Object.create(superCtor.prototype, {
2940 constructor: {
2941 value: ctor,
2942 enumerable: false,
2943 writable: true,
2944 configurable: true
2945 }
2946 });
2947 };
2948 } else {
2949 // old school shim for old browsers
2950 module.exports = function inherits(ctor, superCtor) {
2951 ctor.super_ = superCtor
2952 var TempCtor = function () {}
2953 TempCtor.prototype = superCtor.prototype
2954 ctor.prototype = new TempCtor()
2955 ctor.prototype.constructor = ctor
2956 }
2957 }
2958
2959 },{}],10:[function(require,module,exports){
2960 /*!
2961 * Determine if an object is a Buffer
2962 *
2963 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2964 * @license MIT
2965 */
2966
2967 // The _isBuffer check is for Safari 5-7 support, because it's missing
2968 // Object.prototype.constructor. Remove this eventually
2969 module.exports = function (obj) {
2970 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
2971 }
2972
2973 function isBuffer (obj) {
2974 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
2975 }
2976
2977 // For Node v0.10 support. Remove this eventually.
2978 function isSlowBuffer (obj) {
2979 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
2980 }
2981
2982 },{}],11:[function(require,module,exports){
2983 var toString = {}.toString;
2984
2985 module.exports = Array.isArray || function (arr) {
2986 return toString.call(arr) == '[object Array]';
2987 };
2988
2989 },{}],12:[function(require,module,exports){
2990 (function (process){
2991 'use strict';
2992
2993 if (!process.version ||
2994 process.version.indexOf('v0.') === 0 ||
2995 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
2996 module.exports = nextTick;
2997 } else {
2998 module.exports = process.nextTick;
2999 }
3000
3001 function nextTick(fn, arg1, arg2, arg3) {
3002 if (typeof fn !== 'function') {
3003 throw new TypeError('"callback" argument must be a function');
3004 }
3005 var len = arguments.length;
3006 var args, i;
3007 switch (len) {
3008 case 0:
3009 case 1:
3010 return process.nextTick(fn);
3011 case 2:
3012 return process.nextTick(function afterTickOne() {
3013 fn.call(null, arg1);
3014 });
3015 case 3:
3016 return process.nextTick(function afterTickTwo() {
3017 fn.call(null, arg1, arg2);
3018 });
3019 case 4:
3020 return process.nextTick(function afterTickThree() {
3021 fn.call(null, arg1, arg2, arg3);
3022 });
3023 default:
3024 args = new Array(len - 1);
3025 i = 0;
3026 while (i < args.length) {
3027 args[i++] = arguments[i];
3028 }
3029 return process.nextTick(function afterTick() {
3030 fn.apply(null, args);
3031 });
3032 }
3033 }
3034
3035 }).call(this,require('_process'))
3036 },{"_process":13}],13:[function(require,module,exports){
3037 // shim for using process in browser
3038 var process = module.exports = {};
3039
3040 // cached from whatever global is present so that test runners that stub it
3041 // don't break things. But we need to wrap it in a try catch in case it is
3042 // wrapped in strict mode code which doesn't define any globals. It's inside a
3043 // function because try/catches deoptimize in certain engines.
3044
3045 var cachedSetTimeout;
3046 var cachedClearTimeout;
3047
3048 function defaultSetTimout() {
3049 throw new Error('setTimeout has not been defined');
3050 }
3051 function defaultClearTimeout () {
3052 throw new Error('clearTimeout has not been defined');
3053 }
3054 (function () {
3055 try {
3056 if (typeof setTimeout === 'function') {
3057 cachedSetTimeout = setTimeout;
3058 } else {
3059 cachedSetTimeout = defaultSetTimout;
3060 }
3061 } catch (e) {
3062 cachedSetTimeout = defaultSetTimout;
3063 }
3064 try {
3065 if (typeof clearTimeout === 'function') {
3066 cachedClearTimeout = clearTimeout;
3067 } else {
3068 cachedClearTimeout = defaultClearTimeout;
3069 }
3070 } catch (e) {
3071 cachedClearTimeout = defaultClearTimeout;
3072 }
3073 } ())
3074 function runTimeout(fun) {
3075 if (cachedSetTimeout === setTimeout) {
3076 //normal enviroments in sane situations
3077 return setTimeout(fun, 0);
3078 }
3079 // if setTimeout wasn't available but was latter defined
3080 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
3081 cachedSetTimeout = setTimeout;
3082 return setTimeout(fun, 0);
3083 }
3084 try {
3085 // when when somebody has screwed with setTimeout but no I.E. maddness
3086 return cachedSetTimeout(fun, 0);
3087 } catch(e){
3088 try {
3089 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3090 return cachedSetTimeout.call(null, fun, 0);
3091 } catch(e){
3092 // 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
3093 return cachedSetTimeout.call(this, fun, 0);
3094 }
3095 }
3096
3097
3098 }
3099 function runClearTimeout(marker) {
3100 if (cachedClearTimeout === clearTimeout) {
3101 //normal enviroments in sane situations
3102 return clearTimeout(marker);
3103 }
3104 // if clearTimeout wasn't available but was latter defined
3105 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
3106 cachedClearTimeout = clearTimeout;
3107 return clearTimeout(marker);
3108 }
3109 try {
3110 // when when somebody has screwed with setTimeout but no I.E. maddness
3111 return cachedClearTimeout(marker);
3112 } catch (e){
3113 try {
3114 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3115 return cachedClearTimeout.call(null, marker);
3116 } catch (e){
3117 // 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.
3118 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
3119 return cachedClearTimeout.call(this, marker);
3120 }
3121 }
3122
3123
3124
3125 }
3126 var queue = [];
3127 var draining = false;
3128 var currentQueue;
3129 var queueIndex = -1;
3130
3131 function cleanUpNextTick() {
3132 if (!draining || !currentQueue) {
3133 return;
3134 }
3135 draining = false;
3136 if (currentQueue.length) {
3137 queue = currentQueue.concat(queue);
3138 } else {
3139 queueIndex = -1;
3140 }
3141 if (queue.length) {
3142 drainQueue();
3143 }
3144 }
3145
3146 function drainQueue() {
3147 if (draining) {
3148 return;
3149 }
3150 var timeout = runTimeout(cleanUpNextTick);
3151 draining = true;
3152
3153 var len = queue.length;
3154 while(len) {
3155 currentQueue = queue;
3156 queue = [];
3157 while (++queueIndex < len) {
3158 if (currentQueue) {
3159 currentQueue[queueIndex].run();
3160 }
3161 }
3162 queueIndex = -1;
3163 len = queue.length;
3164 }
3165 currentQueue = null;
3166 draining = false;
3167 runClearTimeout(timeout);
3168 }
3169
3170 process.nextTick = function (fun) {
3171 var args = new Array(arguments.length - 1);
3172 if (arguments.length > 1) {
3173 for (var i = 1; i < arguments.length; i++) {
3174 args[i - 1] = arguments[i];
3175 }
3176 }
3177 queue.push(new Item(fun, args));
3178 if (queue.length === 1 && !draining) {
3179 runTimeout(drainQueue);
3180 }
3181 };
3182
3183 // v8 likes predictible objects
3184 function Item(fun, array) {
3185 this.fun = fun;
3186 this.array = array;
3187 }
3188 Item.prototype.run = function () {
3189 this.fun.apply(null, this.array);
3190 };
3191 process.title = 'browser';
3192 process.browser = true;
3193 process.env = {};
3194 process.argv = [];
3195 process.version = ''; // empty string to avoid regexp issues
3196 process.versions = {};
3197
3198 function noop() {}
3199
3200 process.on = noop;
3201 process.addListener = noop;
3202 process.once = noop;
3203 process.off = noop;
3204 process.removeListener = noop;
3205 process.removeAllListeners = noop;
3206 process.emit = noop;
3207 process.prependListener = noop;
3208 process.prependOnceListener = noop;
3209
3210 process.listeners = function (name) { return [] }
3211
3212 process.binding = function (name) {
3213 throw new Error('process.binding is not supported');
3214 };
3215
3216 process.cwd = function () { return '/' };
3217 process.chdir = function (dir) {
3218 throw new Error('process.chdir is not supported');
3219 };
3220 process.umask = function() { return 0; };
3221
3222 },{}],14:[function(require,module,exports){
3223 module.exports = require('./lib/_stream_duplex.js');
3224
3225 },{"./lib/_stream_duplex.js":15}],15:[function(require,module,exports){
3226 // a duplex stream is just a stream that is both readable and writable.
3227 // Since JS doesn't have multiple prototypal inheritance, this class
3228 // prototypally inherits from Readable, and then parasitically from
3229 // Writable.
3230
3231 'use strict';
3232
3233 /*<replacement>*/
3234
3235 var objectKeys = Object.keys || function (obj) {
3236 var keys = [];
3237 for (var key in obj) {
3238 keys.push(key);
3239 }return keys;
3240 };
3241 /*</replacement>*/
3242
3243 module.exports = Duplex;
3244
3245 /*<replacement>*/
3246 var processNextTick = require('process-nextick-args');
3247 /*</replacement>*/
3248
3249 /*<replacement>*/
3250 var util = require('core-util-is');
3251 util.inherits = require('inherits');
3252 /*</replacement>*/
3253
3254 var Readable = require('./_stream_readable');
3255 var Writable = require('./_stream_writable');
3256
3257 util.inherits(Duplex, Readable);
3258
3259 var keys = objectKeys(Writable.prototype);
3260 for (var v = 0; v < keys.length; v++) {
3261 var method = keys[v];
3262 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
3263 }
3264
3265 function Duplex(options) {
3266 if (!(this instanceof Duplex)) return new Duplex(options);
3267
3268 Readable.call(this, options);
3269 Writable.call(this, options);
3270
3271 if (options && options.readable === false) this.readable = false;
3272
3273 if (options && options.writable === false) this.writable = false;
3274
3275 this.allowHalfOpen = true;
3276 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
3277
3278 this.once('end', onend);
3279 }
3280
3281 // the no-half-open enforcer
3282 function onend() {
3283 // if we allow half-open state, or if the writable side ended,
3284 // then we're ok.
3285 if (this.allowHalfOpen || this._writableState.ended) return;
3286
3287 // no more data can be written.
3288 // But allow more writes to happen in this tick.
3289 processNextTick(onEndNT, this);
3290 }
3291
3292 function onEndNT(self) {
3293 self.end();
3294 }
3295
3296 function forEach(xs, f) {
3297 for (var i = 0, l = xs.length; i < l; i++) {
3298 f(xs[i], i);
3299 }
3300 }
3301 },{"./_stream_readable":17,"./_stream_writable":19,"core-util-is":6,"inherits":9,"process-nextick-args":12}],16:[function(require,module,exports){
3302 // a passthrough stream.
3303 // basically just the most minimal sort of Transform stream.
3304 // Every written chunk gets output as-is.
3305
3306 'use strict';
3307
3308 module.exports = PassThrough;
3309
3310 var Transform = require('./_stream_transform');
3311
3312 /*<replacement>*/
3313 var util = require('core-util-is');
3314 util.inherits = require('inherits');
3315 /*</replacement>*/
3316
3317 util.inherits(PassThrough, Transform);
3318
3319 function PassThrough(options) {
3320 if (!(this instanceof PassThrough)) return new PassThrough(options);
3321
3322 Transform.call(this, options);
3323 }
3324
3325 PassThrough.prototype._transform = function (chunk, encoding, cb) {
3326 cb(null, chunk);
3327 };
3328 },{"./_stream_transform":18,"core-util-is":6,"inherits":9}],17:[function(require,module,exports){
3329 (function (process){
3330 'use strict';
3331
3332 module.exports = Readable;
3333
3334 /*<replacement>*/
3335 var processNextTick = require('process-nextick-args');
3336 /*</replacement>*/
3337
3338 /*<replacement>*/
3339 var isArray = require('isarray');
3340 /*</replacement>*/
3341
3342 /*<replacement>*/
3343 var Duplex;
3344 /*</replacement>*/
3345
3346 Readable.ReadableState = ReadableState;
3347
3348 /*<replacement>*/
3349 var EE = require('events').EventEmitter;
3350
3351 var EElistenerCount = function (emitter, type) {
3352 return emitter.listeners(type).length;
3353 };
3354 /*</replacement>*/
3355
3356 /*<replacement>*/
3357 var Stream = require('./internal/streams/stream');
3358 /*</replacement>*/
3359
3360 var Buffer = require('buffer').Buffer;
3361 /*<replacement>*/
3362 var bufferShim = require('buffer-shims');
3363 /*</replacement>*/
3364
3365 /*<replacement>*/
3366 var util = require('core-util-is');
3367 util.inherits = require('inherits');
3368 /*</replacement>*/
3369
3370 /*<replacement>*/
3371 var debugUtil = require('util');
3372 var debug = void 0;
3373 if (debugUtil && debugUtil.debuglog) {
3374 debug = debugUtil.debuglog('stream');
3375 } else {
3376 debug = function () {};
3377 }
3378 /*</replacement>*/
3379
3380 var BufferList = require('./internal/streams/BufferList');
3381 var StringDecoder;
3382
3383 util.inherits(Readable, Stream);
3384
3385 var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
3386
3387 function prependListener(emitter, event, fn) {
3388 // Sadly this is not cacheable as some libraries bundle their own
3389 // event emitter implementation with them.
3390 if (typeof emitter.prependListener === 'function') {
3391 return emitter.prependListener(event, fn);
3392 } else {
3393 // This is a hack to make sure that our error handler is attached before any
3394 // userland ones. NEVER DO THIS. This is here only because this code needs
3395 // to continue to work with older versions of Node.js that do not include
3396 // the prependListener() method. The goal is to eventually remove this hack.
3397 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]];
3398 }
3399 }
3400
3401 function ReadableState(options, stream) {
3402 Duplex = Duplex || require('./_stream_duplex');
3403
3404 options = options || {};
3405
3406 // object stream flag. Used to make read(n) ignore n and to
3407 // make all the buffer merging and length checks go away
3408 this.objectMode = !!options.objectMode;
3409
3410 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
3411
3412 // the point at which it stops calling _read() to fill the buffer
3413 // Note: 0 is a valid value, means "don't call _read preemptively ever"
3414 var hwm = options.highWaterMark;
3415 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
3416 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
3417
3418 // cast to ints.
3419 this.highWaterMark = ~~this.highWaterMark;
3420
3421 // A linked list is used to store data chunks instead of an array because the
3422 // linked list can remove elements from the beginning faster than
3423 // array.shift()
3424 this.buffer = new BufferList();
3425 this.length = 0;
3426 this.pipes = null;
3427 this.pipesCount = 0;
3428 this.flowing = null;
3429 this.ended = false;
3430 this.endEmitted = false;
3431 this.reading = false;
3432
3433 // a flag to be able to tell if the onwrite cb is called immediately,
3434 // or on a later tick. We set this to true at first, because any
3435 // actions that shouldn't happen until "later" should generally also
3436 // not happen before the first write call.
3437 this.sync = true;
3438
3439 // whenever we return null, then we set a flag to say
3440 // that we're awaiting a 'readable' event emission.
3441 this.needReadable = false;
3442 this.emittedReadable = false;
3443 this.readableListening = false;
3444 this.resumeScheduled = false;
3445
3446 // Crypto is kind of old and crusty. Historically, its default string
3447 // encoding is 'binary' so we have to make this configurable.
3448 // Everything else in the universe uses 'utf8', though.
3449 this.defaultEncoding = options.defaultEncoding || 'utf8';
3450
3451 // when piping, we only care about 'readable' events that happen
3452 // after read()ing all the bytes and not getting any pushback.
3453 this.ranOut = false;
3454
3455 // the number of writers that are awaiting a drain event in .pipe()s
3456 this.awaitDrain = 0;
3457
3458 // if true, a maybeReadMore has been scheduled
3459 this.readingMore = false;
3460
3461 this.decoder = null;
3462 this.encoding = null;
3463 if (options.encoding) {
3464 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
3465 this.decoder = new StringDecoder(options.encoding);
3466 this.encoding = options.encoding;
3467 }
3468 }
3469
3470 function Readable(options) {
3471 Duplex = Duplex || require('./_stream_duplex');
3472
3473 if (!(this instanceof Readable)) return new Readable(options);
3474
3475 this._readableState = new ReadableState(options, this);
3476
3477 // legacy
3478 this.readable = true;
3479
3480 if (options && typeof options.read === 'function') this._read = options.read;
3481
3482 Stream.call(this);
3483 }
3484
3485 // Manually shove something into the read() buffer.
3486 // This returns true if the highWaterMark has not been hit yet,
3487 // similar to how Writable.write() returns true if you should
3488 // write() some more.
3489 Readable.prototype.push = function (chunk, encoding) {
3490 var state = this._readableState;
3491
3492 if (!state.objectMode && typeof chunk === 'string') {
3493 encoding = encoding || state.defaultEncoding;
3494 if (encoding !== state.encoding) {
3495 chunk = bufferShim.from(chunk, encoding);
3496 encoding = '';
3497 }
3498 }
3499
3500 return readableAddChunk(this, state, chunk, encoding, false);
3501 };
3502
3503 // Unshift should *always* be something directly out of read()
3504 Readable.prototype.unshift = function (chunk) {
3505 var state = this._readableState;
3506 return readableAddChunk(this, state, chunk, '', true);
3507 };
3508
3509 Readable.prototype.isPaused = function () {
3510 return this._readableState.flowing === false;
3511 };
3512
3513 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
3514 var er = chunkInvalid(state, chunk);
3515 if (er) {
3516 stream.emit('error', er);
3517 } else if (chunk === null) {
3518 state.reading = false;
3519 onEofChunk(stream, state);
3520 } else if (state.objectMode || chunk && chunk.length > 0) {
3521 if (state.ended && !addToFront) {
3522 var e = new Error('stream.push() after EOF');
3523 stream.emit('error', e);
3524 } else if (state.endEmitted && addToFront) {
3525 var _e = new Error('stream.unshift() after end event');
3526 stream.emit('error', _e);
3527 } else {
3528 var skipAdd;
3529 if (state.decoder && !addToFront && !encoding) {
3530 chunk = state.decoder.write(chunk);
3531 skipAdd = !state.objectMode && chunk.length === 0;
3532 }
3533
3534 if (!addToFront) state.reading = false;
3535
3536 // Don't add to the buffer if we've decoded to an empty string chunk and
3537 // we're not in object mode
3538 if (!skipAdd) {
3539 // if we want the data now, just emit it.
3540 if (state.flowing && state.length === 0 && !state.sync) {
3541 stream.emit('data', chunk);
3542 stream.read(0);
3543 } else {
3544 // update the buffer info.
3545 state.length += state.objectMode ? 1 : chunk.length;
3546 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
3547
3548 if (state.needReadable) emitReadable(stream);
3549 }
3550 }
3551
3552 maybeReadMore(stream, state);
3553 }
3554 } else if (!addToFront) {
3555 state.reading = false;
3556 }
3557
3558 return needMoreData(state);
3559 }
3560
3561 // if it's past the high water mark, we can push in some more.
3562 // Also, if we have no data yet, we can stand some
3563 // more bytes. This is to work around cases where hwm=0,
3564 // such as the repl. Also, if the push() triggered a
3565 // readable event, and the user called read(largeNumber) such that
3566 // needReadable was set, then we ought to push more, so that another
3567 // 'readable' event will be triggered.
3568 function needMoreData(state) {
3569 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
3570 }
3571
3572 // backwards compatibility.
3573 Readable.prototype.setEncoding = function (enc) {
3574 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
3575 this._readableState.decoder = new StringDecoder(enc);
3576 this._readableState.encoding = enc;
3577 return this;
3578 };
3579
3580 // Don't raise the hwm > 8MB
3581 var MAX_HWM = 0x800000;
3582 function computeNewHighWaterMark(n) {
3583 if (n >= MAX_HWM) {
3584 n = MAX_HWM;
3585 } else {
3586 // Get the next highest power of 2 to prevent increasing hwm excessively in
3587 // tiny amounts
3588 n--;
3589 n |= n >>> 1;
3590 n |= n >>> 2;
3591 n |= n >>> 4;
3592 n |= n >>> 8;
3593 n |= n >>> 16;
3594 n++;
3595 }
3596 return n;
3597 }
3598
3599 // This function is designed to be inlinable, so please take care when making
3600 // changes to the function body.
3601 function howMuchToRead(n, state) {
3602 if (n <= 0 || state.length === 0 && state.ended) return 0;
3603 if (state.objectMode) return 1;
3604 if (n !== n) {
3605 // Only flow one buffer at a time
3606 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
3607 }
3608 // If we're asking for more than the current hwm, then raise the hwm.
3609 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
3610 if (n <= state.length) return n;
3611 // Don't have enough
3612 if (!state.ended) {
3613 state.needReadable = true;
3614 return 0;
3615 }
3616 return state.length;
3617 }
3618
3619 // you can override either this method, or the async _read(n) below.
3620 Readable.prototype.read = function (n) {
3621 debug('read', n);
3622 n = parseInt(n, 10);
3623 var state = this._readableState;
3624 var nOrig = n;
3625
3626 if (n !== 0) state.emittedReadable = false;
3627
3628 // if we're doing read(0) to trigger a readable event, but we
3629 // already have a bunch of data in the buffer, then just trigger
3630 // the 'readable' event and move on.
3631 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
3632 debug('read: emitReadable', state.length, state.ended);
3633 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
3634 return null;
3635 }
3636
3637 n = howMuchToRead(n, state);
3638
3639 // if we've ended, and we're now clear, then finish it up.
3640 if (n === 0 && state.ended) {
3641 if (state.length === 0) endReadable(this);
3642 return null;
3643 }
3644
3645 // All the actual chunk generation logic needs to be
3646 // *below* the call to _read. The reason is that in certain
3647 // synthetic stream cases, such as passthrough streams, _read
3648 // may be a completely synchronous operation which may change
3649 // the state of the read buffer, providing enough data when
3650 // before there was *not* enough.
3651 //
3652 // So, the steps are:
3653 // 1. Figure out what the state of things will be after we do
3654 // a read from the buffer.
3655 //
3656 // 2. If that resulting state will trigger a _read, then call _read.
3657 // Note that this may be asynchronous, or synchronous. Yes, it is
3658 // deeply ugly to write APIs this way, but that still doesn't mean
3659 // that the Readable class should behave improperly, as streams are
3660 // designed to be sync/async agnostic.
3661 // Take note if the _read call is sync or async (ie, if the read call
3662 // has returned yet), so that we know whether or not it's safe to emit
3663 // 'readable' etc.
3664 //
3665 // 3. Actually pull the requested chunks out of the buffer and return.
3666
3667 // if we need a readable event, then we need to do some reading.
3668 var doRead = state.needReadable;
3669 debug('need readable', doRead);
3670
3671 // if we currently have less than the highWaterMark, then also read some
3672 if (state.length === 0 || state.length - n < state.highWaterMark) {
3673 doRead = true;
3674 debug('length less than watermark', doRead);
3675 }
3676
3677 // however, if we've ended, then there's no point, and if we're already
3678 // reading, then it's unnecessary.
3679 if (state.ended || state.reading) {
3680 doRead = false;
3681 debug('reading or ended', doRead);
3682 } else if (doRead) {
3683 debug('do read');
3684 state.reading = true;
3685 state.sync = true;
3686 // if the length is currently zero, then we *need* a readable event.
3687 if (state.length === 0) state.needReadable = true;
3688 // call internal read method
3689 this._read(state.highWaterMark);
3690 state.sync = false;
3691 // If _read pushed data synchronously, then `reading` will be false,
3692 // and we need to re-evaluate how much data we can return to the user.
3693 if (!state.reading) n = howMuchToRead(nOrig, state);
3694 }
3695
3696 var ret;
3697 if (n > 0) ret = fromList(n, state);else ret = null;
3698
3699 if (ret === null) {
3700 state.needReadable = true;
3701 n = 0;
3702 } else {
3703 state.length -= n;
3704 }
3705
3706 if (state.length === 0) {
3707 // If we have nothing in the buffer, then we want to know
3708 // as soon as we *do* get something into the buffer.
3709 if (!state.ended) state.needReadable = true;
3710
3711 // If we tried to read() past the EOF, then emit end on the next tick.
3712 if (nOrig !== n && state.ended) endReadable(this);
3713 }
3714
3715 if (ret !== null) this.emit('data', ret);
3716
3717 return ret;
3718 };
3719
3720 function chunkInvalid(state, chunk) {
3721 var er = null;
3722 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
3723 er = new TypeError('Invalid non-string/buffer chunk');
3724 }
3725 return er;
3726 }
3727
3728 function onEofChunk(stream, state) {
3729 if (state.ended) return;
3730 if (state.decoder) {
3731 var chunk = state.decoder.end();
3732 if (chunk && chunk.length) {
3733 state.buffer.push(chunk);
3734 state.length += state.objectMode ? 1 : chunk.length;
3735 }
3736 }
3737 state.ended = true;
3738
3739 // emit 'readable' now to make sure it gets picked up.
3740 emitReadable(stream);
3741 }
3742
3743 // Don't emit readable right away in sync mode, because this can trigger
3744 // another read() call => stack overflow. This way, it might trigger
3745 // a nextTick recursion warning, but that's not so bad.
3746 function emitReadable(stream) {
3747 var state = stream._readableState;
3748 state.needReadable = false;
3749 if (!state.emittedReadable) {
3750 debug('emitReadable', state.flowing);
3751 state.emittedReadable = true;
3752 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
3753 }
3754 }
3755
3756 function emitReadable_(stream) {
3757 debug('emit readable');
3758 stream.emit('readable');
3759 flow(stream);
3760 }
3761
3762 // at this point, the user has presumably seen the 'readable' event,
3763 // and called read() to consume some data. that may have triggered
3764 // in turn another _read(n) call, in which case reading = true if
3765 // it's in progress.
3766 // However, if we're not ended, or reading, and the length < hwm,
3767 // then go ahead and try to read some more preemptively.
3768 function maybeReadMore(stream, state) {
3769 if (!state.readingMore) {
3770 state.readingMore = true;
3771 processNextTick(maybeReadMore_, stream, state);
3772 }
3773 }
3774
3775 function maybeReadMore_(stream, state) {
3776 var len = state.length;
3777 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
3778 debug('maybeReadMore read 0');
3779 stream.read(0);
3780 if (len === state.length)
3781 // didn't get any data, stop spinning.
3782 break;else len = state.length;
3783 }
3784 state.readingMore = false;
3785 }
3786
3787 // abstract method. to be overridden in specific implementation classes.
3788 // call cb(er, data) where data is <= n in length.
3789 // for virtual (non-string, non-buffer) streams, "length" is somewhat
3790 // arbitrary, and perhaps not very meaningful.
3791 Readable.prototype._read = function (n) {
3792 this.emit('error', new Error('_read() is not implemented'));
3793 };
3794
3795 Readable.prototype.pipe = function (dest, pipeOpts) {
3796 var src = this;
3797 var state = this._readableState;
3798
3799 switch (state.pipesCount) {
3800 case 0:
3801 state.pipes = dest;
3802 break;
3803 case 1:
3804 state.pipes = [state.pipes, dest];
3805 break;
3806 default:
3807 state.pipes.push(dest);
3808 break;
3809 }
3810 state.pipesCount += 1;
3811 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
3812
3813 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
3814
3815 var endFn = doEnd ? onend : cleanup;
3816 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
3817
3818 dest.on('unpipe', onunpipe);
3819 function onunpipe(readable) {
3820 debug('onunpipe');
3821 if (readable === src) {
3822 cleanup();
3823 }
3824 }
3825
3826 function onend() {
3827 debug('onend');
3828 dest.end();
3829 }
3830
3831 // when the dest drains, it reduces the awaitDrain counter
3832 // on the source. This would be more elegant with a .once()
3833 // handler in flow(), but adding and removing repeatedly is
3834 // too slow.
3835 var ondrain = pipeOnDrain(src);
3836 dest.on('drain', ondrain);
3837
3838 var cleanedUp = false;
3839 function cleanup() {
3840 debug('cleanup');
3841 // cleanup event handlers once the pipe is broken
3842 dest.removeListener('close', onclose);
3843 dest.removeListener('finish', onfinish);
3844 dest.removeListener('drain', ondrain);
3845 dest.removeListener('error', onerror);
3846 dest.removeListener('unpipe', onunpipe);
3847 src.removeListener('end', onend);
3848 src.removeListener('end', cleanup);
3849 src.removeListener('data', ondata);
3850
3851 cleanedUp = true;
3852
3853 // if the reader is waiting for a drain event from this
3854 // specific writer, then it would cause it to never start
3855 // flowing again.
3856 // So, if this is awaiting a drain, then we just call it now.
3857 // If we don't know, then assume that we are waiting for one.
3858 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
3859 }
3860
3861 // If the user pushes more data while we're writing to dest then we'll end up
3862 // in ondata again. However, we only want to increase awaitDrain once because
3863 // dest will only emit one 'drain' event for the multiple writes.
3864 // => Introduce a guard on increasing awaitDrain.
3865 var increasedAwaitDrain = false;
3866 src.on('data', ondata);
3867 function ondata(chunk) {
3868 debug('ondata');
3869 increasedAwaitDrain = false;
3870 var ret = dest.write(chunk);
3871 if (false === ret && !increasedAwaitDrain) {
3872 // If the user unpiped during `dest.write()`, it is possible
3873 // to get stuck in a permanently paused state if that write
3874 // also returned false.
3875 // => Check whether `dest` is still a piping destination.
3876 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
3877 debug('false write response, pause', src._readableState.awaitDrain);
3878 src._readableState.awaitDrain++;
3879 increasedAwaitDrain = true;
3880 }
3881 src.pause();
3882 }
3883 }
3884
3885 // if the dest has an error, then stop piping into it.
3886 // however, don't suppress the throwing behavior for this.
3887 function onerror(er) {
3888 debug('onerror', er);
3889 unpipe();
3890 dest.removeListener('error', onerror);
3891 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
3892 }
3893
3894 // Make sure our error handler is attached before userland ones.
3895 prependListener(dest, 'error', onerror);
3896
3897 // Both close and finish should trigger unpipe, but only once.
3898 function onclose() {
3899 dest.removeListener('finish', onfinish);
3900 unpipe();
3901 }
3902 dest.once('close', onclose);
3903 function onfinish() {
3904 debug('onfinish');
3905 dest.removeListener('close', onclose);
3906 unpipe();
3907 }
3908 dest.once('finish', onfinish);
3909
3910 function unpipe() {
3911 debug('unpipe');
3912 src.unpipe(dest);
3913 }
3914
3915 // tell the dest that it's being piped to
3916 dest.emit('pipe', src);
3917
3918 // start the flow if it hasn't been started already.
3919 if (!state.flowing) {
3920 debug('pipe resume');
3921 src.resume();
3922 }
3923
3924 return dest;
3925 };
3926
3927 function pipeOnDrain(src) {
3928 return function () {
3929 var state = src._readableState;
3930 debug('pipeOnDrain', state.awaitDrain);
3931 if (state.awaitDrain) state.awaitDrain--;
3932 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
3933 state.flowing = true;
3934 flow(src);
3935 }
3936 };
3937 }
3938
3939 Readable.prototype.unpipe = function (dest) {
3940 var state = this._readableState;
3941
3942 // if we're not piping anywhere, then do nothing.
3943 if (state.pipesCount === 0) return this;
3944
3945 // just one destination. most common case.
3946 if (state.pipesCount === 1) {
3947 // passed in one, but it's not the right one.
3948 if (dest && dest !== state.pipes) return this;
3949
3950 if (!dest) dest = state.pipes;
3951
3952 // got a match.
3953 state.pipes = null;
3954 state.pipesCount = 0;
3955 state.flowing = false;
3956 if (dest) dest.emit('unpipe', this);
3957 return this;
3958 }
3959
3960 // slow case. multiple pipe destinations.
3961
3962 if (!dest) {
3963 // remove all.
3964 var dests = state.pipes;
3965 var len = state.pipesCount;
3966 state.pipes = null;
3967 state.pipesCount = 0;
3968 state.flowing = false;
3969
3970 for (var i = 0; i < len; i++) {
3971 dests[i].emit('unpipe', this);
3972 }return this;
3973 }
3974
3975 // try to find the right one.
3976 var index = indexOf(state.pipes, dest);
3977 if (index === -1) return this;
3978
3979 state.pipes.splice(index, 1);
3980 state.pipesCount -= 1;
3981 if (state.pipesCount === 1) state.pipes = state.pipes[0];
3982
3983 dest.emit('unpipe', this);
3984
3985 return this;
3986 };
3987
3988 // set up data events if they are asked for
3989 // Ensure readable listeners eventually get something
3990 Readable.prototype.on = function (ev, fn) {
3991 var res = Stream.prototype.on.call(this, ev, fn);
3992
3993 if (ev === 'data') {
3994 // Start flowing on next tick if stream isn't explicitly paused
3995 if (this._readableState.flowing !== false) this.resume();
3996 } else if (ev === 'readable') {
3997 var state = this._readableState;
3998 if (!state.endEmitted && !state.readableListening) {
3999 state.readableListening = state.needReadable = true;
4000 state.emittedReadable = false;
4001 if (!state.reading) {
4002 processNextTick(nReadingNextTick, this);
4003 } else if (state.length) {
4004 emitReadable(this, state);
4005 }
4006 }
4007 }
4008
4009 return res;
4010 };
4011 Readable.prototype.addListener = Readable.prototype.on;
4012
4013 function nReadingNextTick(self) {
4014 debug('readable nexttick read 0');
4015 self.read(0);
4016 }
4017
4018 // pause() and resume() are remnants of the legacy readable stream API
4019 // If the user uses them, then switch into old mode.
4020 Readable.prototype.resume = function () {
4021 var state = this._readableState;
4022 if (!state.flowing) {
4023 debug('resume');
4024 state.flowing = true;
4025 resume(this, state);
4026 }
4027 return this;
4028 };
4029
4030 function resume(stream, state) {
4031 if (!state.resumeScheduled) {
4032 state.resumeScheduled = true;
4033 processNextTick(resume_, stream, state);
4034 }
4035 }
4036
4037 function resume_(stream, state) {
4038 if (!state.reading) {
4039 debug('resume read 0');
4040 stream.read(0);
4041 }
4042
4043 state.resumeScheduled = false;
4044 state.awaitDrain = 0;
4045 stream.emit('resume');
4046 flow(stream);
4047 if (state.flowing && !state.reading) stream.read(0);
4048 }
4049
4050 Readable.prototype.pause = function () {
4051 debug('call pause flowing=%j', this._readableState.flowing);
4052 if (false !== this._readableState.flowing) {
4053 debug('pause');
4054 this._readableState.flowing = false;
4055 this.emit('pause');
4056 }
4057 return this;
4058 };
4059
4060 function flow(stream) {
4061 var state = stream._readableState;
4062 debug('flow', state.flowing);
4063 while (state.flowing && stream.read() !== null) {}
4064 }
4065
4066 // wrap an old-style stream as the async data source.
4067 // This is *not* part of the readable stream interface.
4068 // It is an ugly unfortunate mess of history.
4069 Readable.prototype.wrap = function (stream) {
4070 var state = this._readableState;
4071 var paused = false;
4072
4073 var self = this;
4074 stream.on('end', function () {
4075 debug('wrapped end');
4076 if (state.decoder && !state.ended) {
4077 var chunk = state.decoder.end();
4078 if (chunk && chunk.length) self.push(chunk);
4079 }
4080
4081 self.push(null);
4082 });
4083
4084 stream.on('data', function (chunk) {
4085 debug('wrapped data');
4086 if (state.decoder) chunk = state.decoder.write(chunk);
4087
4088 // don't skip over falsy values in objectMode
4089 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
4090
4091 var ret = self.push(chunk);
4092 if (!ret) {
4093 paused = true;
4094 stream.pause();
4095 }
4096 });
4097
4098 // proxy all the other methods.
4099 // important when wrapping filters and duplexes.
4100 for (var i in stream) {
4101 if (this[i] === undefined && typeof stream[i] === 'function') {
4102 this[i] = function (method) {
4103 return function () {
4104 return stream[method].apply(stream, arguments);
4105 };
4106 }(i);
4107 }
4108 }
4109
4110 // proxy certain important events.
4111 for (var n = 0; n < kProxyEvents.length; n++) {
4112 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
4113 }
4114
4115 // when we try to consume some more bytes, simply unpause the
4116 // underlying stream.
4117 self._read = function (n) {
4118 debug('wrapped _read', n);
4119 if (paused) {
4120 paused = false;
4121 stream.resume();
4122 }
4123 };
4124
4125 return self;
4126 };
4127
4128 // exposed for testing purposes only.
4129 Readable._fromList = fromList;
4130
4131 // Pluck off n bytes from an array of buffers.
4132 // Length is the combined lengths of all the buffers in the list.
4133 // This function is designed to be inlinable, so please take care when making
4134 // changes to the function body.
4135 function fromList(n, state) {
4136 // nothing buffered
4137 if (state.length === 0) return null;
4138
4139 var ret;
4140 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
4141 // read it all, truncate the list
4142 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);
4143 state.buffer.clear();
4144 } else {
4145 // read part of list
4146 ret = fromListPartial(n, state.buffer, state.decoder);
4147 }
4148
4149 return ret;
4150 }
4151
4152 // Extracts only enough buffered data to satisfy the amount requested.
4153 // This function is designed to be inlinable, so please take care when making
4154 // changes to the function body.
4155 function fromListPartial(n, list, hasStrings) {
4156 var ret;
4157 if (n < list.head.data.length) {
4158 // slice is the same for buffers and strings
4159 ret = list.head.data.slice(0, n);
4160 list.head.data = list.head.data.slice(n);
4161 } else if (n === list.head.data.length) {
4162 // first chunk is a perfect match
4163 ret = list.shift();
4164 } else {
4165 // result spans more than one buffer
4166 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
4167 }
4168 return ret;
4169 }
4170
4171 // Copies a specified amount of characters from the list of buffered data
4172 // chunks.
4173 // This function is designed to be inlinable, so please take care when making
4174 // changes to the function body.
4175 function copyFromBufferString(n, list) {
4176 var p = list.head;
4177 var c = 1;
4178 var ret = p.data;
4179 n -= ret.length;
4180 while (p = p.next) {
4181 var str = p.data;
4182 var nb = n > str.length ? str.length : n;
4183 if (nb === str.length) ret += str;else ret += str.slice(0, n);
4184 n -= nb;
4185 if (n === 0) {
4186 if (nb === str.length) {
4187 ++c;
4188 if (p.next) list.head = p.next;else list.head = list.tail = null;
4189 } else {
4190 list.head = p;
4191 p.data = str.slice(nb);
4192 }
4193 break;
4194 }
4195 ++c;
4196 }
4197 list.length -= c;
4198 return ret;
4199 }
4200
4201 // Copies a specified amount of bytes from the list of buffered data chunks.
4202 // This function is designed to be inlinable, so please take care when making
4203 // changes to the function body.
4204 function copyFromBuffer(n, list) {
4205 var ret = bufferShim.allocUnsafe(n);
4206 var p = list.head;
4207 var c = 1;
4208 p.data.copy(ret);
4209 n -= p.data.length;
4210 while (p = p.next) {
4211 var buf = p.data;
4212 var nb = n > buf.length ? buf.length : n;
4213 buf.copy(ret, ret.length - n, 0, nb);
4214 n -= nb;
4215 if (n === 0) {
4216 if (nb === buf.length) {
4217 ++c;
4218 if (p.next) list.head = p.next;else list.head = list.tail = null;
4219 } else {
4220 list.head = p;
4221 p.data = buf.slice(nb);
4222 }
4223 break;
4224 }
4225 ++c;
4226 }
4227 list.length -= c;
4228 return ret;
4229 }
4230
4231 function endReadable(stream) {
4232 var state = stream._readableState;
4233
4234 // If we get here before consuming all the bytes, then that is a
4235 // bug in node. Should never happen.
4236 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
4237
4238 if (!state.endEmitted) {
4239 state.ended = true;
4240 processNextTick(endReadableNT, state, stream);
4241 }
4242 }
4243
4244 function endReadableNT(state, stream) {
4245 // Check that we didn't get one last unshift.
4246 if (!state.endEmitted && state.length === 0) {
4247 state.endEmitted = true;
4248 stream.readable = false;
4249 stream.emit('end');
4250 }
4251 }
4252
4253 function forEach(xs, f) {
4254 for (var i = 0, l = xs.length; i < l; i++) {
4255 f(xs[i], i);
4256 }
4257 }
4258
4259 function indexOf(xs, x) {
4260 for (var i = 0, l = xs.length; i < l; i++) {
4261 if (xs[i] === x) return i;
4262 }
4263 return -1;
4264 }
4265 }).call(this,require('_process'))
4266 },{"./_stream_duplex":15,"./internal/streams/BufferList":20,"./internal/streams/stream":21,"_process":13,"buffer":5,"buffer-shims":4,"core-util-is":6,"events":7,"inherits":9,"isarray":11,"process-nextick-args":12,"string_decoder/":22,"util":3}],18:[function(require,module,exports){
4267 // a transform stream is a readable/writable stream where you do
4268 // something with the data. Sometimes it's called a "filter",
4269 // but that's not a great name for it, since that implies a thing where
4270 // some bits pass through, and others are simply ignored. (That would
4271 // be a valid example of a transform, of course.)
4272 //
4273 // While the output is causally related to the input, it's not a
4274 // necessarily symmetric or synchronous transformation. For example,
4275 // a zlib stream might take multiple plain-text writes(), and then
4276 // emit a single compressed chunk some time in the future.
4277 //
4278 // Here's how this works:
4279 //
4280 // The Transform stream has all the aspects of the readable and writable
4281 // stream classes. When you write(chunk), that calls _write(chunk,cb)
4282 // internally, and returns false if there's a lot of pending writes
4283 // buffered up. When you call read(), that calls _read(n) until
4284 // there's enough pending readable data buffered up.
4285 //
4286 // In a transform stream, the written data is placed in a buffer. When
4287 // _read(n) is called, it transforms the queued up data, calling the
4288 // buffered _write cb's as it consumes chunks. If consuming a single
4289 // written chunk would result in multiple output chunks, then the first
4290 // outputted bit calls the readcb, and subsequent chunks just go into
4291 // the read buffer, and will cause it to emit 'readable' if necessary.
4292 //
4293 // This way, back-pressure is actually determined by the reading side,
4294 // since _read has to be called to start processing a new chunk. However,
4295 // a pathological inflate type of transform can cause excessive buffering
4296 // here. For example, imagine a stream where every byte of input is
4297 // interpreted as an integer from 0-255, and then results in that many
4298 // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
4299 // 1kb of data being output. In this case, you could write a very small
4300 // amount of input, and end up with a very large amount of output. In
4301 // such a pathological inflating mechanism, there'd be no way to tell
4302 // the system to stop doing the transform. A single 4MB write could
4303 // cause the system to run out of memory.
4304 //
4305 // However, even in such a pathological case, only a single written chunk
4306 // would be consumed, and then the rest would wait (un-transformed) until
4307 // the results of the previous transformed chunk were consumed.
4308
4309 'use strict';
4310
4311 module.exports = Transform;
4312
4313 var Duplex = require('./_stream_duplex');
4314
4315 /*<replacement>*/
4316 var util = require('core-util-is');
4317 util.inherits = require('inherits');
4318 /*</replacement>*/
4319
4320 util.inherits(Transform, Duplex);
4321
4322 function TransformState(stream) {
4323 this.afterTransform = function (er, data) {
4324 return afterTransform(stream, er, data);
4325 };
4326
4327 this.needTransform = false;
4328 this.transforming = false;
4329 this.writecb = null;
4330 this.writechunk = null;
4331 this.writeencoding = null;
4332 }
4333
4334 function afterTransform(stream, er, data) {
4335 var ts = stream._transformState;
4336 ts.transforming = false;
4337
4338 var cb = ts.writecb;
4339
4340 if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
4341
4342 ts.writechunk = null;
4343 ts.writecb = null;
4344
4345 if (data !== null && data !== undefined) stream.push(data);
4346
4347 cb(er);
4348
4349 var rs = stream._readableState;
4350 rs.reading = false;
4351 if (rs.needReadable || rs.length < rs.highWaterMark) {
4352 stream._read(rs.highWaterMark);
4353 }
4354 }
4355
4356 function Transform(options) {
4357 if (!(this instanceof Transform)) return new Transform(options);
4358
4359 Duplex.call(this, options);
4360
4361 this._transformState = new TransformState(this);
4362
4363 var stream = this;
4364
4365 // start out asking for a readable event once data is transformed.
4366 this._readableState.needReadable = true;
4367
4368 // we have implemented the _read method, and done the other things
4369 // that Readable wants before the first _read call, so unset the
4370 // sync guard flag.
4371 this._readableState.sync = false;
4372
4373 if (options) {
4374 if (typeof options.transform === 'function') this._transform = options.transform;
4375
4376 if (typeof options.flush === 'function') this._flush = options.flush;
4377 }
4378
4379 // When the writable side finishes, then flush out anything remaining.
4380 this.once('prefinish', function () {
4381 if (typeof this._flush === 'function') this._flush(function (er, data) {
4382 done(stream, er, data);
4383 });else done(stream);
4384 });
4385 }
4386
4387 Transform.prototype.push = function (chunk, encoding) {
4388 this._transformState.needTransform = false;
4389 return Duplex.prototype.push.call(this, chunk, encoding);
4390 };
4391
4392 // This is the part where you do stuff!
4393 // override this function in implementation classes.
4394 // 'chunk' is an input chunk.
4395 //
4396 // Call `push(newChunk)` to pass along transformed output
4397 // to the readable side. You may call 'push' zero or more times.
4398 //
4399 // Call `cb(err)` when you are done with this chunk. If you pass
4400 // an error, then that'll put the hurt on the whole operation. If you
4401 // never call cb(), then you'll never get another chunk.
4402 Transform.prototype._transform = function (chunk, encoding, cb) {
4403 throw new Error('_transform() is not implemented');
4404 };
4405
4406 Transform.prototype._write = function (chunk, encoding, cb) {
4407 var ts = this._transformState;
4408 ts.writecb = cb;
4409 ts.writechunk = chunk;
4410 ts.writeencoding = encoding;
4411 if (!ts.transforming) {
4412 var rs = this._readableState;
4413 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
4414 }
4415 };
4416
4417 // Doesn't matter what the args are here.
4418 // _transform does all the work.
4419 // That we got here means that the readable side wants more data.
4420 Transform.prototype._read = function (n) {
4421 var ts = this._transformState;
4422
4423 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
4424 ts.transforming = true;
4425 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
4426 } else {
4427 // mark that we need a transform, so that any data that comes in
4428 // will get processed, now that we've asked for it.
4429 ts.needTransform = true;
4430 }
4431 };
4432
4433 function done(stream, er, data) {
4434 if (er) return stream.emit('error', er);
4435
4436 if (data !== null && data !== undefined) stream.push(data);
4437
4438 // if there's nothing in the write buffer, then that means
4439 // that nothing more will ever be provided
4440 var ws = stream._writableState;
4441 var ts = stream._transformState;
4442
4443 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
4444
4445 if (ts.transforming) throw new Error('Calling transform done when still transforming');
4446
4447 return stream.push(null);
4448 }
4449 },{"./_stream_duplex":15,"core-util-is":6,"inherits":9}],19:[function(require,module,exports){
4450 (function (process){
4451 // A bit simpler than readable streams.
4452 // Implement an async ._write(chunk, encoding, cb), and it'll handle all
4453 // the drain event emission and buffering.
4454
4455 'use strict';
4456
4457 module.exports = Writable;
4458
4459 /*<replacement>*/
4460 var processNextTick = require('process-nextick-args');
4461 /*</replacement>*/
4462
4463 /*<replacement>*/
4464 var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
4465 /*</replacement>*/
4466
4467 /*<replacement>*/
4468 var Duplex;
4469 /*</replacement>*/
4470
4471 Writable.WritableState = WritableState;
4472
4473 /*<replacement>*/
4474 var util = require('core-util-is');
4475 util.inherits = require('inherits');
4476 /*</replacement>*/
4477
4478 /*<replacement>*/
4479 var internalUtil = {
4480 deprecate: require('util-deprecate')
4481 };
4482 /*</replacement>*/
4483
4484 /*<replacement>*/
4485 var Stream = require('./internal/streams/stream');
4486 /*</replacement>*/
4487
4488 var Buffer = require('buffer').Buffer;
4489 /*<replacement>*/
4490 var bufferShim = require('buffer-shims');
4491 /*</replacement>*/
4492
4493 util.inherits(Writable, Stream);
4494
4495 function nop() {}
4496
4497 function WriteReq(chunk, encoding, cb) {
4498 this.chunk = chunk;
4499 this.encoding = encoding;
4500 this.callback = cb;
4501 this.next = null;
4502 }
4503
4504 function WritableState(options, stream) {
4505 Duplex = Duplex || require('./_stream_duplex');
4506
4507 options = options || {};
4508
4509 // object stream flag to indicate whether or not this stream
4510 // contains buffers or objects.
4511 this.objectMode = !!options.objectMode;
4512
4513 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
4514
4515 // the point at which write() starts returning false
4516 // Note: 0 is a valid value, means that we always return false if
4517 // the entire buffer is not flushed immediately on write()
4518 var hwm = options.highWaterMark;
4519 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
4520 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
4521
4522 // cast to ints.
4523 this.highWaterMark = ~~this.highWaterMark;
4524
4525 // drain event flag.
4526 this.needDrain = false;
4527 // at the start of calling end()
4528 this.ending = false;
4529 // when end() has been called, and returned
4530 this.ended = false;
4531 // when 'finish' is emitted
4532 this.finished = false;
4533
4534 // should we decode strings into buffers before passing to _write?
4535 // this is here so that some node-core streams can optimize string
4536 // handling at a lower level.
4537 var noDecode = options.decodeStrings === false;
4538 this.decodeStrings = !noDecode;
4539
4540 // Crypto is kind of old and crusty. Historically, its default string
4541 // encoding is 'binary' so we have to make this configurable.
4542 // Everything else in the universe uses 'utf8', though.
4543 this.defaultEncoding = options.defaultEncoding || 'utf8';
4544
4545 // not an actual buffer we keep track of, but a measurement
4546 // of how much we're waiting to get pushed to some underlying
4547 // socket or file.
4548 this.length = 0;
4549
4550 // a flag to see when we're in the middle of a write.
4551 this.writing = false;
4552
4553 // when true all writes will be buffered until .uncork() call
4554 this.corked = 0;
4555
4556 // a flag to be able to tell if the onwrite cb is called immediately,
4557 // or on a later tick. We set this to true at first, because any
4558 // actions that shouldn't happen until "later" should generally also
4559 // not happen before the first write call.
4560 this.sync = true;
4561
4562 // a flag to know if we're processing previously buffered items, which
4563 // may call the _write() callback in the same tick, so that we don't
4564 // end up in an overlapped onwrite situation.
4565 this.bufferProcessing = false;
4566
4567 // the callback that's passed to _write(chunk,cb)
4568 this.onwrite = function (er) {
4569 onwrite(stream, er);
4570 };
4571
4572 // the callback that the user supplies to write(chunk,encoding,cb)
4573 this.writecb = null;
4574
4575 // the amount that is being written when _write is called.
4576 this.writelen = 0;
4577
4578 this.bufferedRequest = null;
4579 this.lastBufferedRequest = null;
4580
4581 // number of pending user-supplied write callbacks
4582 // this must be 0 before 'finish' can be emitted
4583 this.pendingcb = 0;
4584
4585 // emit prefinish if the only thing we're waiting for is _write cbs
4586 // This is relevant for synchronous Transform streams
4587 this.prefinished = false;
4588
4589 // True if the error was already emitted and should not be thrown again
4590 this.errorEmitted = false;
4591
4592 // count buffered requests
4593 this.bufferedRequestCount = 0;
4594
4595 // allocate the first CorkedRequest, there is always
4596 // one allocated and free to use, and we maintain at most two
4597 this.corkedRequestsFree = new CorkedRequest(this);
4598 }
4599
4600 WritableState.prototype.getBuffer = function getBuffer() {
4601 var current = this.bufferedRequest;
4602 var out = [];
4603 while (current) {
4604 out.push(current);
4605 current = current.next;
4606 }
4607 return out;
4608 };
4609
4610 (function () {
4611 try {
4612 Object.defineProperty(WritableState.prototype, 'buffer', {
4613 get: internalUtil.deprecate(function () {
4614 return this.getBuffer();
4615 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
4616 });
4617 } catch (_) {}
4618 })();
4619
4620 // Test _writableState for inheritance to account for Duplex streams,
4621 // whose prototype chain only points to Readable.
4622 var realHasInstance;
4623 if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
4624 realHasInstance = Function.prototype[Symbol.hasInstance];
4625 Object.defineProperty(Writable, Symbol.hasInstance, {
4626 value: function (object) {
4627 if (realHasInstance.call(this, object)) return true;
4628
4629 return object && object._writableState instanceof WritableState;
4630 }
4631 });
4632 } else {
4633 realHasInstance = function (object) {
4634 return object instanceof this;
4635 };
4636 }
4637
4638 function Writable(options) {
4639 Duplex = Duplex || require('./_stream_duplex');
4640
4641 // Writable ctor is applied to Duplexes, too.
4642 // `realHasInstance` is necessary because using plain `instanceof`
4643 // would return false, as no `_writableState` property is attached.
4644
4645 // Trying to use the custom `instanceof` for Writable here will also break the
4646 // Node.js LazyTransform implementation, which has a non-trivial getter for
4647 // `_writableState` that would lead to infinite recursion.
4648 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
4649 return new Writable(options);
4650 }
4651
4652 this._writableState = new WritableState(options, this);
4653
4654 // legacy.
4655 this.writable = true;
4656
4657 if (options) {
4658 if (typeof options.write === 'function') this._write = options.write;
4659
4660 if (typeof options.writev === 'function') this._writev = options.writev;
4661 }
4662
4663 Stream.call(this);
4664 }
4665
4666 // Otherwise people can pipe Writable streams, which is just wrong.
4667 Writable.prototype.pipe = function () {
4668 this.emit('error', new Error('Cannot pipe, not readable'));
4669 };
4670
4671 function writeAfterEnd(stream, cb) {
4672 var er = new Error('write after end');
4673 // TODO: defer error events consistently everywhere, not just the cb
4674 stream.emit('error', er);
4675 processNextTick(cb, er);
4676 }
4677
4678 // Checks that a user-supplied chunk is valid, especially for the particular
4679 // mode the stream is in. Currently this means that `null` is never accepted
4680 // and undefined/non-string values are only allowed in object mode.
4681 function validChunk(stream, state, chunk, cb) {
4682 var valid = true;
4683 var er = false;
4684
4685 if (chunk === null) {
4686 er = new TypeError('May not write null values to stream');
4687 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
4688 er = new TypeError('Invalid non-string/buffer chunk');
4689 }
4690 if (er) {
4691 stream.emit('error', er);
4692 processNextTick(cb, er);
4693 valid = false;
4694 }
4695 return valid;
4696 }
4697
4698 Writable.prototype.write = function (chunk, encoding, cb) {
4699 var state = this._writableState;
4700 var ret = false;
4701 var isBuf = Buffer.isBuffer(chunk);
4702
4703 if (typeof encoding === 'function') {
4704 cb = encoding;
4705 encoding = null;
4706 }
4707
4708 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
4709
4710 if (typeof cb !== 'function') cb = nop;
4711
4712 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
4713 state.pendingcb++;
4714 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
4715 }
4716
4717 return ret;
4718 };
4719
4720 Writable.prototype.cork = function () {
4721 var state = this._writableState;
4722
4723 state.corked++;
4724 };
4725
4726 Writable.prototype.uncork = function () {
4727 var state = this._writableState;
4728
4729 if (state.corked) {
4730 state.corked--;
4731
4732 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
4733 }
4734 };
4735
4736 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
4737 // node::ParseEncoding() requires lower case.
4738 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
4739 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);
4740 this._writableState.defaultEncoding = encoding;
4741 return this;
4742 };
4743
4744 function decodeChunk(state, chunk, encoding) {
4745 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
4746 chunk = bufferShim.from(chunk, encoding);
4747 }
4748 return chunk;
4749 }
4750
4751 // if we're already writing something, then just put this
4752 // in the queue, and wait our turn. Otherwise, call _write
4753 // If we return false, then we need a drain event, so set that flag.
4754 function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
4755 if (!isBuf) {
4756 chunk = decodeChunk(state, chunk, encoding);
4757 if (Buffer.isBuffer(chunk)) encoding = 'buffer';
4758 }
4759 var len = state.objectMode ? 1 : chunk.length;
4760
4761 state.length += len;
4762
4763 var ret = state.length < state.highWaterMark;
4764 // we must ensure that previous needDrain will not be reset to false.
4765 if (!ret) state.needDrain = true;
4766
4767 if (state.writing || state.corked) {
4768 var last = state.lastBufferedRequest;
4769 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
4770 if (last) {
4771 last.next = state.lastBufferedRequest;
4772 } else {
4773 state.bufferedRequest = state.lastBufferedRequest;
4774 }
4775 state.bufferedRequestCount += 1;
4776 } else {
4777 doWrite(stream, state, false, len, chunk, encoding, cb);
4778 }
4779
4780 return ret;
4781 }
4782
4783 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
4784 state.writelen = len;
4785 state.writecb = cb;
4786 state.writing = true;
4787 state.sync = true;
4788 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
4789 state.sync = false;
4790 }
4791
4792 function onwriteError(stream, state, sync, er, cb) {
4793 --state.pendingcb;
4794 if (sync) processNextTick(cb, er);else cb(er);
4795
4796 stream._writableState.errorEmitted = true;
4797 stream.emit('error', er);
4798 }
4799
4800 function onwriteStateUpdate(state) {
4801 state.writing = false;
4802 state.writecb = null;
4803 state.length -= state.writelen;
4804 state.writelen = 0;
4805 }
4806
4807 function onwrite(stream, er) {
4808 var state = stream._writableState;
4809 var sync = state.sync;
4810 var cb = state.writecb;
4811
4812 onwriteStateUpdate(state);
4813
4814 if (er) onwriteError(stream, state, sync, er, cb);else {
4815 // Check if we're actually ready to finish, but don't emit yet
4816 var finished = needFinish(state);
4817
4818 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
4819 clearBuffer(stream, state);
4820 }
4821
4822 if (sync) {
4823 /*<replacement>*/
4824 asyncWrite(afterWrite, stream, state, finished, cb);
4825 /*</replacement>*/
4826 } else {
4827 afterWrite(stream, state, finished, cb);
4828 }
4829 }
4830 }
4831
4832 function afterWrite(stream, state, finished, cb) {
4833 if (!finished) onwriteDrain(stream, state);
4834 state.pendingcb--;
4835 cb();
4836 finishMaybe(stream, state);
4837 }
4838
4839 // Must force callback to be called on nextTick, so that we don't
4840 // emit 'drain' before the write() consumer gets the 'false' return
4841 // value, and has a chance to attach a 'drain' listener.
4842 function onwriteDrain(stream, state) {
4843 if (state.length === 0 && state.needDrain) {
4844 state.needDrain = false;
4845 stream.emit('drain');
4846 }
4847 }
4848
4849 // if there's something in the buffer waiting, then process it
4850 function clearBuffer(stream, state) {
4851 state.bufferProcessing = true;
4852 var entry = state.bufferedRequest;
4853
4854 if (stream._writev && entry && entry.next) {
4855 // Fast case, write everything using _writev()
4856 var l = state.bufferedRequestCount;
4857 var buffer = new Array(l);
4858 var holder = state.corkedRequestsFree;
4859 holder.entry = entry;
4860
4861 var count = 0;
4862 while (entry) {
4863 buffer[count] = entry;
4864 entry = entry.next;
4865 count += 1;
4866 }
4867
4868 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
4869
4870 // doWrite is almost always async, defer these to save a bit of time
4871 // as the hot path ends with doWrite
4872 state.pendingcb++;
4873 state.lastBufferedRequest = null;
4874 if (holder.next) {
4875 state.corkedRequestsFree = holder.next;
4876 holder.next = null;
4877 } else {
4878 state.corkedRequestsFree = new CorkedRequest(state);
4879 }
4880 } else {
4881 // Slow case, write chunks one-by-one
4882 while (entry) {
4883 var chunk = entry.chunk;
4884 var encoding = entry.encoding;
4885 var cb = entry.callback;
4886 var len = state.objectMode ? 1 : chunk.length;
4887
4888 doWrite(stream, state, false, len, chunk, encoding, cb);
4889 entry = entry.next;
4890 // if we didn't call the onwrite immediately, then
4891 // it means that we need to wait until it does.
4892 // also, that means that the chunk and cb are currently
4893 // being processed, so move the buffer counter past them.
4894 if (state.writing) {
4895 break;
4896 }
4897 }
4898
4899 if (entry === null) state.lastBufferedRequest = null;
4900 }
4901
4902 state.bufferedRequestCount = 0;
4903 state.bufferedRequest = entry;
4904 state.bufferProcessing = false;
4905 }
4906
4907 Writable.prototype._write = function (chunk, encoding, cb) {
4908 cb(new Error('_write() is not implemented'));
4909 };
4910
4911 Writable.prototype._writev = null;
4912
4913 Writable.prototype.end = function (chunk, encoding, cb) {
4914 var state = this._writableState;
4915
4916 if (typeof chunk === 'function') {
4917 cb = chunk;
4918 chunk = null;
4919 encoding = null;
4920 } else if (typeof encoding === 'function') {
4921 cb = encoding;
4922 encoding = null;
4923 }
4924
4925 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
4926
4927 // .end() fully uncorks
4928 if (state.corked) {
4929 state.corked = 1;
4930 this.uncork();
4931 }
4932
4933 // ignore unnecessary end() calls.
4934 if (!state.ending && !state.finished) endWritable(this, state, cb);
4935 };
4936
4937 function needFinish(state) {
4938 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
4939 }
4940
4941 function prefinish(stream, state) {
4942 if (!state.prefinished) {
4943 state.prefinished = true;
4944 stream.emit('prefinish');
4945 }
4946 }
4947
4948 function finishMaybe(stream, state) {
4949 var need = needFinish(state);
4950 if (need) {
4951 if (state.pendingcb === 0) {
4952 prefinish(stream, state);
4953 state.finished = true;
4954 stream.emit('finish');
4955 } else {
4956 prefinish(stream, state);
4957 }
4958 }
4959 return need;
4960 }
4961
4962 function endWritable(stream, state, cb) {
4963 state.ending = true;
4964 finishMaybe(stream, state);
4965 if (cb) {
4966 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
4967 }
4968 state.ended = true;
4969 stream.writable = false;
4970 }
4971
4972 // It seems a linked list but it is not
4973 // there will be only 2 of these for each stream
4974 function CorkedRequest(state) {
4975 var _this = this;
4976
4977 this.next = null;
4978 this.entry = null;
4979 this.finish = function (err) {
4980 var entry = _this.entry;
4981 _this.entry = null;
4982 while (entry) {
4983 var cb = entry.callback;
4984 state.pendingcb--;
4985 cb(err);
4986 entry = entry.next;
4987 }
4988 if (state.corkedRequestsFree) {
4989 state.corkedRequestsFree.next = _this;
4990 } else {
4991 state.corkedRequestsFree = _this;
4992 }
4993 };
4994 }
4995 }).call(this,require('_process'))
4996 },{"./_stream_duplex":15,"./internal/streams/stream":21,"_process":13,"buffer":5,"buffer-shims":4,"core-util-is":6,"inherits":9,"process-nextick-args":12,"util-deprecate":30}],20:[function(require,module,exports){
4997 'use strict';
4998
4999 var Buffer = require('buffer').Buffer;
5000 /*<replacement>*/
5001 var bufferShim = require('buffer-shims');
5002 /*</replacement>*/
5003
5004 module.exports = BufferList;
5005
5006 function BufferList() {
5007 this.head = null;
5008 this.tail = null;
5009 this.length = 0;
5010 }
5011
5012 BufferList.prototype.push = function (v) {
5013 var entry = { data: v, next: null };
5014 if (this.length > 0) this.tail.next = entry;else this.head = entry;
5015 this.tail = entry;
5016 ++this.length;
5017 };
5018
5019 BufferList.prototype.unshift = function (v) {
5020 var entry = { data: v, next: this.head };
5021 if (this.length === 0) this.tail = entry;
5022 this.head = entry;
5023 ++this.length;
5024 };
5025
5026 BufferList.prototype.shift = function () {
5027 if (this.length === 0) return;
5028 var ret = this.head.data;
5029 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
5030 --this.length;
5031 return ret;
5032 };
5033
5034 BufferList.prototype.clear = function () {
5035 this.head = this.tail = null;
5036 this.length = 0;
5037 };
5038
5039 BufferList.prototype.join = function (s) {
5040 if (this.length === 0) return '';
5041 var p = this.head;
5042 var ret = '' + p.data;
5043 while (p = p.next) {
5044 ret += s + p.data;
5045 }return ret;
5046 };
5047
5048 BufferList.prototype.concat = function (n) {
5049 if (this.length === 0) return bufferShim.alloc(0);
5050 if (this.length === 1) return this.head.data;
5051 var ret = bufferShim.allocUnsafe(n >>> 0);
5052 var p = this.head;
5053 var i = 0;
5054 while (p) {
5055 p.data.copy(ret, i);
5056 i += p.data.length;
5057 p = p.next;
5058 }
5059 return ret;
5060 };
5061 },{"buffer":5,"buffer-shims":4}],21:[function(require,module,exports){
5062 module.exports = require('events').EventEmitter;
5063
5064 },{"events":7}],22:[function(require,module,exports){
5065 'use strict';
5066
5067 var Buffer = require('safe-buffer').Buffer;
5068
5069 var isEncoding = Buffer.isEncoding || function (encoding) {
5070 encoding = '' + encoding;
5071 switch (encoding && encoding.toLowerCase()) {
5072 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':
5073 return true;
5074 default:
5075 return false;
5076 }
5077 };
5078
5079 function _normalizeEncoding(enc) {
5080 if (!enc) return 'utf8';
5081 var retried;
5082 while (true) {
5083 switch (enc) {
5084 case 'utf8':
5085 case 'utf-8':
5086 return 'utf8';
5087 case 'ucs2':
5088 case 'ucs-2':
5089 case 'utf16le':
5090 case 'utf-16le':
5091 return 'utf16le';
5092 case 'latin1':
5093 case 'binary':
5094 return 'latin1';
5095 case 'base64':
5096 case 'ascii':
5097 case 'hex':
5098 return enc;
5099 default:
5100 if (retried) return; // undefined
5101 enc = ('' + enc).toLowerCase();
5102 retried = true;
5103 }
5104 }
5105 };
5106
5107 // Do not cache `Buffer.isEncoding` when checking encoding names as some
5108 // modules monkey-patch it to support additional encodings
5109 function normalizeEncoding(enc) {
5110 var nenc = _normalizeEncoding(enc);
5111 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
5112 return nenc || enc;
5113 }
5114
5115 // StringDecoder provides an interface for efficiently splitting a series of
5116 // buffers into a series of JS strings without breaking apart multi-byte
5117 // characters.
5118 exports.StringDecoder = StringDecoder;
5119 function StringDecoder(encoding) {
5120 this.encoding = normalizeEncoding(encoding);
5121 var nb;
5122 switch (this.encoding) {
5123 case 'utf16le':
5124 this.text = utf16Text;
5125 this.end = utf16End;
5126 nb = 4;
5127 break;
5128 case 'utf8':
5129 this.fillLast = utf8FillLast;
5130 nb = 4;
5131 break;
5132 case 'base64':
5133 this.text = base64Text;
5134 this.end = base64End;
5135 nb = 3;
5136 break;
5137 default:
5138 this.write = simpleWrite;
5139 this.end = simpleEnd;
5140 return;
5141 }
5142 this.lastNeed = 0;
5143 this.lastTotal = 0;
5144 this.lastChar = Buffer.allocUnsafe(nb);
5145 }
5146
5147 StringDecoder.prototype.write = function (buf) {
5148 if (buf.length === 0) return '';
5149 var r;
5150 var i;
5151 if (this.lastNeed) {
5152 r = this.fillLast(buf);
5153 if (r === undefined) return '';
5154 i = this.lastNeed;
5155 this.lastNeed = 0;
5156 } else {
5157 i = 0;
5158 }
5159 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
5160 return r || '';
5161 };
5162
5163 StringDecoder.prototype.end = utf8End;
5164
5165 // Returns only complete characters in a Buffer
5166 StringDecoder.prototype.text = utf8Text;
5167
5168 // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
5169 StringDecoder.prototype.fillLast = function (buf) {
5170 if (this.lastNeed <= buf.length) {
5171 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
5172 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5173 }
5174 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
5175 this.lastNeed -= buf.length;
5176 };
5177
5178 // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
5179 // continuation byte.
5180 function utf8CheckByte(byte) {
5181 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;
5182 return -1;
5183 }
5184
5185 // Checks at most 3 bytes at the end of a Buffer in order to detect an
5186 // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
5187 // needed to complete the UTF-8 character (if applicable) are returned.
5188 function utf8CheckIncomplete(self, buf, i) {
5189 var j = buf.length - 1;
5190 if (j < i) return 0;
5191 var nb = utf8CheckByte(buf[j]);
5192 if (nb >= 0) {
5193 if (nb > 0) self.lastNeed = nb - 1;
5194 return nb;
5195 }
5196 if (--j < i) return 0;
5197 nb = utf8CheckByte(buf[j]);
5198 if (nb >= 0) {
5199 if (nb > 0) self.lastNeed = nb - 2;
5200 return nb;
5201 }
5202 if (--j < i) return 0;
5203 nb = utf8CheckByte(buf[j]);
5204 if (nb >= 0) {
5205 if (nb > 0) {
5206 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
5207 }
5208 return nb;
5209 }
5210 return 0;
5211 }
5212
5213 // Validates as many continuation bytes for a multi-byte UTF-8 character as
5214 // needed or are available. If we see a non-continuation byte where we expect
5215 // one, we "replace" the validated continuation bytes we've seen so far with
5216 // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
5217 // behavior. The continuation byte check is included three times in the case
5218 // where all of the continuation bytes for a character exist in the same buffer.
5219 // It is also done this way as a slight performance increase instead of using a
5220 // loop.
5221 function utf8CheckExtraBytes(self, buf, p) {
5222 if ((buf[0] & 0xC0) !== 0x80) {
5223 self.lastNeed = 0;
5224 return '\ufffd'.repeat(p);
5225 }
5226 if (self.lastNeed > 1 && buf.length > 1) {
5227 if ((buf[1] & 0xC0) !== 0x80) {
5228 self.lastNeed = 1;
5229 return '\ufffd'.repeat(p + 1);
5230 }
5231 if (self.lastNeed > 2 && buf.length > 2) {
5232 if ((buf[2] & 0xC0) !== 0x80) {
5233 self.lastNeed = 2;
5234 return '\ufffd'.repeat(p + 2);
5235 }
5236 }
5237 }
5238 }
5239
5240 // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
5241 function utf8FillLast(buf) {
5242 var p = this.lastTotal - this.lastNeed;
5243 var r = utf8CheckExtraBytes(this, buf, p);
5244 if (r !== undefined) return r;
5245 if (this.lastNeed <= buf.length) {
5246 buf.copy(this.lastChar, p, 0, this.lastNeed);
5247 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5248 }
5249 buf.copy(this.lastChar, p, 0, buf.length);
5250 this.lastNeed -= buf.length;
5251 }
5252
5253 // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
5254 // partial character, the character's bytes are buffered until the required
5255 // number of bytes are available.
5256 function utf8Text(buf, i) {
5257 var total = utf8CheckIncomplete(this, buf, i);
5258 if (!this.lastNeed) return buf.toString('utf8', i);
5259 this.lastTotal = total;
5260 var end = buf.length - (total - this.lastNeed);
5261 buf.copy(this.lastChar, 0, end);
5262 return buf.toString('utf8', i, end);
5263 }
5264
5265 // For UTF-8, a replacement character for each buffered byte of a (partial)
5266 // character needs to be added to the output.
5267 function utf8End(buf) {
5268 var r = buf && buf.length ? this.write(buf) : '';
5269 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
5270 return r;
5271 }
5272
5273 // UTF-16LE typically needs two bytes per character, but even if we have an even
5274 // number of bytes available, we need to check if we end on a leading/high
5275 // surrogate. In that case, we need to wait for the next two bytes in order to
5276 // decode the last character properly.
5277 function utf16Text(buf, i) {
5278 if ((buf.length - i) % 2 === 0) {
5279 var r = buf.toString('utf16le', i);
5280 if (r) {
5281 var c = r.charCodeAt(r.length - 1);
5282 if (c >= 0xD800 && c <= 0xDBFF) {
5283 this.lastNeed = 2;
5284 this.lastTotal = 4;
5285 this.lastChar[0] = buf[buf.length - 2];
5286 this.lastChar[1] = buf[buf.length - 1];
5287 return r.slice(0, -1);
5288 }
5289 }
5290 return r;
5291 }
5292 this.lastNeed = 1;
5293 this.lastTotal = 2;
5294 this.lastChar[0] = buf[buf.length - 1];
5295 return buf.toString('utf16le', i, buf.length - 1);
5296 }
5297
5298 // For UTF-16LE we do not explicitly append special replacement characters if we
5299 // end on a partial character, we simply let v8 handle that.
5300 function utf16End(buf) {
5301 var r = buf && buf.length ? this.write(buf) : '';
5302 if (this.lastNeed) {
5303 var end = this.lastTotal - this.lastNeed;
5304 return r + this.lastChar.toString('utf16le', 0, end);
5305 }
5306 return r;
5307 }
5308
5309 function base64Text(buf, i) {
5310 var n = (buf.length - i) % 3;
5311 if (n === 0) return buf.toString('base64', i);
5312 this.lastNeed = 3 - n;
5313 this.lastTotal = 3;
5314 if (n === 1) {
5315 this.lastChar[0] = buf[buf.length - 1];
5316 } else {
5317 this.lastChar[0] = buf[buf.length - 2];
5318 this.lastChar[1] = buf[buf.length - 1];
5319 }
5320 return buf.toString('base64', i, buf.length - n);
5321 }
5322
5323 function base64End(buf) {
5324 var r = buf && buf.length ? this.write(buf) : '';
5325 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
5326 return r;
5327 }
5328
5329 // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
5330 function simpleWrite(buf) {
5331 return buf.toString(this.encoding);
5332 }
5333
5334 function simpleEnd(buf) {
5335 return buf && buf.length ? this.write(buf) : '';
5336 }
5337 },{"safe-buffer":27}],23:[function(require,module,exports){
5338 module.exports = require('./readable').PassThrough
5339
5340 },{"./readable":24}],24:[function(require,module,exports){
5341 exports = module.exports = require('./lib/_stream_readable.js');
5342 exports.Stream = exports;
5343 exports.Readable = exports;
5344 exports.Writable = require('./lib/_stream_writable.js');
5345 exports.Duplex = require('./lib/_stream_duplex.js');
5346 exports.Transform = require('./lib/_stream_transform.js');
5347 exports.PassThrough = require('./lib/_stream_passthrough.js');
5348
5349 },{"./lib/_stream_duplex.js":15,"./lib/_stream_passthrough.js":16,"./lib/_stream_readable.js":17,"./lib/_stream_transform.js":18,"./lib/_stream_writable.js":19}],25:[function(require,module,exports){
5350 module.exports = require('./readable').Transform
5351
5352 },{"./readable":24}],26:[function(require,module,exports){
5353 module.exports = require('./lib/_stream_writable.js');
5354
5355 },{"./lib/_stream_writable.js":19}],27:[function(require,module,exports){
5356 module.exports = require('buffer')
5357
5358 },{"buffer":5}],28:[function(require,module,exports){
5359 // Copyright Joyent, Inc. and other Node contributors.
5360 //
5361 // Permission is hereby granted, free of charge, to any person obtaining a
5362 // copy of this software and associated documentation files (the
5363 // "Software"), to deal in the Software without restriction, including
5364 // without limitation the rights to use, copy, modify, merge, publish,
5365 // distribute, sublicense, and/or sell copies of the Software, and to permit
5366 // persons to whom the Software is furnished to do so, subject to the
5367 // following conditions:
5368 //
5369 // The above copyright notice and this permission notice shall be included
5370 // in all copies or substantial portions of the Software.
5371 //
5372 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5373 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5374 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5375 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5376 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5377 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5378 // USE OR OTHER DEALINGS IN THE SOFTWARE.
5379
5380 module.exports = Stream;
5381
5382 var EE = require('events').EventEmitter;
5383 var inherits = require('inherits');
5384
5385 inherits(Stream, EE);
5386 Stream.Readable = require('readable-stream/readable.js');
5387 Stream.Writable = require('readable-stream/writable.js');
5388 Stream.Duplex = require('readable-stream/duplex.js');
5389 Stream.Transform = require('readable-stream/transform.js');
5390 Stream.PassThrough = require('readable-stream/passthrough.js');
5391
5392 // Backwards-compat with node 0.4.x
5393 Stream.Stream = Stream;
5394
5395
5396
5397 // old-style streams. Note that the pipe method (the only relevant
5398 // part of this class) is overridden in the Readable class.
5399
5400 function Stream() {
5401 EE.call(this);
5402 }
5403
5404 Stream.prototype.pipe = function(dest, options) {
5405 var source = this;
5406
5407 function ondata(chunk) {
5408 if (dest.writable) {
5409 if (false === dest.write(chunk) && source.pause) {
5410 source.pause();
5411 }
5412 }
5413 }
5414
5415 source.on('data', ondata);
5416
5417 function ondrain() {
5418 if (source.readable && source.resume) {
5419 source.resume();
5420 }
5421 }
5422
5423 dest.on('drain', ondrain);
5424
5425 // If the 'end' option is not supplied, dest.end() will be called when
5426 // source gets the 'end' or 'close' events. Only dest.end() once.
5427 if (!dest._isStdio && (!options || options.end !== false)) {
5428 source.on('end', onend);
5429 source.on('close', onclose);
5430 }
5431
5432 var didOnEnd = false;
5433 function onend() {
5434 if (didOnEnd) return;
5435 didOnEnd = true;
5436
5437 dest.end();
5438 }
5439
5440
5441 function onclose() {
5442 if (didOnEnd) return;
5443 didOnEnd = true;
5444
5445 if (typeof dest.destroy === 'function') dest.destroy();
5446 }
5447
5448 // don't leave dangling pipes when there are errors.
5449 function onerror(er) {
5450 cleanup();
5451 if (EE.listenerCount(this, 'error') === 0) {
5452 throw er; // Unhandled stream error in pipe.
5453 }
5454 }
5455
5456 source.on('error', onerror);
5457 dest.on('error', onerror);
5458
5459 // remove all the event listeners that were added.
5460 function cleanup() {
5461 source.removeListener('data', ondata);
5462 dest.removeListener('drain', ondrain);
5463
5464 source.removeListener('end', onend);
5465 source.removeListener('close', onclose);
5466
5467 source.removeListener('error', onerror);
5468 dest.removeListener('error', onerror);
5469
5470 source.removeListener('end', cleanup);
5471 source.removeListener('close', cleanup);
5472
5473 dest.removeListener('close', cleanup);
5474 }
5475
5476 source.on('end', cleanup);
5477 source.on('close', cleanup);
5478
5479 dest.on('close', cleanup);
5480
5481 dest.emit('pipe', source);
5482
5483 // Allow for unix-like usage: A.pipe(B).pipe(C)
5484 return dest;
5485 };
5486
5487 },{"events":7,"inherits":9,"readable-stream/duplex.js":14,"readable-stream/passthrough.js":23,"readable-stream/readable.js":24,"readable-stream/transform.js":25,"readable-stream/writable.js":26}],29:[function(require,module,exports){
5488 // Copyright Joyent, Inc. and other Node contributors.
5489 //
5490 // Permission is hereby granted, free of charge, to any person obtaining a
5491 // copy of this software and associated documentation files (the
5492 // "Software"), to deal in the Software without restriction, including
5493 // without limitation the rights to use, copy, modify, merge, publish,
5494 // distribute, sublicense, and/or sell copies of the Software, and to permit
5495 // persons to whom the Software is furnished to do so, subject to the
5496 // following conditions:
5497 //
5498 // The above copyright notice and this permission notice shall be included
5499 // in all copies or substantial portions of the Software.
5500 //
5501 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5502 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5503 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5504 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5505 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5506 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5507 // USE OR OTHER DEALINGS IN THE SOFTWARE.
5508
5509 var Buffer = require('buffer').Buffer;
5510
5511 var isBufferEncoding = Buffer.isEncoding
5512 || function(encoding) {
5513 switch (encoding && encoding.toLowerCase()) {
5514 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': return true;
5515 default: return false;
5516 }
5517 }
5518
5519
5520 function assertEncoding(encoding) {
5521 if (encoding && !isBufferEncoding(encoding)) {
5522 throw new Error('Unknown encoding: ' + encoding);
5523 }
5524 }
5525
5526 // StringDecoder provides an interface for efficiently splitting a series of
5527 // buffers into a series of JS strings without breaking apart multi-byte
5528 // characters. CESU-8 is handled as part of the UTF-8 encoding.
5529 //
5530 // @TODO Handling all encodings inside a single object makes it very difficult
5531 // to reason about this code, so it should be split up in the future.
5532 // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
5533 // points as used by CESU-8.
5534 var StringDecoder = exports.StringDecoder = function(encoding) {
5535 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
5536 assertEncoding(encoding);
5537 switch (this.encoding) {
5538 case 'utf8':
5539 // CESU-8 represents each of Surrogate Pair by 3-bytes
5540 this.surrogateSize = 3;
5541 break;
5542 case 'ucs2':
5543 case 'utf16le':
5544 // UTF-16 represents each of Surrogate Pair by 2-bytes
5545 this.surrogateSize = 2;
5546 this.detectIncompleteChar = utf16DetectIncompleteChar;
5547 break;
5548 case 'base64':
5549 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
5550 this.surrogateSize = 3;
5551 this.detectIncompleteChar = base64DetectIncompleteChar;
5552 break;
5553 default:
5554 this.write = passThroughWrite;
5555 return;
5556 }
5557
5558 // Enough space to store all bytes of a single character. UTF-8 needs 4
5559 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
5560 this.charBuffer = new Buffer(6);
5561 // Number of bytes received for the current incomplete multi-byte character.
5562 this.charReceived = 0;
5563 // Number of bytes expected for the current incomplete multi-byte character.
5564 this.charLength = 0;
5565 };
5566
5567
5568 // write decodes the given buffer and returns it as JS string that is
5569 // guaranteed to not contain any partial multi-byte characters. Any partial
5570 // character found at the end of the buffer is buffered up, and will be
5571 // returned when calling write again with the remaining bytes.
5572 //
5573 // Note: Converting a Buffer containing an orphan surrogate to a String
5574 // currently works, but converting a String to a Buffer (via `new Buffer`, or
5575 // Buffer#write) will replace incomplete surrogates with the unicode
5576 // replacement character. See https://codereview.chromium.org/121173009/ .
5577 StringDecoder.prototype.write = function(buffer) {
5578 var charStr = '';
5579 // if our last write ended with an incomplete multibyte character
5580 while (this.charLength) {
5581 // determine how many remaining bytes this buffer has to offer for this char
5582 var available = (buffer.length >= this.charLength - this.charReceived) ?
5583 this.charLength - this.charReceived :
5584 buffer.length;
5585
5586 // add the new bytes to the char buffer
5587 buffer.copy(this.charBuffer, this.charReceived, 0, available);
5588 this.charReceived += available;
5589
5590 if (this.charReceived < this.charLength) {
5591 // still not enough chars in this buffer? wait for more ...
5592 return '';
5593 }
5594
5595 // remove bytes belonging to the current character from the buffer
5596 buffer = buffer.slice(available, buffer.length);
5597
5598 // get the character that was split
5599 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
5600
5601 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
5602 var charCode = charStr.charCodeAt(charStr.length - 1);
5603 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
5604 this.charLength += this.surrogateSize;
5605 charStr = '';
5606 continue;
5607 }
5608 this.charReceived = this.charLength = 0;
5609
5610 // if there are no more bytes in this buffer, just emit our char
5611 if (buffer.length === 0) {
5612 return charStr;
5613 }
5614 break;
5615 }
5616
5617 // determine and set charLength / charReceived
5618 this.detectIncompleteChar(buffer);
5619
5620 var end = buffer.length;
5621 if (this.charLength) {
5622 // buffer the incomplete character bytes we got
5623 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
5624 end -= this.charReceived;
5625 }
5626
5627 charStr += buffer.toString(this.encoding, 0, end);
5628
5629 var end = charStr.length - 1;
5630 var charCode = charStr.charCodeAt(end);
5631 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
5632 if (charCode >= 0xD800 && charCode <= 0xDBFF) {
5633 var size = this.surrogateSize;
5634 this.charLength += size;
5635 this.charReceived += size;
5636 this.charBuffer.copy(this.charBuffer, size, 0, size);
5637 buffer.copy(this.charBuffer, 0, 0, size);
5638 return charStr.substring(0, end);
5639 }
5640
5641 // or just emit the charStr
5642 return charStr;
5643 };
5644
5645 // detectIncompleteChar determines if there is an incomplete UTF-8 character at
5646 // the end of the given buffer. If so, it sets this.charLength to the byte
5647 // length that character, and sets this.charReceived to the number of bytes
5648 // that are available for this character.
5649 StringDecoder.prototype.detectIncompleteChar = function(buffer) {
5650 // determine how many bytes we have to check at the end of this buffer
5651 var i = (buffer.length >= 3) ? 3 : buffer.length;
5652
5653 // Figure out if one of the last i bytes of our buffer announces an
5654 // incomplete char.
5655 for (; i > 0; i--) {
5656 var c = buffer[buffer.length - i];
5657
5658 // See http://en.wikipedia.org/wiki/UTF-8#Description
5659
5660 // 110XXXXX
5661 if (i == 1 && c >> 5 == 0x06) {
5662 this.charLength = 2;
5663 break;
5664 }
5665
5666 // 1110XXXX
5667 if (i <= 2 && c >> 4 == 0x0E) {
5668 this.charLength = 3;
5669 break;
5670 }
5671
5672 // 11110XXX
5673 if (i <= 3 && c >> 3 == 0x1E) {
5674 this.charLength = 4;
5675 break;
5676 }
5677 }
5678 this.charReceived = i;
5679 };
5680
5681 StringDecoder.prototype.end = function(buffer) {
5682 var res = '';
5683 if (buffer && buffer.length)
5684 res = this.write(buffer);
5685
5686 if (this.charReceived) {
5687 var cr = this.charReceived;
5688 var buf = this.charBuffer;
5689 var enc = this.encoding;
5690 res += buf.slice(0, cr).toString(enc);
5691 }
5692
5693 return res;
5694 };
5695
5696 function passThroughWrite(buffer) {
5697 return buffer.toString(this.encoding);
5698 }
5699
5700 function utf16DetectIncompleteChar(buffer) {
5701 this.charReceived = buffer.length % 2;
5702 this.charLength = this.charReceived ? 2 : 0;
5703 }
5704
5705 function base64DetectIncompleteChar(buffer) {
5706 this.charReceived = buffer.length % 3;
5707 this.charLength = this.charReceived ? 3 : 0;
5708 }
5709
5710 },{"buffer":5}],30:[function(require,module,exports){
5711 (function (global){
5712
5713 /**
5714 * Module exports.
5715 */
5716
5717 module.exports = deprecate;
5718
5719 /**
5720 * Mark that a method should not be used.
5721 * Returns a modified function which warns once by default.
5722 *
5723 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
5724 *
5725 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
5726 * will throw an Error when invoked.
5727 *
5728 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
5729 * will invoke `console.trace()` instead of `console.error()`.
5730 *
5731 * @param {Function} fn - the function to deprecate
5732 * @param {String} msg - the string to print to the console when `fn` is invoked
5733 * @returns {Function} a new "deprecated" version of `fn`
5734 * @api public
5735 */
5736
5737 function deprecate (fn, msg) {
5738 if (config('noDeprecation')) {
5739 return fn;
5740 }
5741
5742 var warned = false;
5743 function deprecated() {
5744 if (!warned) {
5745 if (config('throwDeprecation')) {
5746 throw new Error(msg);
5747 } else if (config('traceDeprecation')) {
5748 console.trace(msg);
5749 } else {
5750 console.warn(msg);
5751 }
5752 warned = true;
5753 }
5754 return fn.apply(this, arguments);
5755 }
5756
5757 return deprecated;
5758 }
5759
5760 /**
5761 * Checks `localStorage` for boolean values for the given `name`.
5762 *
5763 * @param {String} name
5764 * @returns {Boolean}
5765 * @api private
5766 */
5767
5768 function config (name) {
5769 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
5770 try {
5771 if (!global.localStorage) return false;
5772 } catch (_) {
5773 return false;
5774 }
5775 var val = global.localStorage[name];
5776 if (null == val) return false;
5777 return String(val).toLowerCase() === 'true';
5778 }
5779
5780 }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5781 },{}],31:[function(require,module,exports){
5782 arguments[4][9][0].apply(exports,arguments)
5783 },{"dup":9}],32:[function(require,module,exports){
5784 module.exports = function isBuffer(arg) {
5785 return arg && typeof arg === 'object'
5786 && typeof arg.copy === 'function'
5787 && typeof arg.fill === 'function'
5788 && typeof arg.readUInt8 === 'function';
5789 }
5790 },{}],33:[function(require,module,exports){
5791 (function (process,global){
5792 // Copyright Joyent, Inc. and other Node contributors.
5793 //
5794 // Permission is hereby granted, free of charge, to any person obtaining a
5795 // copy of this software and associated documentation files (the
5796 // "Software"), to deal in the Software without restriction, including
5797 // without limitation the rights to use, copy, modify, merge, publish,
5798 // distribute, sublicense, and/or sell copies of the Software, and to permit
5799 // persons to whom the Software is furnished to do so, subject to the
5800 // following conditions:
5801 //
5802 // The above copyright notice and this permission notice shall be included
5803 // in all copies or substantial portions of the Software.
5804 //
5805 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5806 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5807 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5808 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
5809 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
5810 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
5811 // USE OR OTHER DEALINGS IN THE SOFTWARE.
5812
5813 var formatRegExp = /%[sdj%]/g;
5814 exports.format = function(f) {
5815 if (!isString(f)) {
5816 var objects = [];
5817 for (var i = 0; i < arguments.length; i++) {
5818 objects.push(inspect(arguments[i]));
5819 }
5820 return objects.join(' ');
5821 }
5822
5823 var i = 1;
5824 var args = arguments;
5825 var len = args.length;
5826 var str = String(f).replace(formatRegExp, function(x) {
5827 if (x === '%%') return '%';
5828 if (i >= len) return x;
5829 switch (x) {
5830 case '%s': return String(args[i++]);
5831 case '%d': return Number(args[i++]);
5832 case '%j':
5833 try {
5834 return JSON.stringify(args[i++]);
5835 } catch (_) {
5836 return '[Circular]';
5837 }
5838 default:
5839 return x;
5840 }
5841 });
5842 for (var x = args[i]; i < len; x = args[++i]) {
5843 if (isNull(x) || !isObject(x)) {
5844 str += ' ' + x;
5845 } else {
5846 str += ' ' + inspect(x);
5847 }
5848 }
5849 return str;
5850 };
5851
5852
5853 // Mark that a method should not be used.
5854 // Returns a modified function which warns once by default.
5855 // If --no-deprecation is set, then it is a no-op.
5856 exports.deprecate = function(fn, msg) {
5857 // Allow for deprecating things in the process of starting up.
5858 if (isUndefined(global.process)) {
5859 return function() {
5860 return exports.deprecate(fn, msg).apply(this, arguments);
5861 };
5862 }
5863
5864 if (process.noDeprecation === true) {
5865 return fn;
5866 }
5867
5868 var warned = false;
5869 function deprecated() {
5870 if (!warned) {
5871 if (process.throwDeprecation) {
5872 throw new Error(msg);
5873 } else if (process.traceDeprecation) {
5874 console.trace(msg);
5875 } else {
5876 console.error(msg);
5877 }
5878 warned = true;
5879 }
5880 return fn.apply(this, arguments);
5881 }
5882
5883 return deprecated;
5884 };
5885
5886
5887 var debugs = {};
5888 var debugEnviron;
5889 exports.debuglog = function(set) {
5890 if (isUndefined(debugEnviron))
5891 debugEnviron = process.env.NODE_DEBUG || '';
5892 set = set.toUpperCase();
5893 if (!debugs[set]) {
5894 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
5895 var pid = process.pid;
5896 debugs[set] = function() {
5897 var msg = exports.format.apply(exports, arguments);
5898 console.error('%s %d: %s', set, pid, msg);
5899 };
5900 } else {
5901 debugs[set] = function() {};
5902 }
5903 }
5904 return debugs[set];
5905 };
5906
5907
5908 /**
5909 * Echos the value of a value. Trys to print the value out
5910 * in the best way possible given the different types.
5911 *
5912 * @param {Object} obj The object to print out.
5913 * @param {Object} opts Optional options object that alters the output.
5914 */
5915 /* legacy: obj, showHidden, depth, colors*/
5916 function inspect(obj, opts) {
5917 // default options
5918 var ctx = {
5919 seen: [],
5920 stylize: stylizeNoColor
5921 };
5922 // legacy...
5923 if (arguments.length >= 3) ctx.depth = arguments[2];
5924 if (arguments.length >= 4) ctx.colors = arguments[3];
5925 if (isBoolean(opts)) {
5926 // legacy...
5927 ctx.showHidden = opts;
5928 } else if (opts) {
5929 // got an "options" object
5930 exports._extend(ctx, opts);
5931 }
5932 // set default options
5933 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
5934 if (isUndefined(ctx.depth)) ctx.depth = 2;
5935 if (isUndefined(ctx.colors)) ctx.colors = false;
5936 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
5937 if (ctx.colors) ctx.stylize = stylizeWithColor;
5938 return formatValue(ctx, obj, ctx.depth);
5939 }
5940 exports.inspect = inspect;
5941
5942
5943 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
5944 inspect.colors = {
5945 'bold' : [1, 22],
5946 'italic' : [3, 23],
5947 'underline' : [4, 24],
5948 'inverse' : [7, 27],
5949 'white' : [37, 39],
5950 'grey' : [90, 39],
5951 'black' : [30, 39],
5952 'blue' : [34, 39],
5953 'cyan' : [36, 39],
5954 'green' : [32, 39],
5955 'magenta' : [35, 39],
5956 'red' : [31, 39],
5957 'yellow' : [33, 39]
5958 };
5959
5960 // Don't use 'blue' not visible on cmd.exe
5961 inspect.styles = {
5962 'special': 'cyan',
5963 'number': 'yellow',
5964 'boolean': 'yellow',
5965 'undefined': 'grey',
5966 'null': 'bold',
5967 'string': 'green',
5968 'date': 'magenta',
5969 // "name": intentionally not styling
5970 'regexp': 'red'
5971 };
5972
5973
5974 function stylizeWithColor(str, styleType) {
5975 var style = inspect.styles[styleType];
5976
5977 if (style) {
5978 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
5979 '\u001b[' + inspect.colors[style][1] + 'm';
5980 } else {
5981 return str;
5982 }
5983 }
5984
5985
5986 function stylizeNoColor(str, styleType) {
5987 return str;
5988 }
5989
5990
5991 function arrayToHash(array) {
5992 var hash = {};
5993
5994 array.forEach(function(val, idx) {
5995 hash[val] = true;
5996 });
5997
5998 return hash;
5999 }
6000
6001
6002 function formatValue(ctx, value, recurseTimes) {
6003 // Provide a hook for user-specified inspect functions.
6004 // Check that value is an object with an inspect function on it
6005 if (ctx.customInspect &&
6006 value &&
6007 isFunction(value.inspect) &&
6008 // Filter out the util module, it's inspect function is special
6009 value.inspect !== exports.inspect &&
6010 // Also filter out any prototype objects using the circular check.
6011 !(value.constructor && value.constructor.prototype === value)) {
6012 var ret = value.inspect(recurseTimes, ctx);
6013 if (!isString(ret)) {
6014 ret = formatValue(ctx, ret, recurseTimes);
6015 }
6016 return ret;
6017 }
6018
6019 // Primitive types cannot have properties
6020 var primitive = formatPrimitive(ctx, value);
6021 if (primitive) {
6022 return primitive;
6023 }
6024
6025 // Look up the keys of the object.
6026 var keys = Object.keys(value);
6027 var visibleKeys = arrayToHash(keys);
6028
6029 if (ctx.showHidden) {
6030 keys = Object.getOwnPropertyNames(value);
6031 }
6032
6033 // IE doesn't make error fields non-enumerable
6034 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
6035 if (isError(value)
6036 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
6037 return formatError(value);
6038 }
6039
6040 // Some type of object without properties can be shortcutted.
6041 if (keys.length === 0) {
6042 if (isFunction(value)) {
6043 var name = value.name ? ': ' + value.name : '';
6044 return ctx.stylize('[Function' + name + ']', 'special');
6045 }
6046 if (isRegExp(value)) {
6047 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6048 }
6049 if (isDate(value)) {
6050 return ctx.stylize(Date.prototype.toString.call(value), 'date');
6051 }
6052 if (isError(value)) {
6053 return formatError(value);
6054 }
6055 }
6056
6057 var base = '', array = false, braces = ['{', '}'];
6058
6059 // Make Array say that they are Array
6060 if (isArray(value)) {
6061 array = true;
6062 braces = ['[', ']'];
6063 }
6064
6065 // Make functions say that they are functions
6066 if (isFunction(value)) {
6067 var n = value.name ? ': ' + value.name : '';
6068 base = ' [Function' + n + ']';
6069 }
6070
6071 // Make RegExps say that they are RegExps
6072 if (isRegExp(value)) {
6073 base = ' ' + RegExp.prototype.toString.call(value);
6074 }
6075
6076 // Make dates with properties first say the date
6077 if (isDate(value)) {
6078 base = ' ' + Date.prototype.toUTCString.call(value);
6079 }
6080
6081 // Make error with message first say the error
6082 if (isError(value)) {
6083 base = ' ' + formatError(value);
6084 }
6085
6086 if (keys.length === 0 && (!array || value.length == 0)) {
6087 return braces[0] + base + braces[1];
6088 }
6089
6090 if (recurseTimes < 0) {
6091 if (isRegExp(value)) {
6092 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
6093 } else {
6094 return ctx.stylize('[Object]', 'special');
6095 }
6096 }
6097
6098 ctx.seen.push(value);
6099
6100 var output;
6101 if (array) {
6102 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
6103 } else {
6104 output = keys.map(function(key) {
6105 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
6106 });
6107 }
6108
6109 ctx.seen.pop();
6110
6111 return reduceToSingleString(output, base, braces);
6112 }
6113
6114
6115 function formatPrimitive(ctx, value) {
6116 if (isUndefined(value))
6117 return ctx.stylize('undefined', 'undefined');
6118 if (isString(value)) {
6119 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
6120 .replace(/'/g, "\\'")
6121 .replace(/\\"/g, '"') + '\'';
6122 return ctx.stylize(simple, 'string');
6123 }
6124 if (isNumber(value))
6125 return ctx.stylize('' + value, 'number');
6126 if (isBoolean(value))
6127 return ctx.stylize('' + value, 'boolean');
6128 // For some reason typeof null is "object", so special case here.
6129 if (isNull(value))
6130 return ctx.stylize('null', 'null');
6131 }
6132
6133
6134 function formatError(value) {
6135 return '[' + Error.prototype.toString.call(value) + ']';
6136 }
6137
6138
6139 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
6140 var output = [];
6141 for (var i = 0, l = value.length; i < l; ++i) {
6142 if (hasOwnProperty(value, String(i))) {
6143 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6144 String(i), true));
6145 } else {
6146 output.push('');
6147 }
6148 }
6149 keys.forEach(function(key) {
6150 if (!key.match(/^\d+$/)) {
6151 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
6152 key, true));
6153 }
6154 });
6155 return output;
6156 }
6157
6158
6159 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
6160 var name, str, desc;
6161 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
6162 if (desc.get) {
6163 if (desc.set) {
6164 str = ctx.stylize('[Getter/Setter]', 'special');
6165 } else {
6166 str = ctx.stylize('[Getter]', 'special');
6167 }
6168 } else {
6169 if (desc.set) {
6170 str = ctx.stylize('[Setter]', 'special');
6171 }
6172 }
6173 if (!hasOwnProperty(visibleKeys, key)) {
6174 name = '[' + key + ']';
6175 }
6176 if (!str) {
6177 if (ctx.seen.indexOf(desc.value) < 0) {
6178 if (isNull(recurseTimes)) {
6179 str = formatValue(ctx, desc.value, null);
6180 } else {
6181 str = formatValue(ctx, desc.value, recurseTimes - 1);
6182 }
6183 if (str.indexOf('\n') > -1) {
6184 if (array) {
6185 str = str.split('\n').map(function(line) {
6186 return ' ' + line;
6187 }).join('\n').substr(2);
6188 } else {
6189 str = '\n' + str.split('\n').map(function(line) {
6190 return ' ' + line;
6191 }).join('\n');
6192 }
6193 }
6194 } else {
6195 str = ctx.stylize('[Circular]', 'special');
6196 }
6197 }
6198 if (isUndefined(name)) {
6199 if (array && key.match(/^\d+$/)) {
6200 return str;
6201 }
6202 name = JSON.stringify('' + key);
6203 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
6204 name = name.substr(1, name.length - 2);
6205 name = ctx.stylize(name, 'name');
6206 } else {
6207 name = name.replace(/'/g, "\\'")
6208 .replace(/\\"/g, '"')
6209 .replace(/(^"|"$)/g, "'");
6210 name = ctx.stylize(name, 'string');
6211 }
6212 }
6213
6214 return name + ': ' + str;
6215 }
6216
6217
6218 function reduceToSingleString(output, base, braces) {
6219 var numLinesEst = 0;
6220 var length = output.reduce(function(prev, cur) {
6221 numLinesEst++;
6222 if (cur.indexOf('\n') >= 0) numLinesEst++;
6223 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
6224 }, 0);
6225
6226 if (length > 60) {
6227 return braces[0] +
6228 (base === '' ? '' : base + '\n ') +
6229 ' ' +
6230 output.join(',\n ') +
6231 ' ' +
6232 braces[1];
6233 }
6234
6235 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
6236 }
6237
6238
6239 // NOTE: These type checking functions intentionally don't use `instanceof`
6240 // because it is fragile and can be easily faked with `Object.create()`.
6241 function isArray(ar) {
6242 return Array.isArray(ar);
6243 }
6244 exports.isArray = isArray;
6245
6246 function isBoolean(arg) {
6247 return typeof arg === 'boolean';
6248 }
6249 exports.isBoolean = isBoolean;
6250
6251 function isNull(arg) {
6252 return arg === null;
6253 }
6254 exports.isNull = isNull;
6255
6256 function isNullOrUndefined(arg) {
6257 return arg == null;
6258 }
6259 exports.isNullOrUndefined = isNullOrUndefined;
6260
6261 function isNumber(arg) {
6262 return typeof arg === 'number';
6263 }
6264 exports.isNumber = isNumber;
6265
6266 function isString(arg) {
6267 return typeof arg === 'string';
6268 }
6269 exports.isString = isString;
6270
6271 function isSymbol(arg) {
6272 return typeof arg === 'symbol';
6273 }
6274 exports.isSymbol = isSymbol;
6275
6276 function isUndefined(arg) {
6277 return arg === void 0;
6278 }
6279 exports.isUndefined = isUndefined;
6280
6281 function isRegExp(re) {
6282 return isObject(re) && objectToString(re) === '[object RegExp]';
6283 }
6284 exports.isRegExp = isRegExp;
6285
6286 function isObject(arg) {
6287 return typeof arg === 'object' && arg !== null;
6288 }
6289 exports.isObject = isObject;
6290
6291 function isDate(d) {
6292 return isObject(d) && objectToString(d) === '[object Date]';
6293 }
6294 exports.isDate = isDate;
6295
6296 function isError(e) {
6297 return isObject(e) &&
6298 (objectToString(e) === '[object Error]' || e instanceof Error);
6299 }
6300 exports.isError = isError;
6301
6302 function isFunction(arg) {
6303 return typeof arg === 'function';
6304 }
6305 exports.isFunction = isFunction;
6306
6307 function isPrimitive(arg) {
6308 return arg === null ||
6309 typeof arg === 'boolean' ||
6310 typeof arg === 'number' ||
6311 typeof arg === 'string' ||
6312 typeof arg === 'symbol' || // ES6 symbol
6313 typeof arg === 'undefined';
6314 }
6315 exports.isPrimitive = isPrimitive;
6316
6317 exports.isBuffer = require('./support/isBuffer');
6318
6319 function objectToString(o) {
6320 return Object.prototype.toString.call(o);
6321 }
6322
6323
6324 function pad(n) {
6325 return n < 10 ? '0' + n.toString(10) : n.toString(10);
6326 }
6327
6328
6329 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
6330 'Oct', 'Nov', 'Dec'];
6331
6332 // 26 Feb 16:19:34
6333 function timestamp() {
6334 var d = new Date();
6335 var time = [pad(d.getHours()),
6336 pad(d.getMinutes()),
6337 pad(d.getSeconds())].join(':');
6338 return [d.getDate(), months[d.getMonth()], time].join(' ');
6339 }
6340
6341
6342 // log is just a thin wrapper to console.log that prepends a timestamp
6343 exports.log = function() {
6344 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
6345 };
6346
6347
6348 /**
6349 * Inherit the prototype methods from one constructor into another.
6350 *
6351 * The Function.prototype.inherits from lang.js rewritten as a standalone
6352 * function (not on Function.prototype). NOTE: If this file is to be loaded
6353 * during bootstrapping this function needs to be rewritten using some native
6354 * functions as prototype setup using normal JavaScript does not work as
6355 * expected during bootstrapping (see mirror.js in r114903).
6356 *
6357 * @param {function} ctor Constructor function which needs to inherit the
6358 * prototype.
6359 * @param {function} superCtor Constructor function to inherit prototype from.
6360 */
6361 exports.inherits = require('inherits');
6362
6363 exports._extend = function(origin, add) {
6364 // Don't do anything if add isn't an object
6365 if (!add || !isObject(add)) return origin;
6366
6367 var keys = Object.keys(add);
6368 var i = keys.length;
6369 while (i--) {
6370 origin[keys[i]] = add[keys[i]];
6371 }
6372 return origin;
6373 };
6374
6375 function hasOwnProperty(obj, prop) {
6376 return Object.prototype.hasOwnProperty.call(obj, prop);
6377 }
6378
6379 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6380 },{"./support/isBuffer":32,"_process":13,"inherits":31}],34:[function(require,module,exports){
6381 let bitcoin = require('bitcoinjs-lib');
6382
6383 module.exports = {
6384 bitcoin
6385 }
6386
6387 },{"bitcoinjs-lib":52}],35:[function(require,module,exports){
6388 // base-x encoding
6389 // Forked from https://github.com/cryptocoinjs/bs58
6390 // Originally written by Mike Hearn for BitcoinJ
6391 // Copyright (c) 2011 Google Inc
6392 // Ported to JavaScript by Stefan Thomas
6393 // Merged Buffer refactorings from base58-native by Stephen Pair
6394 // Copyright (c) 2013 BitPay Inc
6395
6396 var Buffer = require('safe-buffer').Buffer
6397
6398 module.exports = function base (ALPHABET) {
6399 var ALPHABET_MAP = {}
6400 var BASE = ALPHABET.length
6401 var LEADER = ALPHABET.charAt(0)
6402
6403 // pre-compute lookup table
6404 for (var z = 0; z < ALPHABET.length; z++) {
6405 var x = ALPHABET.charAt(z)
6406
6407 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
6408 ALPHABET_MAP[x] = z
6409 }
6410
6411 function encode (source) {
6412 if (source.length === 0) return ''
6413
6414 var digits = [0]
6415 for (var i = 0; i < source.length; ++i) {
6416 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
6417 carry += digits[j] << 8
6418 digits[j] = carry % BASE
6419 carry = (carry / BASE) | 0
6420 }
6421
6422 while (carry > 0) {
6423 digits.push(carry % BASE)
6424 carry = (carry / BASE) | 0
6425 }
6426 }
6427
6428 var string = ''
6429
6430 // deal with leading zeros
6431 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
6432 // convert digits to a string
6433 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
6434
6435 return string
6436 }
6437
6438 function decodeUnsafe (string) {
6439 if (typeof string !== 'string') throw new TypeError('Expected String')
6440 if (string.length === 0) return Buffer.allocUnsafe(0)
6441
6442 var bytes = [0]
6443 for (var i = 0; i < string.length; i++) {
6444 var value = ALPHABET_MAP[string[i]]
6445 if (value === undefined) return
6446
6447 for (var j = 0, carry = value; j < bytes.length; ++j) {
6448 carry += bytes[j] * BASE
6449 bytes[j] = carry & 0xff
6450 carry >>= 8
6451 }
6452
6453 while (carry > 0) {
6454 bytes.push(carry & 0xff)
6455 carry >>= 8
6456 }
6457 }
6458
6459 // deal with leading zeros
6460 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
6461 bytes.push(0)
6462 }
6463
6464 return Buffer.from(bytes.reverse())
6465 }
6466
6467 function decode (string) {
6468 var buffer = decodeUnsafe(string)
6469 if (buffer) return buffer
6470
6471 throw new Error('Non-base' + BASE + ' character')
6472 }
6473
6474 return {
6475 encode: encode,
6476 decodeUnsafe: decodeUnsafe,
6477 decode: decode
6478 }
6479 }
6480
6481 },{"safe-buffer":101}],36:[function(require,module,exports){
6482 'use strict'
6483 var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
6484
6485 // pre-compute lookup table
6486 var ALPHABET_MAP = {}
6487 for (var z = 0; z < ALPHABET.length; z++) {
6488 var x = ALPHABET.charAt(z)
6489
6490 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
6491 ALPHABET_MAP[x] = z
6492 }
6493
6494 function polymodStep (pre) {
6495 var b = pre >> 25
6496 return ((pre & 0x1FFFFFF) << 5) ^
6497 (-((b >> 0) & 1) & 0x3b6a57b2) ^
6498 (-((b >> 1) & 1) & 0x26508e6d) ^
6499 (-((b >> 2) & 1) & 0x1ea119fa) ^
6500 (-((b >> 3) & 1) & 0x3d4233dd) ^
6501 (-((b >> 4) & 1) & 0x2a1462b3)
6502 }
6503
6504 function prefixChk (prefix) {
6505 var chk = 1
6506 for (var i = 0; i < prefix.length; ++i) {
6507 var c = prefix.charCodeAt(i)
6508 if (c < 33 || c > 126) throw new Error('Invalid prefix (' + prefix + ')')
6509
6510 chk = polymodStep(chk) ^ (c >> 5)
6511 }
6512 chk = polymodStep(chk)
6513
6514 for (i = 0; i < prefix.length; ++i) {
6515 var v = prefix.charCodeAt(i)
6516 chk = polymodStep(chk) ^ (v & 0x1f)
6517 }
6518 return chk
6519 }
6520
6521 function encode (prefix, words, LIMIT) {
6522 LIMIT = LIMIT || 90
6523 if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit')
6524
6525 prefix = prefix.toLowerCase()
6526
6527 // determine chk mod
6528 var chk = prefixChk(prefix)
6529 var result = prefix + '1'
6530 for (var i = 0; i < words.length; ++i) {
6531 var x = words[i]
6532 if ((x >> 5) !== 0) throw new Error('Non 5-bit word')
6533
6534 chk = polymodStep(chk) ^ x
6535 result += ALPHABET.charAt(x)
6536 }
6537
6538 for (i = 0; i < 6; ++i) {
6539 chk = polymodStep(chk)
6540 }
6541 chk ^= 1
6542
6543 for (i = 0; i < 6; ++i) {
6544 var v = (chk >> ((5 - i) * 5)) & 0x1f
6545 result += ALPHABET.charAt(v)
6546 }
6547
6548 return result
6549 }
6550
6551 function decode (str, LIMIT) {
6552 LIMIT = LIMIT || 90
6553 if (str.length < 8) throw new TypeError(str + ' too short')
6554 if (str.length > LIMIT) throw new TypeError('Exceeds length limit')
6555
6556 // don't allow mixed case
6557 var lowered = str.toLowerCase()
6558 var uppered = str.toUpperCase()
6559 if (str !== lowered && str !== uppered) throw new Error('Mixed-case string ' + str)
6560 str = lowered
6561
6562 var split = str.lastIndexOf('1')
6563 if (split === -1) throw new Error('No separator character for ' + str)
6564 if (split === 0) throw new Error('Missing prefix for ' + str)
6565
6566 var prefix = str.slice(0, split)
6567 var wordChars = str.slice(split + 1)
6568 if (wordChars.length < 6) throw new Error('Data too short')
6569
6570 var chk = prefixChk(prefix)
6571 var words = []
6572 for (var i = 0; i < wordChars.length; ++i) {
6573 var c = wordChars.charAt(i)
6574 var v = ALPHABET_MAP[c]
6575 if (v === undefined) throw new Error('Unknown character ' + c)
6576 chk = polymodStep(chk) ^ v
6577
6578 // not in the checksum?
6579 if (i + 6 >= wordChars.length) continue
6580 words.push(v)
6581 }
6582
6583 if (chk !== 1) throw new Error('Invalid checksum for ' + str)
6584 return { prefix: prefix, words: words }
6585 }
6586
6587 function convert (data, inBits, outBits, pad) {
6588 var value = 0
6589 var bits = 0
6590 var maxV = (1 << outBits) - 1
6591
6592 var result = []
6593 for (var i = 0; i < data.length; ++i) {
6594 value = (value << inBits) | data[i]
6595 bits += inBits
6596
6597 while (bits >= outBits) {
6598 bits -= outBits
6599 result.push((value >> bits) & maxV)
6600 }
6601 }
6602
6603 if (pad) {
6604 if (bits > 0) {
6605 result.push((value << (outBits - bits)) & maxV)
6606 }
6607 } else {
6608 if (bits >= inBits) throw new Error('Excess padding')
6609 if ((value << (outBits - bits)) & maxV) throw new Error('Non-zero padding')
6610 }
6611
6612 return result
6613 }
6614
6615 function toWords (bytes) {
6616 return convert(bytes, 8, 5, true)
6617 }
6618
6619 function fromWords (words) {
6620 return convert(words, 5, 8, false)
6621 }
6622
6623 module.exports = {
6624 decode: decode,
6625 encode: encode,
6626 toWords: toWords,
6627 fromWords: fromWords
6628 }
6629
6630 },{}],37:[function(require,module,exports){
6631 // (public) Constructor
6632 function BigInteger(a, b, c) {
6633 if (!(this instanceof BigInteger))
6634 return new BigInteger(a, b, c)
6635
6636 if (a != null) {
6637 if ("number" == typeof a) this.fromNumber(a, b, c)
6638 else if (b == null && "string" != typeof a) this.fromString(a, 256)
6639 else this.fromString(a, b)
6640 }
6641 }
6642
6643 var proto = BigInteger.prototype
6644
6645 // duck-typed isBigInteger
6646 proto.__bigi = require('../package.json').version
6647 BigInteger.isBigInteger = function (obj, check_ver) {
6648 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
6649 }
6650
6651 // Bits per digit
6652 var dbits
6653
6654 // am: Compute w_j += (x*this_i), propagate carries,
6655 // c is initial carry, returns final carry.
6656 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
6657 // We need to select the fastest one that works in this environment.
6658
6659 // am1: use a single mult and divide to get the high bits,
6660 // max digit bits should be 26 because
6661 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
6662 function am1(i, x, w, j, c, n) {
6663 while (--n >= 0) {
6664 var v = x * this[i++] + w[j] + c
6665 c = Math.floor(v / 0x4000000)
6666 w[j++] = v & 0x3ffffff
6667 }
6668 return c
6669 }
6670 // am2 avoids a big mult-and-extract completely.
6671 // Max digit bits should be <= 30 because we do bitwise ops
6672 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
6673 function am2(i, x, w, j, c, n) {
6674 var xl = x & 0x7fff,
6675 xh = x >> 15
6676 while (--n >= 0) {
6677 var l = this[i] & 0x7fff
6678 var h = this[i++] >> 15
6679 var m = xh * l + h * xl
6680 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
6681 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
6682 w[j++] = l & 0x3fffffff
6683 }
6684 return c
6685 }
6686 // Alternately, set max digit bits to 28 since some
6687 // browsers slow down when dealing with 32-bit numbers.
6688 function am3(i, x, w, j, c, n) {
6689 var xl = x & 0x3fff,
6690 xh = x >> 14
6691 while (--n >= 0) {
6692 var l = this[i] & 0x3fff
6693 var h = this[i++] >> 14
6694 var m = xh * l + h * xl
6695 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
6696 c = (l >> 28) + (m >> 14) + xh * h
6697 w[j++] = l & 0xfffffff
6698 }
6699 return c
6700 }
6701
6702 // wtf?
6703 BigInteger.prototype.am = am1
6704 dbits = 26
6705
6706 BigInteger.prototype.DB = dbits
6707 BigInteger.prototype.DM = ((1 << dbits) - 1)
6708 var DV = BigInteger.prototype.DV = (1 << dbits)
6709
6710 var BI_FP = 52
6711 BigInteger.prototype.FV = Math.pow(2, BI_FP)
6712 BigInteger.prototype.F1 = BI_FP - dbits
6713 BigInteger.prototype.F2 = 2 * dbits - BI_FP
6714
6715 // Digit conversions
6716 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
6717 var BI_RC = new Array()
6718 var rr, vv
6719 rr = "0".charCodeAt(0)
6720 for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
6721 rr = "a".charCodeAt(0)
6722 for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6723 rr = "A".charCodeAt(0)
6724 for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6725
6726 function int2char(n) {
6727 return BI_RM.charAt(n)
6728 }
6729
6730 function intAt(s, i) {
6731 var c = BI_RC[s.charCodeAt(i)]
6732 return (c == null) ? -1 : c
6733 }
6734
6735 // (protected) copy this to r
6736 function bnpCopyTo(r) {
6737 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
6738 r.t = this.t
6739 r.s = this.s
6740 }
6741
6742 // (protected) set from integer value x, -DV <= x < DV
6743 function bnpFromInt(x) {
6744 this.t = 1
6745 this.s = (x < 0) ? -1 : 0
6746 if (x > 0) this[0] = x
6747 else if (x < -1) this[0] = x + DV
6748 else this.t = 0
6749 }
6750
6751 // return bigint initialized to value
6752 function nbv(i) {
6753 var r = new BigInteger()
6754 r.fromInt(i)
6755 return r
6756 }
6757
6758 // (protected) set from string and radix
6759 function bnpFromString(s, b) {
6760 var self = this
6761
6762 var k
6763 if (b == 16) k = 4
6764 else if (b == 8) k = 3
6765 else if (b == 256) k = 8; // byte array
6766 else if (b == 2) k = 1
6767 else if (b == 32) k = 5
6768 else if (b == 4) k = 2
6769 else {
6770 self.fromRadix(s, b)
6771 return
6772 }
6773 self.t = 0
6774 self.s = 0
6775 var i = s.length,
6776 mi = false,
6777 sh = 0
6778 while (--i >= 0) {
6779 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
6780 if (x < 0) {
6781 if (s.charAt(i) == "-") mi = true
6782 continue
6783 }
6784 mi = false
6785 if (sh == 0)
6786 self[self.t++] = x
6787 else if (sh + k > self.DB) {
6788 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
6789 self[self.t++] = (x >> (self.DB - sh))
6790 } else
6791 self[self.t - 1] |= x << sh
6792 sh += k
6793 if (sh >= self.DB) sh -= self.DB
6794 }
6795 if (k == 8 && (s[0] & 0x80) != 0) {
6796 self.s = -1
6797 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
6798 }
6799 self.clamp()
6800 if (mi) BigInteger.ZERO.subTo(self, self)
6801 }
6802
6803 // (protected) clamp off excess high words
6804 function bnpClamp() {
6805 var c = this.s & this.DM
6806 while (this.t > 0 && this[this.t - 1] == c)--this.t
6807 }
6808
6809 // (public) return string representation in given radix
6810 function bnToString(b) {
6811 var self = this
6812 if (self.s < 0) return "-" + self.negate()
6813 .toString(b)
6814 var k
6815 if (b == 16) k = 4
6816 else if (b == 8) k = 3
6817 else if (b == 2) k = 1
6818 else if (b == 32) k = 5
6819 else if (b == 4) k = 2
6820 else return self.toRadix(b)
6821 var km = (1 << k) - 1,
6822 d, m = false,
6823 r = "",
6824 i = self.t
6825 var p = self.DB - (i * self.DB) % k
6826 if (i-- > 0) {
6827 if (p < self.DB && (d = self[i] >> p) > 0) {
6828 m = true
6829 r = int2char(d)
6830 }
6831 while (i >= 0) {
6832 if (p < k) {
6833 d = (self[i] & ((1 << p) - 1)) << (k - p)
6834 d |= self[--i] >> (p += self.DB - k)
6835 } else {
6836 d = (self[i] >> (p -= k)) & km
6837 if (p <= 0) {
6838 p += self.DB
6839 --i
6840 }
6841 }
6842 if (d > 0) m = true
6843 if (m) r += int2char(d)
6844 }
6845 }
6846 return m ? r : "0"
6847 }
6848
6849 // (public) -this
6850 function bnNegate() {
6851 var r = new BigInteger()
6852 BigInteger.ZERO.subTo(this, r)
6853 return r
6854 }
6855
6856 // (public) |this|
6857 function bnAbs() {
6858 return (this.s < 0) ? this.negate() : this
6859 }
6860
6861 // (public) return + if this > a, - if this < a, 0 if equal
6862 function bnCompareTo(a) {
6863 var r = this.s - a.s
6864 if (r != 0) return r
6865 var i = this.t
6866 r = i - a.t
6867 if (r != 0) return (this.s < 0) ? -r : r
6868 while (--i >= 0)
6869 if ((r = this[i] - a[i]) != 0) return r
6870 return 0
6871 }
6872
6873 // returns bit length of the integer x
6874 function nbits(x) {
6875 var r = 1,
6876 t
6877 if ((t = x >>> 16) != 0) {
6878 x = t
6879 r += 16
6880 }
6881 if ((t = x >> 8) != 0) {
6882 x = t
6883 r += 8
6884 }
6885 if ((t = x >> 4) != 0) {
6886 x = t
6887 r += 4
6888 }
6889 if ((t = x >> 2) != 0) {
6890 x = t
6891 r += 2
6892 }
6893 if ((t = x >> 1) != 0) {
6894 x = t
6895 r += 1
6896 }
6897 return r
6898 }
6899
6900 // (public) return the number of bits in "this"
6901 function bnBitLength() {
6902 if (this.t <= 0) return 0
6903 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
6904 }
6905
6906 // (public) return the number of bytes in "this"
6907 function bnByteLength() {
6908 return this.bitLength() >> 3
6909 }
6910
6911 // (protected) r = this << n*DB
6912 function bnpDLShiftTo(n, r) {
6913 var i
6914 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
6915 for (i = n - 1; i >= 0; --i) r[i] = 0
6916 r.t = this.t + n
6917 r.s = this.s
6918 }
6919
6920 // (protected) r = this >> n*DB
6921 function bnpDRShiftTo(n, r) {
6922 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
6923 r.t = Math.max(this.t - n, 0)
6924 r.s = this.s
6925 }
6926
6927 // (protected) r = this << n
6928 function bnpLShiftTo(n, r) {
6929 var self = this
6930 var bs = n % self.DB
6931 var cbs = self.DB - bs
6932 var bm = (1 << cbs) - 1
6933 var ds = Math.floor(n / self.DB),
6934 c = (self.s << bs) & self.DM,
6935 i
6936 for (i = self.t - 1; i >= 0; --i) {
6937 r[i + ds + 1] = (self[i] >> cbs) | c
6938 c = (self[i] & bm) << bs
6939 }
6940 for (i = ds - 1; i >= 0; --i) r[i] = 0
6941 r[ds] = c
6942 r.t = self.t + ds + 1
6943 r.s = self.s
6944 r.clamp()
6945 }
6946
6947 // (protected) r = this >> n
6948 function bnpRShiftTo(n, r) {
6949 var self = this
6950 r.s = self.s
6951 var ds = Math.floor(n / self.DB)
6952 if (ds >= self.t) {
6953 r.t = 0
6954 return
6955 }
6956 var bs = n % self.DB
6957 var cbs = self.DB - bs
6958 var bm = (1 << bs) - 1
6959 r[0] = self[ds] >> bs
6960 for (var i = ds + 1; i < self.t; ++i) {
6961 r[i - ds - 1] |= (self[i] & bm) << cbs
6962 r[i - ds] = self[i] >> bs
6963 }
6964 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
6965 r.t = self.t - ds
6966 r.clamp()
6967 }
6968
6969 // (protected) r = this - a
6970 function bnpSubTo(a, r) {
6971 var self = this
6972 var i = 0,
6973 c = 0,
6974 m = Math.min(a.t, self.t)
6975 while (i < m) {
6976 c += self[i] - a[i]
6977 r[i++] = c & self.DM
6978 c >>= self.DB
6979 }
6980 if (a.t < self.t) {
6981 c -= a.s
6982 while (i < self.t) {
6983 c += self[i]
6984 r[i++] = c & self.DM
6985 c >>= self.DB
6986 }
6987 c += self.s
6988 } else {
6989 c += self.s
6990 while (i < a.t) {
6991 c -= a[i]
6992 r[i++] = c & self.DM
6993 c >>= self.DB
6994 }
6995 c -= a.s
6996 }
6997 r.s = (c < 0) ? -1 : 0
6998 if (c < -1) r[i++] = self.DV + c
6999 else if (c > 0) r[i++] = c
7000 r.t = i
7001 r.clamp()
7002 }
7003
7004 // (protected) r = this * a, r != this,a (HAC 14.12)
7005 // "this" should be the larger one if appropriate.
7006 function bnpMultiplyTo(a, r) {
7007 var x = this.abs(),
7008 y = a.abs()
7009 var i = x.t
7010 r.t = i + y.t
7011 while (--i >= 0) r[i] = 0
7012 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
7013 r.s = 0
7014 r.clamp()
7015 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
7016 }
7017
7018 // (protected) r = this^2, r != this (HAC 14.16)
7019 function bnpSquareTo(r) {
7020 var x = this.abs()
7021 var i = r.t = 2 * x.t
7022 while (--i >= 0) r[i] = 0
7023 for (i = 0; i < x.t - 1; ++i) {
7024 var c = x.am(i, x[i], r, 2 * i, 0, 1)
7025 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
7026 r[i + x.t] -= x.DV
7027 r[i + x.t + 1] = 1
7028 }
7029 }
7030 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
7031 r.s = 0
7032 r.clamp()
7033 }
7034
7035 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
7036 // r != q, this != m. q or r may be null.
7037 function bnpDivRemTo(m, q, r) {
7038 var self = this
7039 var pm = m.abs()
7040 if (pm.t <= 0) return
7041 var pt = self.abs()
7042 if (pt.t < pm.t) {
7043 if (q != null) q.fromInt(0)
7044 if (r != null) self.copyTo(r)
7045 return
7046 }
7047 if (r == null) r = new BigInteger()
7048 var y = new BigInteger(),
7049 ts = self.s,
7050 ms = m.s
7051 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
7052 if (nsh > 0) {
7053 pm.lShiftTo(nsh, y)
7054 pt.lShiftTo(nsh, r)
7055 } else {
7056 pm.copyTo(y)
7057 pt.copyTo(r)
7058 }
7059 var ys = y.t
7060 var y0 = y[ys - 1]
7061 if (y0 == 0) return
7062 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
7063 var d1 = self.FV / yt,
7064 d2 = (1 << self.F1) / yt,
7065 e = 1 << self.F2
7066 var i = r.t,
7067 j = i - ys,
7068 t = (q == null) ? new BigInteger() : q
7069 y.dlShiftTo(j, t)
7070 if (r.compareTo(t) >= 0) {
7071 r[r.t++] = 1
7072 r.subTo(t, r)
7073 }
7074 BigInteger.ONE.dlShiftTo(ys, t)
7075 t.subTo(y, y); // "negative" y so we can replace sub with am later
7076 while (y.t < ys) y[y.t++] = 0
7077 while (--j >= 0) {
7078 // Estimate quotient digit
7079 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
7080 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
7081 y.dlShiftTo(j, t)
7082 r.subTo(t, r)
7083 while (r[i] < --qd) r.subTo(t, r)
7084 }
7085 }
7086 if (q != null) {
7087 r.drShiftTo(ys, q)
7088 if (ts != ms) BigInteger.ZERO.subTo(q, q)
7089 }
7090 r.t = ys
7091 r.clamp()
7092 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
7093 if (ts < 0) BigInteger.ZERO.subTo(r, r)
7094 }
7095
7096 // (public) this mod a
7097 function bnMod(a) {
7098 var r = new BigInteger()
7099 this.abs()
7100 .divRemTo(a, null, r)
7101 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
7102 return r
7103 }
7104
7105 // Modular reduction using "classic" algorithm
7106 function Classic(m) {
7107 this.m = m
7108 }
7109
7110 function cConvert(x) {
7111 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
7112 else return x
7113 }
7114
7115 function cRevert(x) {
7116 return x
7117 }
7118
7119 function cReduce(x) {
7120 x.divRemTo(this.m, null, x)
7121 }
7122
7123 function cMulTo(x, y, r) {
7124 x.multiplyTo(y, r)
7125 this.reduce(r)
7126 }
7127
7128 function cSqrTo(x, r) {
7129 x.squareTo(r)
7130 this.reduce(r)
7131 }
7132
7133 Classic.prototype.convert = cConvert
7134 Classic.prototype.revert = cRevert
7135 Classic.prototype.reduce = cReduce
7136 Classic.prototype.mulTo = cMulTo
7137 Classic.prototype.sqrTo = cSqrTo
7138
7139 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
7140 // justification:
7141 // xy == 1 (mod m)
7142 // xy = 1+km
7143 // xy(2-xy) = (1+km)(1-km)
7144 // x[y(2-xy)] = 1-k^2m^2
7145 // x[y(2-xy)] == 1 (mod m^2)
7146 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
7147 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
7148 // JS multiply "overflows" differently from C/C++, so care is needed here.
7149 function bnpInvDigit() {
7150 if (this.t < 1) return 0
7151 var x = this[0]
7152 if ((x & 1) == 0) return 0
7153 var y = x & 3; // y == 1/x mod 2^2
7154 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
7155 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
7156 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
7157 // last step - calculate inverse mod DV directly
7158 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
7159 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
7160 // we really want the negative inverse, and -DV < y < DV
7161 return (y > 0) ? this.DV - y : -y
7162 }
7163
7164 // Montgomery reduction
7165 function Montgomery(m) {
7166 this.m = m
7167 this.mp = m.invDigit()
7168 this.mpl = this.mp & 0x7fff
7169 this.mph = this.mp >> 15
7170 this.um = (1 << (m.DB - 15)) - 1
7171 this.mt2 = 2 * m.t
7172 }
7173
7174 // xR mod m
7175 function montConvert(x) {
7176 var r = new BigInteger()
7177 x.abs()
7178 .dlShiftTo(this.m.t, r)
7179 r.divRemTo(this.m, null, r)
7180 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
7181 return r
7182 }
7183
7184 // x/R mod m
7185 function montRevert(x) {
7186 var r = new BigInteger()
7187 x.copyTo(r)
7188 this.reduce(r)
7189 return r
7190 }
7191
7192 // x = x/R mod m (HAC 14.32)
7193 function montReduce(x) {
7194 while (x.t <= this.mt2) // pad x so am has enough room later
7195 x[x.t++] = 0
7196 for (var i = 0; i < this.m.t; ++i) {
7197 // faster way of calculating u0 = x[i]*mp mod DV
7198 var j = x[i] & 0x7fff
7199 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
7200 // use am to combine the multiply-shift-add into one call
7201 j = i + this.m.t
7202 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
7203 // propagate carry
7204 while (x[j] >= x.DV) {
7205 x[j] -= x.DV
7206 x[++j]++
7207 }
7208 }
7209 x.clamp()
7210 x.drShiftTo(this.m.t, x)
7211 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
7212 }
7213
7214 // r = "x^2/R mod m"; x != r
7215 function montSqrTo(x, r) {
7216 x.squareTo(r)
7217 this.reduce(r)
7218 }
7219
7220 // r = "xy/R mod m"; x,y != r
7221 function montMulTo(x, y, r) {
7222 x.multiplyTo(y, r)
7223 this.reduce(r)
7224 }
7225
7226 Montgomery.prototype.convert = montConvert
7227 Montgomery.prototype.revert = montRevert
7228 Montgomery.prototype.reduce = montReduce
7229 Montgomery.prototype.mulTo = montMulTo
7230 Montgomery.prototype.sqrTo = montSqrTo
7231
7232 // (protected) true iff this is even
7233 function bnpIsEven() {
7234 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
7235 }
7236
7237 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
7238 function bnpExp(e, z) {
7239 if (e > 0xffffffff || e < 1) return BigInteger.ONE
7240 var r = new BigInteger(),
7241 r2 = new BigInteger(),
7242 g = z.convert(this),
7243 i = nbits(e) - 1
7244 g.copyTo(r)
7245 while (--i >= 0) {
7246 z.sqrTo(r, r2)
7247 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
7248 else {
7249 var t = r
7250 r = r2
7251 r2 = t
7252 }
7253 }
7254 return z.revert(r)
7255 }
7256
7257 // (public) this^e % m, 0 <= e < 2^32
7258 function bnModPowInt(e, m) {
7259 var z
7260 if (e < 256 || m.isEven()) z = new Classic(m)
7261 else z = new Montgomery(m)
7262 return this.exp(e, z)
7263 }
7264
7265 // protected
7266 proto.copyTo = bnpCopyTo
7267 proto.fromInt = bnpFromInt
7268 proto.fromString = bnpFromString
7269 proto.clamp = bnpClamp
7270 proto.dlShiftTo = bnpDLShiftTo
7271 proto.drShiftTo = bnpDRShiftTo
7272 proto.lShiftTo = bnpLShiftTo
7273 proto.rShiftTo = bnpRShiftTo
7274 proto.subTo = bnpSubTo
7275 proto.multiplyTo = bnpMultiplyTo
7276 proto.squareTo = bnpSquareTo
7277 proto.divRemTo = bnpDivRemTo
7278 proto.invDigit = bnpInvDigit
7279 proto.isEven = bnpIsEven
7280 proto.exp = bnpExp
7281
7282 // public
7283 proto.toString = bnToString
7284 proto.negate = bnNegate
7285 proto.abs = bnAbs
7286 proto.compareTo = bnCompareTo
7287 proto.bitLength = bnBitLength
7288 proto.byteLength = bnByteLength
7289 proto.mod = bnMod
7290 proto.modPowInt = bnModPowInt
7291
7292 // (public)
7293 function bnClone() {
7294 var r = new BigInteger()
7295 this.copyTo(r)
7296 return r
7297 }
7298
7299 // (public) return value as integer
7300 function bnIntValue() {
7301 if (this.s < 0) {
7302 if (this.t == 1) return this[0] - this.DV
7303 else if (this.t == 0) return -1
7304 } else if (this.t == 1) return this[0]
7305 else if (this.t == 0) return 0
7306 // assumes 16 < DB < 32
7307 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
7308 }
7309
7310 // (public) return value as byte
7311 function bnByteValue() {
7312 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
7313 }
7314
7315 // (public) return value as short (assumes DB>=16)
7316 function bnShortValue() {
7317 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
7318 }
7319
7320 // (protected) return x s.t. r^x < DV
7321 function bnpChunkSize(r) {
7322 return Math.floor(Math.LN2 * this.DB / Math.log(r))
7323 }
7324
7325 // (public) 0 if this == 0, 1 if this > 0
7326 function bnSigNum() {
7327 if (this.s < 0) return -1
7328 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
7329 else return 1
7330 }
7331
7332 // (protected) convert to radix string
7333 function bnpToRadix(b) {
7334 if (b == null) b = 10
7335 if (this.signum() == 0 || b < 2 || b > 36) return "0"
7336 var cs = this.chunkSize(b)
7337 var a = Math.pow(b, cs)
7338 var d = nbv(a),
7339 y = new BigInteger(),
7340 z = new BigInteger(),
7341 r = ""
7342 this.divRemTo(d, y, z)
7343 while (y.signum() > 0) {
7344 r = (a + z.intValue())
7345 .toString(b)
7346 .substr(1) + r
7347 y.divRemTo(d, y, z)
7348 }
7349 return z.intValue()
7350 .toString(b) + r
7351 }
7352
7353 // (protected) convert from radix string
7354 function bnpFromRadix(s, b) {
7355 var self = this
7356 self.fromInt(0)
7357 if (b == null) b = 10
7358 var cs = self.chunkSize(b)
7359 var d = Math.pow(b, cs),
7360 mi = false,
7361 j = 0,
7362 w = 0
7363 for (var i = 0; i < s.length; ++i) {
7364 var x = intAt(s, i)
7365 if (x < 0) {
7366 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
7367 continue
7368 }
7369 w = b * w + x
7370 if (++j >= cs) {
7371 self.dMultiply(d)
7372 self.dAddOffset(w, 0)
7373 j = 0
7374 w = 0
7375 }
7376 }
7377 if (j > 0) {
7378 self.dMultiply(Math.pow(b, j))
7379 self.dAddOffset(w, 0)
7380 }
7381 if (mi) BigInteger.ZERO.subTo(self, self)
7382 }
7383
7384 // (protected) alternate constructor
7385 function bnpFromNumber(a, b, c) {
7386 var self = this
7387 if ("number" == typeof b) {
7388 // new BigInteger(int,int,RNG)
7389 if (a < 2) self.fromInt(1)
7390 else {
7391 self.fromNumber(a, c)
7392 if (!self.testBit(a - 1)) // force MSB set
7393 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
7394 if (self.isEven()) self.dAddOffset(1, 0); // force odd
7395 while (!self.isProbablePrime(b)) {
7396 self.dAddOffset(2, 0)
7397 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
7398 }
7399 }
7400 } else {
7401 // new BigInteger(int,RNG)
7402 var x = new Array(),
7403 t = a & 7
7404 x.length = (a >> 3) + 1
7405 b.nextBytes(x)
7406 if (t > 0) x[0] &= ((1 << t) - 1)
7407 else x[0] = 0
7408 self.fromString(x, 256)
7409 }
7410 }
7411
7412 // (public) convert to bigendian byte array
7413 function bnToByteArray() {
7414 var self = this
7415 var i = self.t,
7416 r = new Array()
7417 r[0] = self.s
7418 var p = self.DB - (i * self.DB) % 8,
7419 d, k = 0
7420 if (i-- > 0) {
7421 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
7422 r[k++] = d | (self.s << (self.DB - p))
7423 while (i >= 0) {
7424 if (p < 8) {
7425 d = (self[i] & ((1 << p) - 1)) << (8 - p)
7426 d |= self[--i] >> (p += self.DB - 8)
7427 } else {
7428 d = (self[i] >> (p -= 8)) & 0xff
7429 if (p <= 0) {
7430 p += self.DB
7431 --i
7432 }
7433 }
7434 if ((d & 0x80) != 0) d |= -256
7435 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
7436 if (k > 0 || d != self.s) r[k++] = d
7437 }
7438 }
7439 return r
7440 }
7441
7442 function bnEquals(a) {
7443 return (this.compareTo(a) == 0)
7444 }
7445
7446 function bnMin(a) {
7447 return (this.compareTo(a) < 0) ? this : a
7448 }
7449
7450 function bnMax(a) {
7451 return (this.compareTo(a) > 0) ? this : a
7452 }
7453
7454 // (protected) r = this op a (bitwise)
7455 function bnpBitwiseTo(a, op, r) {
7456 var self = this
7457 var i, f, m = Math.min(a.t, self.t)
7458 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
7459 if (a.t < self.t) {
7460 f = a.s & self.DM
7461 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
7462 r.t = self.t
7463 } else {
7464 f = self.s & self.DM
7465 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
7466 r.t = a.t
7467 }
7468 r.s = op(self.s, a.s)
7469 r.clamp()
7470 }
7471
7472 // (public) this & a
7473 function op_and(x, y) {
7474 return x & y
7475 }
7476
7477 function bnAnd(a) {
7478 var r = new BigInteger()
7479 this.bitwiseTo(a, op_and, r)
7480 return r
7481 }
7482
7483 // (public) this | a
7484 function op_or(x, y) {
7485 return x | y
7486 }
7487
7488 function bnOr(a) {
7489 var r = new BigInteger()
7490 this.bitwiseTo(a, op_or, r)
7491 return r
7492 }
7493
7494 // (public) this ^ a
7495 function op_xor(x, y) {
7496 return x ^ y
7497 }
7498
7499 function bnXor(a) {
7500 var r = new BigInteger()
7501 this.bitwiseTo(a, op_xor, r)
7502 return r
7503 }
7504
7505 // (public) this & ~a
7506 function op_andnot(x, y) {
7507 return x & ~y
7508 }
7509
7510 function bnAndNot(a) {
7511 var r = new BigInteger()
7512 this.bitwiseTo(a, op_andnot, r)
7513 return r
7514 }
7515
7516 // (public) ~this
7517 function bnNot() {
7518 var r = new BigInteger()
7519 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
7520 r.t = this.t
7521 r.s = ~this.s
7522 return r
7523 }
7524
7525 // (public) this << n
7526 function bnShiftLeft(n) {
7527 var r = new BigInteger()
7528 if (n < 0) this.rShiftTo(-n, r)
7529 else this.lShiftTo(n, r)
7530 return r
7531 }
7532
7533 // (public) this >> n
7534 function bnShiftRight(n) {
7535 var r = new BigInteger()
7536 if (n < 0) this.lShiftTo(-n, r)
7537 else this.rShiftTo(n, r)
7538 return r
7539 }
7540
7541 // return index of lowest 1-bit in x, x < 2^31
7542 function lbit(x) {
7543 if (x == 0) return -1
7544 var r = 0
7545 if ((x & 0xffff) == 0) {
7546 x >>= 16
7547 r += 16
7548 }
7549 if ((x & 0xff) == 0) {
7550 x >>= 8
7551 r += 8
7552 }
7553 if ((x & 0xf) == 0) {
7554 x >>= 4
7555 r += 4
7556 }
7557 if ((x & 3) == 0) {
7558 x >>= 2
7559 r += 2
7560 }
7561 if ((x & 1) == 0)++r
7562 return r
7563 }
7564
7565 // (public) returns index of lowest 1-bit (or -1 if none)
7566 function bnGetLowestSetBit() {
7567 for (var i = 0; i < this.t; ++i)
7568 if (this[i] != 0) return i * this.DB + lbit(this[i])
7569 if (this.s < 0) return this.t * this.DB
7570 return -1
7571 }
7572
7573 // return number of 1 bits in x
7574 function cbit(x) {
7575 var r = 0
7576 while (x != 0) {
7577 x &= x - 1
7578 ++r
7579 }
7580 return r
7581 }
7582
7583 // (public) return number of set bits
7584 function bnBitCount() {
7585 var r = 0,
7586 x = this.s & this.DM
7587 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
7588 return r
7589 }
7590
7591 // (public) true iff nth bit is set
7592 function bnTestBit(n) {
7593 var j = Math.floor(n / this.DB)
7594 if (j >= this.t) return (this.s != 0)
7595 return ((this[j] & (1 << (n % this.DB))) != 0)
7596 }
7597
7598 // (protected) this op (1<<n)
7599 function bnpChangeBit(n, op) {
7600 var r = BigInteger.ONE.shiftLeft(n)
7601 this.bitwiseTo(r, op, r)
7602 return r
7603 }
7604
7605 // (public) this | (1<<n)
7606 function bnSetBit(n) {
7607 return this.changeBit(n, op_or)
7608 }
7609
7610 // (public) this & ~(1<<n)
7611 function bnClearBit(n) {
7612 return this.changeBit(n, op_andnot)
7613 }
7614
7615 // (public) this ^ (1<<n)
7616 function bnFlipBit(n) {
7617 return this.changeBit(n, op_xor)
7618 }
7619
7620 // (protected) r = this + a
7621 function bnpAddTo(a, r) {
7622 var self = this
7623
7624 var i = 0,
7625 c = 0,
7626 m = Math.min(a.t, self.t)
7627 while (i < m) {
7628 c += self[i] + a[i]
7629 r[i++] = c & self.DM
7630 c >>= self.DB
7631 }
7632 if (a.t < self.t) {
7633 c += a.s
7634 while (i < self.t) {
7635 c += self[i]
7636 r[i++] = c & self.DM
7637 c >>= self.DB
7638 }
7639 c += self.s
7640 } else {
7641 c += self.s
7642 while (i < a.t) {
7643 c += a[i]
7644 r[i++] = c & self.DM
7645 c >>= self.DB
7646 }
7647 c += a.s
7648 }
7649 r.s = (c < 0) ? -1 : 0
7650 if (c > 0) r[i++] = c
7651 else if (c < -1) r[i++] = self.DV + c
7652 r.t = i
7653 r.clamp()
7654 }
7655
7656 // (public) this + a
7657 function bnAdd(a) {
7658 var r = new BigInteger()
7659 this.addTo(a, r)
7660 return r
7661 }
7662
7663 // (public) this - a
7664 function bnSubtract(a) {
7665 var r = new BigInteger()
7666 this.subTo(a, r)
7667 return r
7668 }
7669
7670 // (public) this * a
7671 function bnMultiply(a) {
7672 var r = new BigInteger()
7673 this.multiplyTo(a, r)
7674 return r
7675 }
7676
7677 // (public) this^2
7678 function bnSquare() {
7679 var r = new BigInteger()
7680 this.squareTo(r)
7681 return r
7682 }
7683
7684 // (public) this / a
7685 function bnDivide(a) {
7686 var r = new BigInteger()
7687 this.divRemTo(a, r, null)
7688 return r
7689 }
7690
7691 // (public) this % a
7692 function bnRemainder(a) {
7693 var r = new BigInteger()
7694 this.divRemTo(a, null, r)
7695 return r
7696 }
7697
7698 // (public) [this/a,this%a]
7699 function bnDivideAndRemainder(a) {
7700 var q = new BigInteger(),
7701 r = new BigInteger()
7702 this.divRemTo(a, q, r)
7703 return new Array(q, r)
7704 }
7705
7706 // (protected) this *= n, this >= 0, 1 < n < DV
7707 function bnpDMultiply(n) {
7708 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
7709 ++this.t
7710 this.clamp()
7711 }
7712
7713 // (protected) this += n << w words, this >= 0
7714 function bnpDAddOffset(n, w) {
7715 if (n == 0) return
7716 while (this.t <= w) this[this.t++] = 0
7717 this[w] += n
7718 while (this[w] >= this.DV) {
7719 this[w] -= this.DV
7720 if (++w >= this.t) this[this.t++] = 0
7721 ++this[w]
7722 }
7723 }
7724
7725 // A "null" reducer
7726 function NullExp() {}
7727
7728 function nNop(x) {
7729 return x
7730 }
7731
7732 function nMulTo(x, y, r) {
7733 x.multiplyTo(y, r)
7734 }
7735
7736 function nSqrTo(x, r) {
7737 x.squareTo(r)
7738 }
7739
7740 NullExp.prototype.convert = nNop
7741 NullExp.prototype.revert = nNop
7742 NullExp.prototype.mulTo = nMulTo
7743 NullExp.prototype.sqrTo = nSqrTo
7744
7745 // (public) this^e
7746 function bnPow(e) {
7747 return this.exp(e, new NullExp())
7748 }
7749
7750 // (protected) r = lower n words of "this * a", a.t <= n
7751 // "this" should be the larger one if appropriate.
7752 function bnpMultiplyLowerTo(a, n, r) {
7753 var i = Math.min(this.t + a.t, n)
7754 r.s = 0; // assumes a,this >= 0
7755 r.t = i
7756 while (i > 0) r[--i] = 0
7757 var j
7758 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
7759 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
7760 r.clamp()
7761 }
7762
7763 // (protected) r = "this * a" without lower n words, n > 0
7764 // "this" should be the larger one if appropriate.
7765 function bnpMultiplyUpperTo(a, n, r) {
7766 --n
7767 var i = r.t = this.t + a.t - n
7768 r.s = 0; // assumes a,this >= 0
7769 while (--i >= 0) r[i] = 0
7770 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
7771 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
7772 r.clamp()
7773 r.drShiftTo(1, r)
7774 }
7775
7776 // Barrett modular reduction
7777 function Barrett(m) {
7778 // setup Barrett
7779 this.r2 = new BigInteger()
7780 this.q3 = new BigInteger()
7781 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
7782 this.mu = this.r2.divide(m)
7783 this.m = m
7784 }
7785
7786 function barrettConvert(x) {
7787 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
7788 else if (x.compareTo(this.m) < 0) return x
7789 else {
7790 var r = new BigInteger()
7791 x.copyTo(r)
7792 this.reduce(r)
7793 return r
7794 }
7795 }
7796
7797 function barrettRevert(x) {
7798 return x
7799 }
7800
7801 // x = x mod m (HAC 14.42)
7802 function barrettReduce(x) {
7803 var self = this
7804 x.drShiftTo(self.m.t - 1, self.r2)
7805 if (x.t > self.m.t + 1) {
7806 x.t = self.m.t + 1
7807 x.clamp()
7808 }
7809 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
7810 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
7811 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
7812 x.subTo(self.r2, x)
7813 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
7814 }
7815
7816 // r = x^2 mod m; x != r
7817 function barrettSqrTo(x, r) {
7818 x.squareTo(r)
7819 this.reduce(r)
7820 }
7821
7822 // r = x*y mod m; x,y != r
7823 function barrettMulTo(x, y, r) {
7824 x.multiplyTo(y, r)
7825 this.reduce(r)
7826 }
7827
7828 Barrett.prototype.convert = barrettConvert
7829 Barrett.prototype.revert = barrettRevert
7830 Barrett.prototype.reduce = barrettReduce
7831 Barrett.prototype.mulTo = barrettMulTo
7832 Barrett.prototype.sqrTo = barrettSqrTo
7833
7834 // (public) this^e % m (HAC 14.85)
7835 function bnModPow(e, m) {
7836 var i = e.bitLength(),
7837 k, r = nbv(1),
7838 z
7839 if (i <= 0) return r
7840 else if (i < 18) k = 1
7841 else if (i < 48) k = 3
7842 else if (i < 144) k = 4
7843 else if (i < 768) k = 5
7844 else k = 6
7845 if (i < 8)
7846 z = new Classic(m)
7847 else if (m.isEven())
7848 z = new Barrett(m)
7849 else
7850 z = new Montgomery(m)
7851
7852 // precomputation
7853 var g = new Array(),
7854 n = 3,
7855 k1 = k - 1,
7856 km = (1 << k) - 1
7857 g[1] = z.convert(this)
7858 if (k > 1) {
7859 var g2 = new BigInteger()
7860 z.sqrTo(g[1], g2)
7861 while (n <= km) {
7862 g[n] = new BigInteger()
7863 z.mulTo(g2, g[n - 2], g[n])
7864 n += 2
7865 }
7866 }
7867
7868 var j = e.t - 1,
7869 w, is1 = true,
7870 r2 = new BigInteger(),
7871 t
7872 i = nbits(e[j]) - 1
7873 while (j >= 0) {
7874 if (i >= k1) w = (e[j] >> (i - k1)) & km
7875 else {
7876 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
7877 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
7878 }
7879
7880 n = k
7881 while ((w & 1) == 0) {
7882 w >>= 1
7883 --n
7884 }
7885 if ((i -= n) < 0) {
7886 i += this.DB
7887 --j
7888 }
7889 if (is1) { // ret == 1, don't bother squaring or multiplying it
7890 g[w].copyTo(r)
7891 is1 = false
7892 } else {
7893 while (n > 1) {
7894 z.sqrTo(r, r2)
7895 z.sqrTo(r2, r)
7896 n -= 2
7897 }
7898 if (n > 0) z.sqrTo(r, r2)
7899 else {
7900 t = r
7901 r = r2
7902 r2 = t
7903 }
7904 z.mulTo(r2, g[w], r)
7905 }
7906
7907 while (j >= 0 && (e[j] & (1 << i)) == 0) {
7908 z.sqrTo(r, r2)
7909 t = r
7910 r = r2
7911 r2 = t
7912 if (--i < 0) {
7913 i = this.DB - 1
7914 --j
7915 }
7916 }
7917 }
7918 return z.revert(r)
7919 }
7920
7921 // (public) gcd(this,a) (HAC 14.54)
7922 function bnGCD(a) {
7923 var x = (this.s < 0) ? this.negate() : this.clone()
7924 var y = (a.s < 0) ? a.negate() : a.clone()
7925 if (x.compareTo(y) < 0) {
7926 var t = x
7927 x = y
7928 y = t
7929 }
7930 var i = x.getLowestSetBit(),
7931 g = y.getLowestSetBit()
7932 if (g < 0) return x
7933 if (i < g) g = i
7934 if (g > 0) {
7935 x.rShiftTo(g, x)
7936 y.rShiftTo(g, y)
7937 }
7938 while (x.signum() > 0) {
7939 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
7940 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
7941 if (x.compareTo(y) >= 0) {
7942 x.subTo(y, x)
7943 x.rShiftTo(1, x)
7944 } else {
7945 y.subTo(x, y)
7946 y.rShiftTo(1, y)
7947 }
7948 }
7949 if (g > 0) y.lShiftTo(g, y)
7950 return y
7951 }
7952
7953 // (protected) this % n, n < 2^26
7954 function bnpModInt(n) {
7955 if (n <= 0) return 0
7956 var d = this.DV % n,
7957 r = (this.s < 0) ? n - 1 : 0
7958 if (this.t > 0)
7959 if (d == 0) r = this[0] % n
7960 else
7961 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
7962 return r
7963 }
7964
7965 // (public) 1/this % m (HAC 14.61)
7966 function bnModInverse(m) {
7967 var ac = m.isEven()
7968 if (this.signum() === 0) throw new Error('division by zero')
7969 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
7970 var u = m.clone(),
7971 v = this.clone()
7972 var a = nbv(1),
7973 b = nbv(0),
7974 c = nbv(0),
7975 d = nbv(1)
7976 while (u.signum() != 0) {
7977 while (u.isEven()) {
7978 u.rShiftTo(1, u)
7979 if (ac) {
7980 if (!a.isEven() || !b.isEven()) {
7981 a.addTo(this, a)
7982 b.subTo(m, b)
7983 }
7984 a.rShiftTo(1, a)
7985 } else if (!b.isEven()) b.subTo(m, b)
7986 b.rShiftTo(1, b)
7987 }
7988 while (v.isEven()) {
7989 v.rShiftTo(1, v)
7990 if (ac) {
7991 if (!c.isEven() || !d.isEven()) {
7992 c.addTo(this, c)
7993 d.subTo(m, d)
7994 }
7995 c.rShiftTo(1, c)
7996 } else if (!d.isEven()) d.subTo(m, d)
7997 d.rShiftTo(1, d)
7998 }
7999 if (u.compareTo(v) >= 0) {
8000 u.subTo(v, u)
8001 if (ac) a.subTo(c, a)
8002 b.subTo(d, b)
8003 } else {
8004 v.subTo(u, v)
8005 if (ac) c.subTo(a, c)
8006 d.subTo(b, d)
8007 }
8008 }
8009 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
8010 while (d.compareTo(m) >= 0) d.subTo(m, d)
8011 while (d.signum() < 0) d.addTo(m, d)
8012 return d
8013 }
8014
8015 var lowprimes = [
8016 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
8017 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
8018 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
8019 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
8020 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
8021 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
8022 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
8023 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
8024 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
8025 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
8026 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
8027 ]
8028
8029 var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
8030
8031 // (public) test primality with certainty >= 1-.5^t
8032 function bnIsProbablePrime(t) {
8033 var i, x = this.abs()
8034 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
8035 for (i = 0; i < lowprimes.length; ++i)
8036 if (x[0] == lowprimes[i]) return true
8037 return false
8038 }
8039 if (x.isEven()) return false
8040 i = 1
8041 while (i < lowprimes.length) {
8042 var m = lowprimes[i],
8043 j = i + 1
8044 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
8045 m = x.modInt(m)
8046 while (i < j) if (m % lowprimes[i++] == 0) return false
8047 }
8048 return x.millerRabin(t)
8049 }
8050
8051 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
8052 function bnpMillerRabin(t) {
8053 var n1 = this.subtract(BigInteger.ONE)
8054 var k = n1.getLowestSetBit()
8055 if (k <= 0) return false
8056 var r = n1.shiftRight(k)
8057 t = (t + 1) >> 1
8058 if (t > lowprimes.length) t = lowprimes.length
8059 var a = new BigInteger(null)
8060 var j, bases = []
8061 for (var i = 0; i < t; ++i) {
8062 for (;;) {
8063 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
8064 if (bases.indexOf(j) == -1) break
8065 }
8066 bases.push(j)
8067 a.fromInt(j)
8068 var y = a.modPow(r, this)
8069 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
8070 var j = 1
8071 while (j++ < k && y.compareTo(n1) != 0) {
8072 y = y.modPowInt(2, this)
8073 if (y.compareTo(BigInteger.ONE) == 0) return false
8074 }
8075 if (y.compareTo(n1) != 0) return false
8076 }
8077 }
8078 return true
8079 }
8080
8081 // protected
8082 proto.chunkSize = bnpChunkSize
8083 proto.toRadix = bnpToRadix
8084 proto.fromRadix = bnpFromRadix
8085 proto.fromNumber = bnpFromNumber
8086 proto.bitwiseTo = bnpBitwiseTo
8087 proto.changeBit = bnpChangeBit
8088 proto.addTo = bnpAddTo
8089 proto.dMultiply = bnpDMultiply
8090 proto.dAddOffset = bnpDAddOffset
8091 proto.multiplyLowerTo = bnpMultiplyLowerTo
8092 proto.multiplyUpperTo = bnpMultiplyUpperTo
8093 proto.modInt = bnpModInt
8094 proto.millerRabin = bnpMillerRabin
8095
8096 // public
8097 proto.clone = bnClone
8098 proto.intValue = bnIntValue
8099 proto.byteValue = bnByteValue
8100 proto.shortValue = bnShortValue
8101 proto.signum = bnSigNum
8102 proto.toByteArray = bnToByteArray
8103 proto.equals = bnEquals
8104 proto.min = bnMin
8105 proto.max = bnMax
8106 proto.and = bnAnd
8107 proto.or = bnOr
8108 proto.xor = bnXor
8109 proto.andNot = bnAndNot
8110 proto.not = bnNot
8111 proto.shiftLeft = bnShiftLeft
8112 proto.shiftRight = bnShiftRight
8113 proto.getLowestSetBit = bnGetLowestSetBit
8114 proto.bitCount = bnBitCount
8115 proto.testBit = bnTestBit
8116 proto.setBit = bnSetBit
8117 proto.clearBit = bnClearBit
8118 proto.flipBit = bnFlipBit
8119 proto.add = bnAdd
8120 proto.subtract = bnSubtract
8121 proto.multiply = bnMultiply
8122 proto.divide = bnDivide
8123 proto.remainder = bnRemainder
8124 proto.divideAndRemainder = bnDivideAndRemainder
8125 proto.modPow = bnModPow
8126 proto.modInverse = bnModInverse
8127 proto.pow = bnPow
8128 proto.gcd = bnGCD
8129 proto.isProbablePrime = bnIsProbablePrime
8130
8131 // JSBN-specific extension
8132 proto.square = bnSquare
8133
8134 // constants
8135 BigInteger.ZERO = nbv(0)
8136 BigInteger.ONE = nbv(1)
8137 BigInteger.valueOf = nbv
8138
8139 module.exports = BigInteger
8140
8141 },{"../package.json":40}],38:[function(require,module,exports){
8142 (function (Buffer){
8143 // FIXME: Kind of a weird way to throw exceptions, consider removing
8144 var assert = require('assert')
8145 var BigInteger = require('./bigi')
8146
8147 /**
8148 * Turns a byte array into a big integer.
8149 *
8150 * This function will interpret a byte array as a big integer in big
8151 * endian notation.
8152 */
8153 BigInteger.fromByteArrayUnsigned = function(byteArray) {
8154 // BigInteger expects a DER integer conformant byte array
8155 if (byteArray[0] & 0x80) {
8156 return new BigInteger([0].concat(byteArray))
8157 }
8158
8159 return new BigInteger(byteArray)
8160 }
8161
8162 /**
8163 * Returns a byte array representation of the big integer.
8164 *
8165 * This returns the absolute of the contained value in big endian
8166 * form. A value of zero results in an empty array.
8167 */
8168 BigInteger.prototype.toByteArrayUnsigned = function() {
8169 var byteArray = this.toByteArray()
8170 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
8171 }
8172
8173 BigInteger.fromDERInteger = function(byteArray) {
8174 return new BigInteger(byteArray)
8175 }
8176
8177 /*
8178 * Converts BigInteger to a DER integer representation.
8179 *
8180 * The format for this value uses the most significant bit as a sign
8181 * bit. If the most significant bit is already set and the integer is
8182 * positive, a 0x00 is prepended.
8183 *
8184 * Examples:
8185 *
8186 * 0 => 0x00
8187 * 1 => 0x01
8188 * -1 => 0xff
8189 * 127 => 0x7f
8190 * -127 => 0x81
8191 * 128 => 0x0080
8192 * -128 => 0x80
8193 * 255 => 0x00ff
8194 * -255 => 0xff01
8195 * 16300 => 0x3fac
8196 * -16300 => 0xc054
8197 * 62300 => 0x00f35c
8198 * -62300 => 0xff0ca4
8199 */
8200 BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
8201
8202 BigInteger.fromBuffer = function(buffer) {
8203 // BigInteger expects a DER integer conformant byte array
8204 if (buffer[0] & 0x80) {
8205 var byteArray = Array.prototype.slice.call(buffer)
8206
8207 return new BigInteger([0].concat(byteArray))
8208 }
8209
8210 return new BigInteger(buffer)
8211 }
8212
8213 BigInteger.fromHex = function(hex) {
8214 if (hex === '') return BigInteger.ZERO
8215
8216 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
8217 assert.equal(hex.length % 2, 0, 'Incomplete hex')
8218 return new BigInteger(hex, 16)
8219 }
8220
8221 BigInteger.prototype.toBuffer = function(size) {
8222 var byteArray = this.toByteArrayUnsigned()
8223 var zeros = []
8224
8225 var padding = size - byteArray.length
8226 while (zeros.length < padding) zeros.push(0)
8227
8228 return new Buffer(zeros.concat(byteArray))
8229 }
8230
8231 BigInteger.prototype.toHex = function(size) {
8232 return this.toBuffer(size).toString('hex')
8233 }
8234
8235 }).call(this,require("buffer").Buffer)
8236 },{"./bigi":37,"assert":1,"buffer":5}],39:[function(require,module,exports){
8237 var BigInteger = require('./bigi')
8238
8239 //addons
8240 require('./convert')
8241
8242 module.exports = BigInteger
8243 },{"./bigi":37,"./convert":38}],40:[function(require,module,exports){
8244 module.exports={
8245 "_args": [
8246 [
8247 "bigi@^1.4.0",
8248 "/home/ian/git/bitcoin/bitcoinjs-lib-browser/node_modules/bitcoinjs-lib"
8249 ]
8250 ],
8251 "_from": "bigi@>=1.4.0 <2.0.0",
8252 "_id": "bigi@1.4.2",
8253 "_inCache": true,
8254 "_installable": true,
8255 "_location": "/bigi",
8256 "_nodeVersion": "6.1.0",
8257 "_npmOperationalInternal": {
8258 "host": "packages-12-west.internal.npmjs.com",
8259 "tmp": "tmp/bigi-1.4.2.tgz_1469584192413_0.6801238611806184"
8260 },
8261 "_npmUser": {
8262 "email": "jprichardson@gmail.com",
8263 "name": "jprichardson"
8264 },
8265 "_npmVersion": "3.8.6",
8266 "_phantomChildren": {},
8267 "_requested": {
8268 "name": "bigi",
8269 "raw": "bigi@^1.4.0",
8270 "rawSpec": "^1.4.0",
8271 "scope": null,
8272 "spec": ">=1.4.0 <2.0.0",
8273 "type": "range"
8274 },
8275 "_requiredBy": [
8276 "/bitcoinjs-lib",
8277 "/ecurve"
8278 ],
8279 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
8280 "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
8281 "_shrinkwrap": null,
8282 "_spec": "bigi@^1.4.0",
8283 "_where": "/home/ian/git/bitcoin/bitcoinjs-lib-browser/node_modules/bitcoinjs-lib",
8284 "bugs": {
8285 "url": "https://github.com/cryptocoinjs/bigi/issues"
8286 },
8287 "dependencies": {},
8288 "description": "Big integers.",
8289 "devDependencies": {
8290 "coveralls": "^2.11.2",
8291 "istanbul": "^0.3.5",
8292 "jshint": "^2.5.1",
8293 "mocha": "^2.1.0",
8294 "mochify": "^2.1.0"
8295 },
8296 "directories": {},
8297 "dist": {
8298 "shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
8299 "tarball": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz"
8300 },
8301 "gitHead": "c25308081c896ff84702303722bf5ecd8b3f78e3",
8302 "homepage": "https://github.com/cryptocoinjs/bigi#readme",
8303 "keywords": [
8304 "cryptography",
8305 "math",
8306 "bitcoin",
8307 "arbitrary",
8308 "precision",
8309 "arithmetic",
8310 "big",
8311 "integer",
8312 "int",
8313 "number",
8314 "biginteger",
8315 "bigint",
8316 "bignumber",
8317 "decimal",
8318 "float"
8319 ],
8320 "main": "./lib/index.js",
8321 "maintainers": [
8322 {
8323 "email": "boydb@midnightdesign.ws",
8324 "name": "midnightlightning"
8325 },
8326 {
8327 "email": "sidazhang89@gmail.com",
8328 "name": "sidazhang"
8329 },
8330 {
8331 "email": "npm@shesek.info",
8332 "name": "nadav"
8333 },
8334 {
8335 "email": "jprichardson@gmail.com",
8336 "name": "jprichardson"
8337 }
8338 ],
8339 "name": "bigi",
8340 "optionalDependencies": {},
8341 "readme": "ERROR: No README data found!",
8342 "repository": {
8343 "type": "git",
8344 "url": "git+https://github.com/cryptocoinjs/bigi.git"
8345 },
8346 "scripts": {
8347 "browser-test": "mochify --wd -R spec",
8348 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
8349 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info",
8350 "jshint": "jshint --config jshint.json lib/*.js ; true",
8351 "test": "_mocha -- test/*.js",
8352 "unit": "mocha"
8353 },
8354 "testling": {
8355 "browsers": [
8356 "ie/9..latest",
8357 "firefox/latest",
8358 "chrome/latest",
8359 "safari/6.0..latest",
8360 "iphone/6.0..latest",
8361 "android-browser/4.2..latest"
8362 ],
8363 "files": "test/*.js",
8364 "harness": "mocha"
8365 },
8366 "version": "1.4.2"
8367 }
8368
8369 },{}],41:[function(require,module,exports){
8370 // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
8371 // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
8372 // NOTE: SIGHASH byte ignored AND restricted, truncate before use
8373
8374 var Buffer = require('safe-buffer').Buffer
8375
8376 function check (buffer) {
8377 if (buffer.length < 8) return false
8378 if (buffer.length > 72) return false
8379 if (buffer[0] !== 0x30) return false
8380 if (buffer[1] !== buffer.length - 2) return false
8381 if (buffer[2] !== 0x02) return false
8382
8383 var lenR = buffer[3]
8384 if (lenR === 0) return false
8385 if (5 + lenR >= buffer.length) return false
8386 if (buffer[4 + lenR] !== 0x02) return false
8387
8388 var lenS = buffer[5 + lenR]
8389 if (lenS === 0) return false
8390 if ((6 + lenR + lenS) !== buffer.length) return false
8391
8392 if (buffer[4] & 0x80) return false
8393 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false
8394
8395 if (buffer[lenR + 6] & 0x80) return false
8396 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false
8397 return true
8398 }
8399
8400 function decode (buffer) {
8401 if (buffer.length < 8) throw new Error('DER sequence length is too short')
8402 if (buffer.length > 72) throw new Error('DER sequence length is too long')
8403 if (buffer[0] !== 0x30) throw new Error('Expected DER sequence')
8404 if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid')
8405 if (buffer[2] !== 0x02) throw new Error('Expected DER integer')
8406
8407 var lenR = buffer[3]
8408 if (lenR === 0) throw new Error('R length is zero')
8409 if (5 + lenR >= buffer.length) throw new Error('R length is too long')
8410 if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)')
8411
8412 var lenS = buffer[5 + lenR]
8413 if (lenS === 0) throw new Error('S length is zero')
8414 if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid')
8415
8416 if (buffer[4] & 0x80) throw new Error('R value is negative')
8417 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded')
8418
8419 if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative')
8420 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded')
8421
8422 // non-BIP66 - extract R, S values
8423 return {
8424 r: buffer.slice(4, 4 + lenR),
8425 s: buffer.slice(6 + lenR)
8426 }
8427 }
8428
8429 /*
8430 * Expects r and s to be positive DER integers.
8431 *
8432 * The DER format uses the most significant bit as a sign bit (& 0x80).
8433 * If the significant bit is set AND the integer is positive, a 0x00 is prepended.
8434 *
8435 * Examples:
8436 *
8437 * 0 => 0x00
8438 * 1 => 0x01
8439 * -1 => 0xff
8440 * 127 => 0x7f
8441 * -127 => 0x81
8442 * 128 => 0x0080
8443 * -128 => 0x80
8444 * 255 => 0x00ff
8445 * -255 => 0xff01
8446 * 16300 => 0x3fac
8447 * -16300 => 0xc054
8448 * 62300 => 0x00f35c
8449 * -62300 => 0xff0ca4
8450 */
8451 function encode (r, s) {
8452 var lenR = r.length
8453 var lenS = s.length
8454 if (lenR === 0) throw new Error('R length is zero')
8455 if (lenS === 0) throw new Error('S length is zero')
8456 if (lenR > 33) throw new Error('R length is too long')
8457 if (lenS > 33) throw new Error('S length is too long')
8458 if (r[0] & 0x80) throw new Error('R value is negative')
8459 if (s[0] & 0x80) throw new Error('S value is negative')
8460 if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded')
8461 if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded')
8462
8463 var signature = Buffer.allocUnsafe(6 + lenR + lenS)
8464
8465 // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
8466 signature[0] = 0x30
8467 signature[1] = signature.length - 2
8468 signature[2] = 0x02
8469 signature[3] = r.length
8470 r.copy(signature, 4)
8471 signature[4 + lenR] = 0x02
8472 signature[5 + lenR] = s.length
8473 s.copy(signature, 6 + lenR)
8474
8475 return signature
8476 }
8477
8478 module.exports = {
8479 check: check,
8480 decode: decode,
8481 encode: encode
8482 }
8483
8484 },{"safe-buffer":101}],42:[function(require,module,exports){
8485 module.exports={
8486 "OP_FALSE": 0,
8487 "OP_0": 0,
8488 "OP_PUSHDATA1": 76,
8489 "OP_PUSHDATA2": 77,
8490 "OP_PUSHDATA4": 78,
8491 "OP_1NEGATE": 79,
8492 "OP_RESERVED": 80,
8493 "OP_TRUE": 81,
8494 "OP_1": 81,
8495 "OP_2": 82,
8496 "OP_3": 83,
8497 "OP_4": 84,
8498 "OP_5": 85,
8499 "OP_6": 86,
8500 "OP_7": 87,
8501 "OP_8": 88,
8502 "OP_9": 89,
8503 "OP_10": 90,
8504 "OP_11": 91,
8505 "OP_12": 92,
8506 "OP_13": 93,
8507 "OP_14": 94,
8508 "OP_15": 95,
8509 "OP_16": 96,
8510
8511 "OP_NOP": 97,
8512 "OP_VER": 98,
8513 "OP_IF": 99,
8514 "OP_NOTIF": 100,
8515 "OP_VERIF": 101,
8516 "OP_VERNOTIF": 102,
8517 "OP_ELSE": 103,
8518 "OP_ENDIF": 104,
8519 "OP_VERIFY": 105,
8520 "OP_RETURN": 106,
8521
8522 "OP_TOALTSTACK": 107,
8523 "OP_FROMALTSTACK": 108,
8524 "OP_2DROP": 109,
8525 "OP_2DUP": 110,
8526 "OP_3DUP": 111,
8527 "OP_2OVER": 112,
8528 "OP_2ROT": 113,
8529 "OP_2SWAP": 114,
8530 "OP_IFDUP": 115,
8531 "OP_DEPTH": 116,
8532 "OP_DROP": 117,
8533 "OP_DUP": 118,
8534 "OP_NIP": 119,
8535 "OP_OVER": 120,
8536 "OP_PICK": 121,
8537 "OP_ROLL": 122,
8538 "OP_ROT": 123,
8539 "OP_SWAP": 124,
8540 "OP_TUCK": 125,
8541
8542 "OP_CAT": 126,
8543 "OP_SUBSTR": 127,
8544 "OP_LEFT": 128,
8545 "OP_RIGHT": 129,
8546 "OP_SIZE": 130,
8547
8548 "OP_INVERT": 131,
8549 "OP_AND": 132,
8550 "OP_OR": 133,
8551 "OP_XOR": 134,
8552 "OP_EQUAL": 135,
8553 "OP_EQUALVERIFY": 136,
8554 "OP_RESERVED1": 137,
8555 "OP_RESERVED2": 138,
8556
8557 "OP_1ADD": 139,
8558 "OP_1SUB": 140,
8559 "OP_2MUL": 141,
8560 "OP_2DIV": 142,
8561 "OP_NEGATE": 143,
8562 "OP_ABS": 144,
8563 "OP_NOT": 145,
8564 "OP_0NOTEQUAL": 146,
8565 "OP_ADD": 147,
8566 "OP_SUB": 148,
8567 "OP_MUL": 149,
8568 "OP_DIV": 150,
8569 "OP_MOD": 151,
8570 "OP_LSHIFT": 152,
8571 "OP_RSHIFT": 153,
8572
8573 "OP_BOOLAND": 154,
8574 "OP_BOOLOR": 155,
8575 "OP_NUMEQUAL": 156,
8576 "OP_NUMEQUALVERIFY": 157,
8577 "OP_NUMNOTEQUAL": 158,
8578 "OP_LESSTHAN": 159,
8579 "OP_GREATERTHAN": 160,
8580 "OP_LESSTHANOREQUAL": 161,
8581 "OP_GREATERTHANOREQUAL": 162,
8582 "OP_MIN": 163,
8583 "OP_MAX": 164,
8584
8585 "OP_WITHIN": 165,
8586
8587 "OP_RIPEMD160": 166,
8588 "OP_SHA1": 167,
8589 "OP_SHA256": 168,
8590 "OP_HASH160": 169,
8591 "OP_HASH256": 170,
8592 "OP_CODESEPARATOR": 171,
8593 "OP_CHECKSIG": 172,
8594 "OP_CHECKSIGVERIFY": 173,
8595 "OP_CHECKMULTISIG": 174,
8596 "OP_CHECKMULTISIGVERIFY": 175,
8597
8598 "OP_NOP1": 176,
8599
8600 "OP_NOP2": 177,
8601 "OP_CHECKLOCKTIMEVERIFY": 177,
8602
8603 "OP_NOP3": 178,
8604 "OP_CHECKSEQUENCEVERIFY": 178,
8605
8606 "OP_NOP4": 179,
8607 "OP_NOP5": 180,
8608 "OP_NOP6": 181,
8609 "OP_NOP7": 182,
8610 "OP_NOP8": 183,
8611 "OP_NOP9": 184,
8612 "OP_NOP10": 185,
8613
8614 "OP_PUBKEYHASH": 253,
8615 "OP_PUBKEY": 254,
8616 "OP_INVALIDOPCODE": 255
8617 }
8618
8619 },{}],43:[function(require,module,exports){
8620 var OPS = require('./index.json')
8621
8622 var map = {}
8623 for (var op in OPS) {
8624 var code = OPS[op]
8625 map[code] = op
8626 }
8627
8628 module.exports = map
8629
8630 },{"./index.json":42}],44:[function(require,module,exports){
8631 var Buffer = require('safe-buffer').Buffer
8632 var bech32 = require('bech32')
8633 var bs58check = require('bs58check')
8634 var bscript = require('./script')
8635 var btemplates = require('./templates')
8636 var networks = require('./networks')
8637 var typeforce = require('typeforce')
8638 var types = require('./types')
8639
8640 function fromBase58Check (address) {
8641 var payload = bs58check.decode(address)
8642
8643 // TODO: 4.0.0, move to "toOutputScript"
8644 if (payload.length < 21) throw new TypeError(address + ' is too short')
8645 if (payload.length > 21) throw new TypeError(address + ' is too long')
8646
8647 var version = payload.readUInt8(0)
8648 var hash = payload.slice(1)
8649
8650 return { version: version, hash: hash }
8651 }
8652
8653 function fromBech32 (address) {
8654 var result = bech32.decode(address)
8655 var data = bech32.fromWords(result.words.slice(1))
8656
8657 return {
8658 version: result.words[0],
8659 prefix: result.prefix,
8660 data: Buffer.from(data)
8661 }
8662 }
8663
8664 function toBase58Check (hash, version) {
8665 if (version < 256){
8666 typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments)
8667
8668 var payload = Buffer.allocUnsafe(21)
8669 payload.writeUInt8(version, 0)
8670 hash.copy(payload, 1)
8671
8672 return bs58check.encode(payload)
8673 }
8674 else{
8675 typeforce(types.tuple(types.Hash160bit, types.UInt16), arguments)
8676
8677 var payload = Buffer.allocUnsafe(22)
8678 payload.writeUInt16BE(version, 0)
8679 hash.copy(payload, 2)
8680
8681 return bs58check.encode(payload)
8682 }
8683 }
8684
8685 function toBech32 (data, version, prefix) {
8686 var words = bech32.toWords(data)
8687 words.unshift(version)
8688
8689 return bech32.encode(prefix, words)
8690 }
8691
8692 function fromOutputScript (outputScript, network) {
8693 network = network || networks.bitcoin
8694
8695 if (btemplates.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash)
8696 if (btemplates.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash)
8697 if (btemplates.witnessPubKeyHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 22), 0, network.bech32)
8698 if (btemplates.witnessScriptHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 34), 0, network.bech32)
8699
8700 throw new Error(bscript.toASM(outputScript) + ' has no matching Address')
8701 }
8702
8703 function toOutputScript (address, network) {
8704 network = network || networks.bitcoin
8705
8706 var decode
8707 try {
8708 decode = fromBase58Check(address)
8709 } catch (e) {}
8710
8711 if (decode) {
8712 if (decode.version === network.pubKeyHash) return btemplates.pubKeyHash.output.encode(decode.hash)
8713 if (decode.version === network.scriptHash) return btemplates.scriptHash.output.encode(decode.hash)
8714 } else {
8715 try {
8716 decode = fromBech32(address)
8717 } catch (e) {}
8718
8719 if (decode) {
8720 if (decode.prefix !== network.bech32) throw new Error(address + ' has an invalid prefix')
8721 if (decode.version === 0) {
8722 if (decode.data.length === 20) return btemplates.witnessPubKeyHash.output.encode(decode.data)
8723 if (decode.data.length === 32) return btemplates.witnessScriptHash.output.encode(decode.data)
8724 }
8725 }
8726 }
8727
8728 throw new Error(address + ' has no matching Script')
8729 }
8730
8731 module.exports = {
8732 fromBase58Check: fromBase58Check,
8733 fromBech32: fromBech32,
8734 fromOutputScript: fromOutputScript,
8735 toBase58Check: toBase58Check,
8736 toBech32: toBech32,
8737 toOutputScript: toOutputScript
8738 }
8739
8740 },{"./networks":53,"./script":54,"./templates":56,"./types":80,"bech32":36,"bs58check":83,"safe-buffer":101,"typeforce":112}],45:[function(require,module,exports){
8741 var Buffer = require('safe-buffer').Buffer
8742 var bcrypto = require('./crypto')
8743 var fastMerkleRoot = require('merkle-lib/fastRoot')
8744 var typeforce = require('typeforce')
8745 var types = require('./types')
8746 var varuint = require('varuint-bitcoin')
8747
8748 var Transaction = require('./transaction')
8749
8750 function Block () {
8751 this.version = 1
8752 this.prevHash = null
8753 this.merkleRoot = null
8754 this.timestamp = 0
8755 this.bits = 0
8756 this.nonce = 0
8757 }
8758
8759 Block.fromBuffer = function (buffer) {
8760 if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)')
8761
8762 var offset = 0
8763 function readSlice (n) {
8764 offset += n
8765 return buffer.slice(offset - n, offset)
8766 }
8767
8768 function readUInt32 () {
8769 var i = buffer.readUInt32LE(offset)
8770 offset += 4
8771 return i
8772 }
8773
8774 function readInt32 () {
8775 var i = buffer.readInt32LE(offset)
8776 offset += 4
8777 return i
8778 }
8779
8780 var block = new Block()
8781 block.version = readInt32()
8782 block.prevHash = readSlice(32)
8783 block.merkleRoot = readSlice(32)
8784 block.timestamp = readUInt32()
8785 block.bits = readUInt32()
8786 block.nonce = readUInt32()
8787
8788 if (buffer.length === 80) return block
8789
8790 function readVarInt () {
8791 var vi = varuint.decode(buffer, offset)
8792 offset += varuint.decode.bytes
8793 return vi
8794 }
8795
8796 function readTransaction () {
8797 var tx = Transaction.fromBuffer(buffer.slice(offset), true)
8798 offset += tx.byteLength()
8799 return tx
8800 }
8801
8802 var nTransactions = readVarInt()
8803 block.transactions = []
8804
8805 for (var i = 0; i < nTransactions; ++i) {
8806 var tx = readTransaction()
8807 block.transactions.push(tx)
8808 }
8809
8810 return block
8811 }
8812
8813 Block.prototype.byteLength = function (headersOnly) {
8814 if (headersOnly || !this.transactions) return 80
8815
8816 return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) {
8817 return a + x.byteLength()
8818 }, 0)
8819 }
8820
8821 Block.fromHex = function (hex) {
8822 return Block.fromBuffer(Buffer.from(hex, 'hex'))
8823 }
8824
8825 Block.prototype.getHash = function () {
8826 return bcrypto.hash256(this.toBuffer(true))
8827 }
8828
8829 Block.prototype.getId = function () {
8830 return this.getHash().reverse().toString('hex')
8831 }
8832
8833 Block.prototype.getUTCDate = function () {
8834 var date = new Date(0) // epoch
8835 date.setUTCSeconds(this.timestamp)
8836
8837 return date
8838 }
8839
8840 // TODO: buffer, offset compatibility
8841 Block.prototype.toBuffer = function (headersOnly) {
8842 var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly))
8843
8844 var offset = 0
8845 function writeSlice (slice) {
8846 slice.copy(buffer, offset)
8847 offset += slice.length
8848 }
8849
8850 function writeInt32 (i) {
8851 buffer.writeInt32LE(i, offset)
8852 offset += 4
8853 }
8854 function writeUInt32 (i) {
8855 buffer.writeUInt32LE(i, offset)
8856 offset += 4
8857 }
8858
8859 writeInt32(this.version)
8860 writeSlice(this.prevHash)
8861 writeSlice(this.merkleRoot)
8862 writeUInt32(this.timestamp)
8863 writeUInt32(this.bits)
8864 writeUInt32(this.nonce)
8865
8866 if (headersOnly || !this.transactions) return buffer
8867
8868 varuint.encode(this.transactions.length, buffer, offset)
8869 offset += varuint.encode.bytes
8870
8871 this.transactions.forEach(function (tx) {
8872 var txSize = tx.byteLength() // TODO: extract from toBuffer?
8873 tx.toBuffer(buffer, offset)
8874 offset += txSize
8875 })
8876
8877 return buffer
8878 }
8879
8880 Block.prototype.toHex = function (headersOnly) {
8881 return this.toBuffer(headersOnly).toString('hex')
8882 }
8883
8884 Block.calculateTarget = function (bits) {
8885 var exponent = ((bits & 0xff000000) >> 24) - 3
8886 var mantissa = bits & 0x007fffff
8887 var target = Buffer.alloc(32, 0)
8888 target.writeUInt32BE(mantissa, 28 - exponent)
8889 return target
8890 }
8891
8892 Block.calculateMerkleRoot = function (transactions) {
8893 typeforce([{ getHash: types.Function }], transactions)
8894 if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions')
8895
8896 var hashes = transactions.map(function (transaction) {
8897 return transaction.getHash()
8898 })
8899
8900 return fastMerkleRoot(hashes, bcrypto.hash256)
8901 }
8902
8903 Block.prototype.checkMerkleRoot = function () {
8904 if (!this.transactions) return false
8905
8906 var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
8907 return this.merkleRoot.compare(actualMerkleRoot) === 0
8908 }
8909
8910 Block.prototype.checkProofOfWork = function () {
8911 var hash = this.getHash().reverse()
8912 var target = Block.calculateTarget(this.bits)
8913
8914 return hash.compare(target) <= 0
8915 }
8916
8917 module.exports = Block
8918
8919 },{"./crypto":47,"./transaction":78,"./types":80,"merkle-lib/fastRoot":97,"safe-buffer":101,"typeforce":112,"varuint-bitcoin":114}],46:[function(require,module,exports){
8920 var pushdata = require('pushdata-bitcoin')
8921 var varuint = require('varuint-bitcoin')
8922
8923 // https://github.com/feross/buffer/blob/master/index.js#L1127
8924 function verifuint (value, max) {
8925 if (typeof value !== 'number') throw new Error('cannot write a non-number as a number')
8926 if (value < 0) throw new Error('specified a negative value for writing an unsigned value')
8927 if (value > max) throw new Error('RangeError: value out of range')
8928 if (Math.floor(value) !== value) throw new Error('value has a fractional component')
8929 }
8930
8931 function readUInt64LE (buffer, offset) {
8932 var a = buffer.readUInt32LE(offset)
8933 var b = buffer.readUInt32LE(offset + 4)
8934 b *= 0x100000000
8935
8936 verifuint(b + a, 0x001fffffffffffff)
8937
8938 return b + a
8939 }
8940
8941 function writeUInt64LE (buffer, value, offset) {
8942 verifuint(value, 0x001fffffffffffff)
8943
8944 buffer.writeInt32LE(value & -1, offset)
8945 buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
8946 return offset + 8
8947 }
8948
8949 // TODO: remove in 4.0.0?
8950 function readVarInt (buffer, offset) {
8951 var result = varuint.decode(buffer, offset)
8952
8953 return {
8954 number: result,
8955 size: varuint.decode.bytes
8956 }
8957 }
8958
8959 // TODO: remove in 4.0.0?
8960 function writeVarInt (buffer, number, offset) {
8961 varuint.encode(number, buffer, offset)
8962 return varuint.encode.bytes
8963 }
8964
8965 module.exports = {
8966 pushDataSize: pushdata.encodingLength,
8967 readPushDataInt: pushdata.decode,
8968 readUInt64LE: readUInt64LE,
8969 readVarInt: readVarInt,
8970 varIntBuffer: varuint.encode,
8971 varIntSize: varuint.encodingLength,
8972 writePushDataInt: pushdata.encode,
8973 writeUInt64LE: writeUInt64LE,
8974 writeVarInt: writeVarInt
8975 }
8976
8977 },{"pushdata-bitcoin":98,"varuint-bitcoin":114}],47:[function(require,module,exports){
8978 var createHash = require('create-hash')
8979
8980 function ripemd160 (buffer) {
8981 return createHash('rmd160').update(buffer).digest()
8982 }
8983
8984 function sha1 (buffer) {
8985 return createHash('sha1').update(buffer).digest()
8986 }
8987
8988 function sha256 (buffer) {
8989 return createHash('sha256').update(buffer).digest()
8990 }
8991
8992 function hash160 (buffer) {
8993 return ripemd160(sha256(buffer))
8994 }
8995
8996 function hash256 (buffer) {
8997 return sha256(sha256(buffer))
8998 }
8999
9000 module.exports = {
9001 hash160: hash160,
9002 hash256: hash256,
9003 ripemd160: ripemd160,
9004 sha1: sha1,
9005 sha256: sha256
9006 }
9007
9008 },{"create-hash":85}],48:[function(require,module,exports){
9009 var Buffer = require('safe-buffer').Buffer
9010 var createHmac = require('create-hmac')
9011 var typeforce = require('typeforce')
9012 var types = require('./types')
9013
9014 var BigInteger = require('bigi')
9015 var ECSignature = require('./ecsignature')
9016
9017 var ZERO = Buffer.alloc(1, 0)
9018 var ONE = Buffer.alloc(1, 1)
9019
9020 var ecurve = require('ecurve')
9021 var secp256k1 = ecurve.getCurveByName('secp256k1')
9022
9023 // https://tools.ietf.org/html/rfc6979#section-3.2
9024 function deterministicGenerateK (hash, x, checkSig) {
9025 typeforce(types.tuple(
9026 types.Hash256bit,
9027 types.Buffer256bit,
9028 types.Function
9029 ), arguments)
9030
9031 // Step A, ignored as hash already provided
9032 // Step B
9033 // Step C
9034 var k = Buffer.alloc(32, 0)
9035 var v = Buffer.alloc(32, 1)
9036
9037 // Step D
9038 k = createHmac('sha256', k)
9039 .update(v)
9040 .update(ZERO)
9041 .update(x)
9042 .update(hash)
9043 .digest()
9044
9045 // Step E
9046 v = createHmac('sha256', k).update(v).digest()
9047
9048 // Step F
9049 k = createHmac('sha256', k)
9050 .update(v)
9051 .update(ONE)
9052 .update(x)
9053 .update(hash)
9054 .digest()
9055
9056 // Step G
9057 v = createHmac('sha256', k).update(v).digest()
9058
9059 // Step H1/H2a, ignored as tlen === qlen (256 bit)
9060 // Step H2b
9061 v = createHmac('sha256', k).update(v).digest()
9062
9063 var T = BigInteger.fromBuffer(v)
9064
9065 // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA
9066 while (T.signum() <= 0 || T.compareTo(secp256k1.n) >= 0 || !checkSig(T)) {
9067 k = createHmac('sha256', k)
9068 .update(v)
9069 .update(ZERO)
9070 .digest()
9071
9072 v = createHmac('sha256', k).update(v).digest()
9073
9074 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
9075 // Step H2b again
9076 v = createHmac('sha256', k).update(v).digest()
9077 T = BigInteger.fromBuffer(v)
9078 }
9079
9080 return T
9081 }
9082
9083 var N_OVER_TWO = secp256k1.n.shiftRight(1)
9084
9085 function sign (hash, d) {
9086 typeforce(types.tuple(types.Hash256bit, types.BigInt), arguments)
9087
9088 var x = d.toBuffer(32)
9089 var e = BigInteger.fromBuffer(hash)
9090 var n = secp256k1.n
9091 var G = secp256k1.G
9092
9093 var r, s
9094 deterministicGenerateK(hash, x, function (k) {
9095 var Q = G.multiply(k)
9096
9097 if (secp256k1.isInfinity(Q)) return false
9098
9099 r = Q.affineX.mod(n)
9100 if (r.signum() === 0) return false
9101
9102 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
9103 if (s.signum() === 0) return false
9104
9105 return true
9106 })
9107
9108 // enforce low S values, see bip62: 'low s values in signatures'
9109 if (s.compareTo(N_OVER_TWO) > 0) {
9110 s = n.subtract(s)
9111 }
9112
9113 return new ECSignature(r, s)
9114 }
9115
9116 function verify (hash, signature, Q) {
9117 typeforce(types.tuple(
9118 types.Hash256bit,
9119 types.ECSignature,
9120 types.ECPoint
9121 ), arguments)
9122
9123 var n = secp256k1.n
9124 var G = secp256k1.G
9125
9126 var r = signature.r
9127 var s = signature.s
9128
9129 // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
9130 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false
9131 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false
9132
9133 // 1.4.2 H = Hash(M), already done by the user
9134 // 1.4.3 e = H
9135 var e = BigInteger.fromBuffer(hash)
9136
9137 // Compute s^-1
9138 var sInv = s.modInverse(n)
9139
9140 // 1.4.4 Compute u1 = es^−1 mod n
9141 // u2 = rs^−1 mod n
9142 var u1 = e.multiply(sInv).mod(n)
9143 var u2 = r.multiply(sInv).mod(n)
9144
9145 // 1.4.5 Compute R = (xR, yR)
9146 // R = u1G + u2Q
9147 var R = G.multiplyTwo(u1, Q, u2)
9148
9149 // 1.4.5 (cont.) Enforce R is not at infinity
9150 if (secp256k1.isInfinity(R)) return false
9151
9152 // 1.4.6 Convert the field element R.x to an integer
9153 var xR = R.affineX
9154
9155 // 1.4.7 Set v = xR mod n
9156 var v = xR.mod(n)
9157
9158 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
9159 return v.equals(r)
9160 }
9161
9162 module.exports = {
9163 deterministicGenerateK: deterministicGenerateK,
9164 sign: sign,
9165 verify: verify,
9166
9167 // TODO: remove
9168 __curve: secp256k1
9169 }
9170
9171 },{"./ecsignature":50,"./types":80,"bigi":39,"create-hmac":88,"ecurve":92,"safe-buffer":101,"typeforce":112}],49:[function(require,module,exports){
9172 var baddress = require('./address')
9173 var bcrypto = require('./crypto')
9174 var ecdsa = require('./ecdsa')
9175 var randomBytes = require('randombytes')
9176 var typeforce = require('typeforce')
9177 var types = require('./types')
9178 var wif = require('wif')
9179
9180 var NETWORKS = require('./networks')
9181 var BigInteger = require('bigi')
9182
9183 var ecurve = require('ecurve')
9184 var secp256k1 = ecdsa.__curve
9185
9186 function ECPair (d, Q, options) {
9187 if (options) {
9188 typeforce({
9189 compressed: types.maybe(types.Boolean),
9190 network: types.maybe(types.Network)
9191 }, options)
9192 }
9193
9194 options = options || {}
9195
9196 if (d) {
9197 if (d.signum() <= 0) throw new Error('Private key must be greater than 0')
9198 if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order')
9199 if (Q) throw new TypeError('Unexpected publicKey parameter')
9200
9201 this.d = d
9202 } else {
9203 typeforce(types.ECPoint, Q)
9204
9205 this.__Q = Q
9206 }
9207
9208 this.compressed = options.compressed === undefined ? true : options.compressed
9209 this.network = options.network || NETWORKS.bitcoin
9210 }
9211
9212 Object.defineProperty(ECPair.prototype, 'Q', {
9213 get: function () {
9214 if (!this.__Q && this.d) {
9215 this.__Q = secp256k1.G.multiply(this.d)
9216 }
9217
9218 return this.__Q
9219 }
9220 })
9221
9222 ECPair.fromPublicKeyBuffer = function (buffer, network) {
9223 var Q = ecurve.Point.decodeFrom(secp256k1, buffer)
9224
9225 return new ECPair(null, Q, {
9226 compressed: Q.compressed,
9227 network: network
9228 })
9229 }
9230
9231 ECPair.fromWIF = function (string, network) {
9232 var decoded = wif.decode(string)
9233 var version = decoded.version
9234
9235 // list of networks?
9236 if (types.Array(network)) {
9237 network = network.filter(function (x) {
9238 return version === x.wif
9239 }).pop()
9240
9241 if (!network) throw new Error('Unknown network version')
9242
9243 // otherwise, assume a network object (or default to bitcoin)
9244 } else {
9245 network = network || NETWORKS.bitcoin
9246
9247 if (version !== network.wif) throw new Error('Invalid network version')
9248 }
9249
9250 var d = BigInteger.fromBuffer(decoded.privateKey)
9251
9252 return new ECPair(d, null, {
9253 compressed: decoded.compressed,
9254 network: network
9255 })
9256 }
9257
9258 ECPair.makeRandom = function (options) {
9259 options = options || {}
9260
9261 var rng = options.rng || randomBytes
9262
9263 var d
9264 do {
9265 var buffer = rng(32)
9266 typeforce(types.Buffer256bit, buffer)
9267
9268 d = BigInteger.fromBuffer(buffer)
9269 } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0)
9270
9271 return new ECPair(d, null, options)
9272 }
9273
9274 ECPair.prototype.getAddress = function () {
9275 return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash)
9276 }
9277
9278 ECPair.prototype.getNetwork = function () {
9279 return this.network
9280 }
9281
9282 ECPair.prototype.getPublicKeyBuffer = function () {
9283 return this.Q.getEncoded(this.compressed)
9284 }
9285
9286 ECPair.prototype.sign = function (hash) {
9287 if (!this.d) throw new Error('Missing private key')
9288
9289 return ecdsa.sign(hash, this.d)
9290 }
9291
9292 ECPair.prototype.toWIF = function () {
9293 if (!this.d) throw new Error('Missing private key')
9294
9295 return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed)
9296 }
9297
9298 ECPair.prototype.verify = function (hash, signature) {
9299 return ecdsa.verify(hash, signature, this.Q)
9300 }
9301
9302 module.exports = ECPair
9303
9304 },{"./address":44,"./crypto":47,"./ecdsa":48,"./networks":53,"./types":80,"bigi":39,"ecurve":92,"randombytes":99,"typeforce":112,"wif":115}],50:[function(require,module,exports){
9305 (function (Buffer){
9306 var bip66 = require('bip66')
9307 var typeforce = require('typeforce')
9308 var types = require('./types')
9309
9310 var BigInteger = require('bigi')
9311
9312 function ECSignature (r, s) {
9313 typeforce(types.tuple(types.BigInt, types.BigInt), arguments)
9314
9315 this.r = r
9316 this.s = s
9317 }
9318
9319 ECSignature.parseCompact = function (buffer) {
9320 typeforce(types.BufferN(65), buffer)
9321
9322 var flagByte = buffer.readUInt8(0) - 27
9323 if (flagByte !== (flagByte & 7)) throw new Error('Invalid signature parameter')
9324
9325 var compressed = !!(flagByte & 4)
9326 var recoveryParam = flagByte & 3
9327 var signature = ECSignature.fromRSBuffer(buffer.slice(1))
9328
9329 return {
9330 compressed: compressed,
9331 i: recoveryParam,
9332 signature: signature
9333 }
9334 }
9335
9336 ECSignature.fromRSBuffer = function (buffer) {
9337 typeforce(types.BufferN(64), buffer)
9338
9339 var r = BigInteger.fromBuffer(buffer.slice(0, 32))
9340 var s = BigInteger.fromBuffer(buffer.slice(32, 64))
9341 return new ECSignature(r, s)
9342 }
9343
9344 ECSignature.fromDER = function (buffer) {
9345 var decode = bip66.decode(buffer)
9346 var r = BigInteger.fromDERInteger(decode.r)
9347 var s = BigInteger.fromDERInteger(decode.s)
9348
9349 return new ECSignature(r, s)
9350 }
9351
9352 // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
9353 ECSignature.parseScriptSignature = function (buffer) {
9354 var hashType = buffer.readUInt8(buffer.length - 1)
9355 var hashTypeMod = hashType & ~0x80
9356
9357 if (hashTypeMod <= 0x00 || hashTypeMod >= 0x04) throw new Error('Invalid hashType ' + hashType)
9358
9359 return {
9360 signature: ECSignature.fromDER(buffer.slice(0, -1)),
9361 hashType: hashType
9362 }
9363 }
9364
9365 ECSignature.prototype.toCompact = function (i, compressed) {
9366 if (compressed) {
9367 i += 4
9368 }
9369
9370 i += 27
9371
9372 var buffer = Buffer.alloc(65)
9373 buffer.writeUInt8(i, 0)
9374 this.toRSBuffer(buffer, 1)
9375 return buffer
9376 }
9377
9378 ECSignature.prototype.toDER = function () {
9379 var r = Buffer.from(this.r.toDERInteger())
9380 var s = Buffer.from(this.s.toDERInteger())
9381
9382 return bip66.encode(r, s)
9383 }
9384
9385 ECSignature.prototype.toRSBuffer = function (buffer, offset) {
9386 buffer = buffer || Buffer.alloc(64)
9387 this.r.toBuffer(32).copy(buffer, offset)
9388 this.s.toBuffer(32).copy(buffer, offset + 32)
9389 return buffer
9390 }
9391
9392 ECSignature.prototype.toScriptSignature = function (hashType) {
9393 var hashTypeMod = hashType & ~0x80
9394 if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType)
9395
9396 var hashTypeBuffer = Buffer.alloc(1)
9397 hashTypeBuffer.writeUInt8(hashType, 0)
9398
9399 return Buffer.concat([this.toDER(), hashTypeBuffer])
9400 }
9401
9402 module.exports = ECSignature
9403
9404 }).call(this,require("buffer").Buffer)
9405 },{"./types":80,"bigi":39,"bip66":41,"buffer":5,"typeforce":112}],51:[function(require,module,exports){
9406 var Buffer = require('safe-buffer').Buffer
9407 var base58check = require('bs58check')
9408 var bcrypto = require('./crypto')
9409 var createHmac = require('create-hmac')
9410 var typeforce = require('typeforce')
9411 var types = require('./types')
9412 var NETWORKS = require('./networks')
9413
9414 var BigInteger = require('bigi')
9415 var ECPair = require('./ecpair')
9416
9417 var ecurve = require('ecurve')
9418 var curve = ecurve.getCurveByName('secp256k1')
9419
9420 function HDNode (keyPair, chainCode) {
9421 typeforce(types.tuple('ECPair', types.Buffer256bit), arguments)
9422
9423 if (!keyPair.compressed) throw new TypeError('BIP32 only allows compressed keyPairs')
9424
9425 this.keyPair = keyPair
9426 this.chainCode = chainCode
9427 this.depth = 0
9428 this.index = 0
9429 this.parentFingerprint = 0x00000000
9430 }
9431
9432 HDNode.HIGHEST_BIT = 0x80000000
9433 HDNode.LENGTH = 78
9434 HDNode.MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8')
9435
9436 HDNode.fromSeedBuffer = function (seed, network) {
9437 typeforce(types.tuple(types.Buffer, types.maybe(types.Network)), arguments)
9438
9439 if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits')
9440 if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits')
9441
9442 var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest()
9443 var IL = I.slice(0, 32)
9444 var IR = I.slice(32)
9445
9446 // In case IL is 0 or >= n, the master key is invalid
9447 // This is handled by the ECPair constructor
9448 var pIL = BigInteger.fromBuffer(IL)
9449 var keyPair = new ECPair(pIL, null, {
9450 network: network
9451 })
9452
9453 return new HDNode(keyPair, IR)
9454 }
9455
9456 HDNode.fromSeedHex = function (hex, network) {
9457 return HDNode.fromSeedBuffer(Buffer.from(hex, 'hex'), network)
9458 }
9459
9460 HDNode.fromBase58 = function (string, networks) {
9461 var buffer = base58check.decode(string)
9462 if (buffer.length !== 78) throw new Error('Invalid buffer length')
9463
9464 // 4 bytes: version bytes
9465 var version = buffer.readUInt32BE(0)
9466 var network
9467
9468 // list of networks?
9469 if (Array.isArray(networks)) {
9470 network = networks.filter(function (x) {
9471 return version === x.bip32.private ||
9472 version === x.bip32.public
9473 }).pop()
9474
9475 if (!network) throw new Error('Unknown network version')
9476
9477 // otherwise, assume a network object (or default to bitcoin)
9478 } else {
9479 network = networks || NETWORKS.bitcoin
9480 }
9481
9482 if (version !== network.bip32.private &&
9483 version !== network.bip32.public) throw new Error('Invalid network version')
9484
9485 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
9486 var depth = buffer[4]
9487
9488 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9489 var parentFingerprint = buffer.readUInt32BE(5)
9490 if (depth === 0) {
9491 if (parentFingerprint !== 0x00000000) throw new Error('Invalid parent fingerprint')
9492 }
9493
9494 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9495 // This is encoded in MSB order. (0x00000000 if master key)
9496 var index = buffer.readUInt32BE(9)
9497 if (depth === 0 && index !== 0) throw new Error('Invalid index')
9498
9499 // 32 bytes: the chain code
9500 var chainCode = buffer.slice(13, 45)
9501 var keyPair
9502
9503 // 33 bytes: private key data (0x00 + k)
9504 if (version === network.bip32.private) {
9505 if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key')
9506
9507 var d = BigInteger.fromBuffer(buffer.slice(46, 78))
9508 keyPair = new ECPair(d, null, { network: network })
9509
9510 // 33 bytes: public key data (0x02 + X or 0x03 + X)
9511 } else {
9512 var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78))
9513 // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw
9514
9515 // Verify that the X coordinate in the public point corresponds to a point on the curve.
9516 // If not, the extended public key is invalid.
9517 curve.validate(Q)
9518
9519 keyPair = new ECPair(null, Q, { network: network })
9520 }
9521
9522 var hd = new HDNode(keyPair, chainCode)
9523 hd.depth = depth
9524 hd.index = index
9525 hd.parentFingerprint = parentFingerprint
9526
9527 return hd
9528 }
9529
9530 HDNode.prototype.getAddress = function () {
9531 return this.keyPair.getAddress()
9532 }
9533
9534 HDNode.prototype.getIdentifier = function () {
9535 return bcrypto.hash160(this.keyPair.getPublicKeyBuffer())
9536 }
9537
9538 HDNode.prototype.getFingerprint = function () {
9539 return this.getIdentifier().slice(0, 4)
9540 }
9541
9542 HDNode.prototype.getNetwork = function () {
9543 return this.keyPair.getNetwork()
9544 }
9545
9546 HDNode.prototype.getPublicKeyBuffer = function () {
9547 return this.keyPair.getPublicKeyBuffer()
9548 }
9549
9550 HDNode.prototype.neutered = function () {
9551 var neuteredKeyPair = new ECPair(null, this.keyPair.Q, {
9552 network: this.keyPair.network
9553 })
9554
9555 var neutered = new HDNode(neuteredKeyPair, this.chainCode)
9556 neutered.depth = this.depth
9557 neutered.index = this.index
9558 neutered.parentFingerprint = this.parentFingerprint
9559
9560 return neutered
9561 }
9562
9563 HDNode.prototype.sign = function (hash) {
9564 return this.keyPair.sign(hash)
9565 }
9566
9567 HDNode.prototype.verify = function (hash, signature) {
9568 return this.keyPair.verify(hash, signature)
9569 }
9570
9571 HDNode.prototype.toBase58 = function (__isPrivate) {
9572 if (__isPrivate !== undefined) throw new TypeError('Unsupported argument in 2.0.0')
9573
9574 // Version
9575 var network = this.keyPair.network
9576 var version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public
9577 var buffer = Buffer.allocUnsafe(78)
9578
9579 // 4 bytes: version bytes
9580 buffer.writeUInt32BE(version, 0)
9581
9582 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
9583 buffer.writeUInt8(this.depth, 4)
9584
9585 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9586 buffer.writeUInt32BE(this.parentFingerprint, 5)
9587
9588 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9589 // This is encoded in big endian. (0x00000000 if master key)
9590 buffer.writeUInt32BE(this.index, 9)
9591
9592 // 32 bytes: the chain code
9593 this.chainCode.copy(buffer, 13)
9594
9595 // 33 bytes: the public key or private key data
9596 if (!this.isNeutered()) {
9597 // 0x00 + k for private keys
9598 buffer.writeUInt8(0, 45)
9599 this.keyPair.d.toBuffer(32).copy(buffer, 46)
9600
9601 // 33 bytes: the public key
9602 } else {
9603 // X9.62 encoding for public keys
9604 this.keyPair.getPublicKeyBuffer().copy(buffer, 45)
9605 }
9606
9607 return base58check.encode(buffer)
9608 }
9609
9610 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
9611 HDNode.prototype.derive = function (index) {
9612 typeforce(types.UInt32, index)
9613
9614 var isHardened = index >= HDNode.HIGHEST_BIT
9615 var data = Buffer.allocUnsafe(37)
9616
9617 // Hardened child
9618 if (isHardened) {
9619 if (this.isNeutered()) throw new TypeError('Could not derive hardened child key')
9620
9621 // data = 0x00 || ser256(kpar) || ser32(index)
9622 data[0] = 0x00
9623 this.keyPair.d.toBuffer(32).copy(data, 1)
9624 data.writeUInt32BE(index, 33)
9625
9626 // Normal child
9627 } else {
9628 // data = serP(point(kpar)) || ser32(index)
9629 // = serP(Kpar) || ser32(index)
9630 this.keyPair.getPublicKeyBuffer().copy(data, 0)
9631 data.writeUInt32BE(index, 33)
9632 }
9633
9634 var I = createHmac('sha512', this.chainCode).update(data).digest()
9635 var IL = I.slice(0, 32)
9636 var IR = I.slice(32)
9637
9638 var pIL = BigInteger.fromBuffer(IL)
9639
9640 // In case parse256(IL) >= n, proceed with the next value for i
9641 if (pIL.compareTo(curve.n) >= 0) {
9642 return this.derive(index + 1)
9643 }
9644
9645 // Private parent key -> private child key
9646 var derivedKeyPair
9647 if (!this.isNeutered()) {
9648 // ki = parse256(IL) + kpar (mod n)
9649 var ki = pIL.add(this.keyPair.d).mod(curve.n)
9650
9651 // In case ki == 0, proceed with the next value for i
9652 if (ki.signum() === 0) {
9653 return this.derive(index + 1)
9654 }
9655
9656 derivedKeyPair = new ECPair(ki, null, {
9657 network: this.keyPair.network
9658 })
9659
9660 // Public parent key -> public child key
9661 } else {
9662 // Ki = point(parse256(IL)) + Kpar
9663 // = G*IL + Kpar
9664 var Ki = curve.G.multiply(pIL).add(this.keyPair.Q)
9665
9666 // In case Ki is the point at infinity, proceed with the next value for i
9667 if (curve.isInfinity(Ki)) {
9668 return this.derive(index + 1)
9669 }
9670
9671 derivedKeyPair = new ECPair(null, Ki, {
9672 network: this.keyPair.network
9673 })
9674 }
9675
9676 var hd = new HDNode(derivedKeyPair, IR)
9677 hd.depth = this.depth + 1
9678 hd.index = index
9679 hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)
9680
9681 return hd
9682 }
9683
9684 HDNode.prototype.deriveHardened = function (index) {
9685 typeforce(types.UInt31, index)
9686
9687 // Only derives hardened private keys by default
9688 return this.derive(index + HDNode.HIGHEST_BIT)
9689 }
9690
9691 // Private === not neutered
9692 // Public === neutered
9693 HDNode.prototype.isNeutered = function () {
9694 return !(this.keyPair.d)
9695 }
9696
9697 HDNode.prototype.derivePath = function (path) {
9698 typeforce(types.BIP32Path, path)
9699
9700 var splitPath = path.split('/')
9701 if (splitPath[0] === 'm') {
9702 if (this.parentFingerprint) {
9703 throw new Error('Not a master node')
9704 }
9705
9706 splitPath = splitPath.slice(1)
9707 }
9708
9709 return splitPath.reduce(function (prevHd, indexStr) {
9710 var index
9711 if (indexStr.slice(-1) === "'") {
9712 index = parseInt(indexStr.slice(0, -1), 10)
9713 return prevHd.deriveHardened(index)
9714 } else {
9715 index = parseInt(indexStr, 10)
9716 return prevHd.derive(index)
9717 }
9718 }, this)
9719 }
9720
9721 module.exports = HDNode
9722
9723 },{"./crypto":47,"./ecpair":49,"./networks":53,"./types":80,"bigi":39,"bs58check":83,"create-hmac":88,"ecurve":92,"safe-buffer":101,"typeforce":112}],52:[function(require,module,exports){
9724 var script = require('./script')
9725
9726 var templates = require('./templates')
9727 for (var key in templates) {
9728 script[key] = templates[key]
9729 }
9730
9731 module.exports = {
9732 bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0
9733
9734 Block: require('./block'),
9735 ECPair: require('./ecpair'),
9736 ECSignature: require('./ecsignature'),
9737 HDNode: require('./hdnode'),
9738 Transaction: require('./transaction'),
9739 TransactionBuilder: require('./transaction_builder'),
9740
9741 address: require('./address'),
9742 crypto: require('./crypto'),
9743 networks: require('./networks'),
9744 opcodes: require('bitcoin-ops'),
9745 script: script
9746 }
9747
9748 },{"./address":44,"./block":45,"./bufferutils":46,"./crypto":47,"./ecpair":49,"./ecsignature":50,"./hdnode":51,"./networks":53,"./script":54,"./templates":56,"./transaction":78,"./transaction_builder":79,"bitcoin-ops":42}],53:[function(require,module,exports){
9749 // https://en.bitcoin.it/wiki/List_of_address_prefixes
9750 // Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
9751
9752 module.exports = {
9753 bitcoin: {
9754 messagePrefix: '\x18Bitcoin Signed Message:\n',
9755 bech32: 'bc',
9756 bip32: {
9757 public: 0x0488b21e,
9758 private: 0x0488ade4
9759 },
9760 pubKeyHash: 0x00,
9761 scriptHash: 0x05,
9762 wif: 0x80
9763 },
9764 testnet: {
9765 messagePrefix: '\x18Bitcoin Signed Message:\n',
9766 bech32: 'tb',
9767 bip32: {
9768 public: 0x043587cf,
9769 private: 0x04358394
9770 },
9771 pubKeyHash: 0x6f,
9772 scriptHash: 0xc4,
9773 wif: 0xef
9774 },
9775 litecoin: {
9776 messagePrefix: '\x19Litecoin Signed Message:\n',
9777 bip32: {
9778 public: 0x019da462,
9779 private: 0x019d9cfe
9780 },
9781 pubKeyHash: 0x30,
9782 scriptHash: 0x32,
9783 wif: 0xb0
9784 }
9785 }
9786
9787 },{}],54:[function(require,module,exports){
9788 var Buffer = require('safe-buffer').Buffer
9789 var bip66 = require('bip66')
9790 var pushdata = require('pushdata-bitcoin')
9791 var typeforce = require('typeforce')
9792 var types = require('./types')
9793 var scriptNumber = require('./script_number')
9794
9795 var OPS = require('bitcoin-ops')
9796 var REVERSE_OPS = require('bitcoin-ops/map')
9797 var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
9798
9799 function isOPInt (value) {
9800 return types.Number(value) &&
9801 ((value === OPS.OP_0) ||
9802 (value >= OPS.OP_1 && value <= OPS.OP_16) ||
9803 (value === OPS.OP_1NEGATE))
9804 }
9805
9806 function isPushOnlyChunk (value) {
9807 return types.Buffer(value) || isOPInt(value)
9808 }
9809
9810 function isPushOnly (value) {
9811 return types.Array(value) && value.every(isPushOnlyChunk)
9812 }
9813
9814 function asMinimalOP (buffer) {
9815 if (buffer.length === 0) return OPS.OP_0
9816 if (buffer.length !== 1) return
9817 if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]
9818 if (buffer[0] === 0x81) return OPS.OP_1NEGATE
9819 }
9820
9821 function compile (chunks) {
9822 // TODO: remove me
9823 if (Buffer.isBuffer(chunks)) return chunks
9824
9825 typeforce(types.Array, chunks)
9826
9827 var bufferSize = chunks.reduce(function (accum, chunk) {
9828 // data chunk
9829 if (Buffer.isBuffer(chunk)) {
9830 // adhere to BIP62.3, minimal push policy
9831 if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) {
9832 return accum + 1
9833 }
9834
9835 return accum + pushdata.encodingLength(chunk.length) + chunk.length
9836 }
9837
9838 // opcode
9839 return accum + 1
9840 }, 0.0)
9841
9842 var buffer = Buffer.allocUnsafe(bufferSize)
9843 var offset = 0
9844
9845 chunks.forEach(function (chunk) {
9846 // data chunk
9847 if (Buffer.isBuffer(chunk)) {
9848 // adhere to BIP62.3, minimal push policy
9849 var opcode = asMinimalOP(chunk)
9850 if (opcode !== undefined) {
9851 buffer.writeUInt8(opcode, offset)
9852 offset += 1
9853 return
9854 }
9855
9856 offset += pushdata.encode(buffer, chunk.length, offset)
9857 chunk.copy(buffer, offset)
9858 offset += chunk.length
9859
9860 // opcode
9861 } else {
9862 buffer.writeUInt8(chunk, offset)
9863 offset += 1
9864 }
9865 })
9866
9867 if (offset !== buffer.length) throw new Error('Could not decode chunks')
9868 return buffer
9869 }
9870
9871 function decompile (buffer) {
9872 // TODO: remove me
9873 if (types.Array(buffer)) return buffer
9874
9875 typeforce(types.Buffer, buffer)
9876
9877 var chunks = []
9878 var i = 0
9879
9880 while (i < buffer.length) {
9881 var opcode = buffer[i]
9882
9883 // data chunk
9884 if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) {
9885 var d = pushdata.decode(buffer, i)
9886
9887 // did reading a pushDataInt fail? empty script
9888 if (d === null) return []
9889 i += d.size
9890
9891 // attempt to read too much data? empty script
9892 if (i + d.number > buffer.length) return []
9893
9894 var data = buffer.slice(i, i + d.number)
9895 i += d.number
9896
9897 // decompile minimally
9898 var op = asMinimalOP(data)
9899 if (op !== undefined) {
9900 chunks.push(op)
9901 } else {
9902 chunks.push(data)
9903 }
9904
9905 // opcode
9906 } else {
9907 chunks.push(opcode)
9908
9909 i += 1
9910 }
9911 }
9912
9913 return chunks
9914 }
9915
9916 function toASM (chunks) {
9917 if (Buffer.isBuffer(chunks)) {
9918 chunks = decompile(chunks)
9919 }
9920
9921 return chunks.map(function (chunk) {
9922 // data?
9923 if (Buffer.isBuffer(chunk)) {
9924 var op = asMinimalOP(chunk)
9925 if (op === undefined) return chunk.toString('hex')
9926 chunk = op
9927 }
9928
9929 // opcode!
9930 return REVERSE_OPS[chunk]
9931 }).join(' ')
9932 }
9933
9934 function fromASM (asm) {
9935 typeforce(types.String, asm)
9936
9937 return compile(asm.split(' ').map(function (chunkStr) {
9938 // opcode?
9939 if (OPS[chunkStr] !== undefined) return OPS[chunkStr]
9940 typeforce(types.Hex, chunkStr)
9941
9942 // data!
9943 return Buffer.from(chunkStr, 'hex')
9944 }))
9945 }
9946
9947 function toStack (chunks) {
9948 chunks = decompile(chunks)
9949 typeforce(isPushOnly, chunks)
9950
9951 return chunks.map(function (op) {
9952 if (Buffer.isBuffer(op)) return op
9953 if (op === OPS.OP_0) return Buffer.allocUnsafe(0)
9954
9955 return scriptNumber.encode(op - OP_INT_BASE)
9956 })
9957 }
9958
9959 function isCanonicalPubKey (buffer) {
9960 if (!Buffer.isBuffer(buffer)) return false
9961 if (buffer.length < 33) return false
9962
9963 switch (buffer[0]) {
9964 case 0x02:
9965 case 0x03:
9966 return buffer.length === 33
9967 case 0x04:
9968 return buffer.length === 65
9969 }
9970
9971 return false
9972 }
9973
9974 function isDefinedHashType (hashType) {
9975 var hashTypeMod = hashType & ~0x80
9976
9977 // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE
9978 return hashTypeMod > 0x00 && hashTypeMod < 0x04
9979 }
9980
9981 function isCanonicalSignature (buffer) {
9982 if (!Buffer.isBuffer(buffer)) return false
9983 if (!isDefinedHashType(buffer[buffer.length - 1])) return false
9984
9985 return bip66.check(buffer.slice(0, -1))
9986 }
9987
9988 module.exports = {
9989 compile: compile,
9990 decompile: decompile,
9991 fromASM: fromASM,
9992 toASM: toASM,
9993 toStack: toStack,
9994
9995 number: require('./script_number'),
9996
9997 isCanonicalPubKey: isCanonicalPubKey,
9998 isCanonicalSignature: isCanonicalSignature,
9999 isPushOnly: isPushOnly,
10000 isDefinedHashType: isDefinedHashType
10001 }
10002
10003 },{"./script_number":55,"./types":80,"bip66":41,"bitcoin-ops":42,"bitcoin-ops/map":43,"pushdata-bitcoin":98,"safe-buffer":101,"typeforce":112}],55:[function(require,module,exports){
10004 var Buffer = require('safe-buffer').Buffer
10005
10006 function decode (buffer, maxLength, minimal) {
10007 maxLength = maxLength || 4
10008 minimal = minimal === undefined ? true : minimal
10009
10010 var length = buffer.length
10011 if (length === 0) return 0
10012 if (length > maxLength) throw new TypeError('Script number overflow')
10013 if (minimal) {
10014 if ((buffer[length - 1] & 0x7f) === 0) {
10015 if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number')
10016 }
10017 }
10018
10019 // 40-bit
10020 if (length === 5) {
10021 var a = buffer.readUInt32LE(0)
10022 var b = buffer.readUInt8(4)
10023
10024 if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a)
10025 return (b * 0x100000000) + a
10026 }
10027
10028 var result = 0
10029
10030 // 32-bit / 24-bit / 16-bit / 8-bit
10031 for (var i = 0; i < length; ++i) {
10032 result |= buffer[i] << (8 * i)
10033 }
10034
10035 if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1))))
10036 return result
10037 }
10038
10039 function scriptNumSize (i) {
10040 return i > 0x7fffffff ? 5
10041 : i > 0x7fffff ? 4
10042 : i > 0x7fff ? 3
10043 : i > 0x7f ? 2
10044 : i > 0x00 ? 1
10045 : 0
10046 }
10047
10048 function encode (number) {
10049 var value = Math.abs(number)
10050 var size = scriptNumSize(value)
10051 var buffer = Buffer.allocUnsafe(size)
10052 var negative = number < 0
10053
10054 for (var i = 0; i < size; ++i) {
10055 buffer.writeUInt8(value & 0xff, i)
10056 value >>= 8
10057 }
10058
10059 if (buffer[size - 1] & 0x80) {
10060 buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1)
10061 } else if (negative) {
10062 buffer[size - 1] |= 0x80
10063 }
10064
10065 return buffer
10066 }
10067
10068 module.exports = {
10069 decode: decode,
10070 encode: encode
10071 }
10072
10073 },{"safe-buffer":101}],56:[function(require,module,exports){
10074 var decompile = require('../script').decompile
10075 var multisig = require('./multisig')
10076 var nullData = require('./nulldata')
10077 var pubKey = require('./pubkey')
10078 var pubKeyHash = require('./pubkeyhash')
10079 var scriptHash = require('./scripthash')
10080 var witnessPubKeyHash = require('./witnesspubkeyhash')
10081 var witnessScriptHash = require('./witnessscripthash')
10082 var witnessCommitment = require('./witnesscommitment')
10083
10084 var types = {
10085 MULTISIG: 'multisig',
10086 NONSTANDARD: 'nonstandard',
10087 NULLDATA: 'nulldata',
10088 P2PK: 'pubkey',
10089 P2PKH: 'pubkeyhash',
10090 P2SH: 'scripthash',
10091 P2WPKH: 'witnesspubkeyhash',
10092 P2WSH: 'witnessscripthash',
10093 WITNESS_COMMITMENT: 'witnesscommitment'
10094 }
10095
10096 function classifyOutput (script) {
10097 if (witnessPubKeyHash.output.check(script)) return types.P2WPKH
10098 if (witnessScriptHash.output.check(script)) return types.P2WSH
10099 if (pubKeyHash.output.check(script)) return types.P2PKH
10100 if (scriptHash.output.check(script)) return types.P2SH
10101
10102 // XXX: optimization, below functions .decompile before use
10103 var chunks = decompile(script)
10104 if (multisig.output.check(chunks)) return types.MULTISIG
10105 if (pubKey.output.check(chunks)) return types.P2PK
10106 if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT
10107 if (nullData.output.check(chunks)) return types.NULLDATA
10108
10109 return types.NONSTANDARD
10110 }
10111
10112 function classifyInput (script, allowIncomplete) {
10113 // XXX: optimization, below functions .decompile before use
10114 var chunks = decompile(script)
10115
10116 if (pubKeyHash.input.check(chunks)) return types.P2PKH
10117 if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH
10118 if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG
10119 if (pubKey.input.check(chunks)) return types.P2PK
10120
10121 return types.NONSTANDARD
10122 }
10123
10124 function classifyWitness (script, allowIncomplete) {
10125 // XXX: optimization, below functions .decompile before use
10126 var chunks = decompile(script)
10127
10128 if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH
10129 if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH
10130
10131 return types.NONSTANDARD
10132 }
10133
10134 module.exports = {
10135 classifyInput: classifyInput,
10136 classifyOutput: classifyOutput,
10137 classifyWitness: classifyWitness,
10138 multisig: multisig,
10139 nullData: nullData,
10140 pubKey: pubKey,
10141 pubKeyHash: pubKeyHash,
10142 scriptHash: scriptHash,
10143 witnessPubKeyHash: witnessPubKeyHash,
10144 witnessScriptHash: witnessScriptHash,
10145 witnessCommitment: witnessCommitment,
10146 types: types
10147 }
10148
10149 },{"../script":54,"./multisig":57,"./nulldata":60,"./pubkey":61,"./pubkeyhash":64,"./scripthash":67,"./witnesscommitment":70,"./witnesspubkeyhash":72,"./witnessscripthash":75}],57:[function(require,module,exports){
10150 module.exports = {
10151 input: require('./input'),
10152 output: require('./output')
10153 }
10154
10155 },{"./input":58,"./output":59}],58:[function(require,module,exports){
10156 // OP_0 [signatures ...]
10157
10158 var Buffer = require('safe-buffer').Buffer
10159 var bscript = require('../../script')
10160 var p2mso = require('./output')
10161 var typeforce = require('typeforce')
10162 var OPS = require('bitcoin-ops')
10163
10164 function partialSignature (value) {
10165 return value === OPS.OP_0 || bscript.isCanonicalSignature(value)
10166 }
10167
10168 function check (script, allowIncomplete) {
10169 var chunks = bscript.decompile(script)
10170 if (chunks.length < 2) return false
10171 if (chunks[0] !== OPS.OP_0) return false
10172
10173 if (allowIncomplete) {
10174 return chunks.slice(1).every(partialSignature)
10175 }
10176
10177 return chunks.slice(1).every(bscript.isCanonicalSignature)
10178 }
10179 check.toJSON = function () { return 'multisig input' }
10180
10181 var EMPTY_BUFFER = Buffer.allocUnsafe(0)
10182
10183 function encodeStack (signatures, scriptPubKey) {
10184 typeforce([partialSignature], signatures)
10185
10186 if (scriptPubKey) {
10187 var scriptData = p2mso.decode(scriptPubKey)
10188
10189 if (signatures.length < scriptData.m) {
10190 throw new TypeError('Not enough signatures provided')
10191 }
10192
10193 if (signatures.length > scriptData.pubKeys.length) {
10194 throw new TypeError('Too many signatures provided')
10195 }
10196 }
10197
10198 return [].concat(EMPTY_BUFFER, signatures.map(function (sig) {
10199 if (sig === OPS.OP_0) {
10200 return EMPTY_BUFFER
10201 }
10202 return sig
10203 }))
10204 }
10205
10206 function encode (signatures, scriptPubKey) {
10207 return bscript.compile(encodeStack(signatures, scriptPubKey))
10208 }
10209
10210 function decodeStack (stack, allowIncomplete) {
10211 typeforce(typeforce.Array, stack)
10212 typeforce(check, stack, allowIncomplete)
10213 return stack.slice(1)
10214 }
10215
10216 function decode (buffer, allowIncomplete) {
10217 var stack = bscript.decompile(buffer)
10218 return decodeStack(stack, allowIncomplete)
10219 }
10220
10221 module.exports = {
10222 check: check,
10223 decode: decode,
10224 decodeStack: decodeStack,
10225 encode: encode,
10226 encodeStack: encodeStack
10227 }
10228
10229 },{"../../script":54,"./output":59,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],59:[function(require,module,exports){
10230 // m [pubKeys ...] n OP_CHECKMULTISIG
10231
10232 var bscript = require('../../script')
10233 var types = require('../../types')
10234 var typeforce = require('typeforce')
10235 var OPS = require('bitcoin-ops')
10236 var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
10237
10238 function check (script, allowIncomplete) {
10239 var chunks = bscript.decompile(script)
10240
10241 if (chunks.length < 4) return false
10242 if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false
10243 if (!types.Number(chunks[0])) return false
10244 if (!types.Number(chunks[chunks.length - 2])) return false
10245 var m = chunks[0] - OP_INT_BASE
10246 var n = chunks[chunks.length - 2] - OP_INT_BASE
10247
10248 if (m <= 0) return false
10249 if (n > 16) return false
10250 if (m > n) return false
10251 if (n !== chunks.length - 3) return false
10252 if (allowIncomplete) return true
10253
10254 var keys = chunks.slice(1, -2)
10255 return keys.every(bscript.isCanonicalPubKey)
10256 }
10257 check.toJSON = function () { return 'multi-sig output' }
10258
10259 function encode (m, pubKeys) {
10260 typeforce({
10261 m: types.Number,
10262 pubKeys: [bscript.isCanonicalPubKey]
10263 }, {
10264 m: m,
10265 pubKeys: pubKeys
10266 })
10267
10268 var n = pubKeys.length
10269 if (n < m) throw new TypeError('Not enough pubKeys provided')
10270
10271 return bscript.compile([].concat(
10272 OP_INT_BASE + m,
10273 pubKeys,
10274 OP_INT_BASE + n,
10275 OPS.OP_CHECKMULTISIG
10276 ))
10277 }
10278
10279 function decode (buffer, allowIncomplete) {
10280 var chunks = bscript.decompile(buffer)
10281 typeforce(check, chunks, allowIncomplete)
10282
10283 return {
10284 m: chunks[0] - OP_INT_BASE,
10285 pubKeys: chunks.slice(1, -2)
10286 }
10287 }
10288
10289 module.exports = {
10290 check: check,
10291 decode: decode,
10292 encode: encode
10293 }
10294
10295 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],60:[function(require,module,exports){
10296 // OP_RETURN {data}
10297
10298 var bscript = require('../script')
10299 var types = require('../types')
10300 var typeforce = require('typeforce')
10301 var OPS = require('bitcoin-ops')
10302
10303 function check (script) {
10304 var buffer = bscript.compile(script)
10305
10306 return buffer.length > 1 &&
10307 buffer[0] === OPS.OP_RETURN
10308 }
10309 check.toJSON = function () { return 'null data output' }
10310
10311 function encode (data) {
10312 typeforce(types.Buffer, data)
10313
10314 return bscript.compile([OPS.OP_RETURN, data])
10315 }
10316
10317 function decode (buffer) {
10318 typeforce(check, buffer)
10319
10320 return buffer.slice(2)
10321 }
10322
10323 module.exports = {
10324 output: {
10325 check: check,
10326 decode: decode,
10327 encode: encode
10328 }
10329 }
10330
10331 },{"../script":54,"../types":80,"bitcoin-ops":42,"typeforce":112}],61:[function(require,module,exports){
10332 arguments[4][57][0].apply(exports,arguments)
10333 },{"./input":62,"./output":63,"dup":57}],62:[function(require,module,exports){
10334 // {signature}
10335
10336 var bscript = require('../../script')
10337 var typeforce = require('typeforce')
10338
10339 function check (script) {
10340 var chunks = bscript.decompile(script)
10341
10342 return chunks.length === 1 &&
10343 bscript.isCanonicalSignature(chunks[0])
10344 }
10345 check.toJSON = function () { return 'pubKey input' }
10346
10347 function encodeStack (signature) {
10348 typeforce(bscript.isCanonicalSignature, signature)
10349 return [signature]
10350 }
10351
10352 function encode (signature) {
10353 return bscript.compile(encodeStack(signature))
10354 }
10355
10356 function decodeStack (stack) {
10357 typeforce(typeforce.Array, stack)
10358 typeforce(check, stack)
10359 return stack[0]
10360 }
10361
10362 function decode (buffer) {
10363 var stack = bscript.decompile(buffer)
10364 return decodeStack(stack)
10365 }
10366
10367 module.exports = {
10368 check: check,
10369 decode: decode,
10370 decodeStack: decodeStack,
10371 encode: encode,
10372 encodeStack: encodeStack
10373 }
10374
10375 },{"../../script":54,"typeforce":112}],63:[function(require,module,exports){
10376 // {pubKey} OP_CHECKSIG
10377
10378 var bscript = require('../../script')
10379 var typeforce = require('typeforce')
10380 var OPS = require('bitcoin-ops')
10381
10382 function check (script) {
10383 var chunks = bscript.decompile(script)
10384
10385 return chunks.length === 2 &&
10386 bscript.isCanonicalPubKey(chunks[0]) &&
10387 chunks[1] === OPS.OP_CHECKSIG
10388 }
10389 check.toJSON = function () { return 'pubKey output' }
10390
10391 function encode (pubKey) {
10392 typeforce(bscript.isCanonicalPubKey, pubKey)
10393
10394 return bscript.compile([pubKey, OPS.OP_CHECKSIG])
10395 }
10396
10397 function decode (buffer) {
10398 var chunks = bscript.decompile(buffer)
10399 typeforce(check, chunks)
10400
10401 return chunks[0]
10402 }
10403
10404 module.exports = {
10405 check: check,
10406 decode: decode,
10407 encode: encode
10408 }
10409
10410 },{"../../script":54,"bitcoin-ops":42,"typeforce":112}],64:[function(require,module,exports){
10411 arguments[4][57][0].apply(exports,arguments)
10412 },{"./input":65,"./output":66,"dup":57}],65:[function(require,module,exports){
10413 // {signature} {pubKey}
10414
10415 var bscript = require('../../script')
10416 var typeforce = require('typeforce')
10417
10418 function check (script) {
10419 var chunks = bscript.decompile(script)
10420
10421 return chunks.length === 2 &&
10422 bscript.isCanonicalSignature(chunks[0]) &&
10423 bscript.isCanonicalPubKey(chunks[1])
10424 }
10425 check.toJSON = function () { return 'pubKeyHash input' }
10426
10427 function encodeStack (signature, pubKey) {
10428 typeforce({
10429 signature: bscript.isCanonicalSignature,
10430 pubKey: bscript.isCanonicalPubKey
10431 }, {
10432 signature: signature,
10433 pubKey: pubKey
10434 })
10435
10436 return [signature, pubKey]
10437 }
10438
10439 function encode (signature, pubKey) {
10440 return bscript.compile(encodeStack(signature, pubKey))
10441 }
10442
10443 function decodeStack (stack) {
10444 typeforce(typeforce.Array, stack)
10445 typeforce(check, stack)
10446
10447 return {
10448 signature: stack[0],
10449 pubKey: stack[1]
10450 }
10451 }
10452
10453 function decode (buffer) {
10454 var stack = bscript.decompile(buffer)
10455 return decodeStack(stack)
10456 }
10457
10458 module.exports = {
10459 check: check,
10460 decode: decode,
10461 decodeStack: decodeStack,
10462 encode: encode,
10463 encodeStack: encodeStack
10464 }
10465
10466 },{"../../script":54,"typeforce":112}],66:[function(require,module,exports){
10467 // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
10468
10469 var bscript = require('../../script')
10470 var types = require('../../types')
10471 var typeforce = require('typeforce')
10472 var OPS = require('bitcoin-ops')
10473
10474 function check (script) {
10475 var buffer = bscript.compile(script)
10476
10477 return buffer.length === 25 &&
10478 buffer[0] === OPS.OP_DUP &&
10479 buffer[1] === OPS.OP_HASH160 &&
10480 buffer[2] === 0x14 &&
10481 buffer[23] === OPS.OP_EQUALVERIFY &&
10482 buffer[24] === OPS.OP_CHECKSIG
10483 }
10484 check.toJSON = function () { return 'pubKeyHash output' }
10485
10486 function encode (pubKeyHash) {
10487 typeforce(types.Hash160bit, pubKeyHash)
10488
10489 return bscript.compile([
10490 OPS.OP_DUP,
10491 OPS.OP_HASH160,
10492 pubKeyHash,
10493 OPS.OP_EQUALVERIFY,
10494 OPS.OP_CHECKSIG
10495 ])
10496 }
10497
10498 function decode (buffer) {
10499 typeforce(check, buffer)
10500
10501 return buffer.slice(3, 23)
10502 }
10503
10504 module.exports = {
10505 check: check,
10506 decode: decode,
10507 encode: encode
10508 }
10509
10510 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],67:[function(require,module,exports){
10511 arguments[4][57][0].apply(exports,arguments)
10512 },{"./input":68,"./output":69,"dup":57}],68:[function(require,module,exports){
10513 // <scriptSig> {serialized scriptPubKey script}
10514
10515 var Buffer = require('safe-buffer').Buffer
10516 var bscript = require('../../script')
10517 var typeforce = require('typeforce')
10518
10519 var p2ms = require('../multisig/')
10520 var p2pk = require('../pubkey/')
10521 var p2pkh = require('../pubkeyhash/')
10522 var p2wpkho = require('../witnesspubkeyhash/output')
10523 var p2wsho = require('../witnessscripthash/output')
10524
10525 function check (script, allowIncomplete) {
10526 var chunks = bscript.decompile(script)
10527 if (chunks.length < 1) return false
10528
10529 var lastChunk = chunks[chunks.length - 1]
10530 if (!Buffer.isBuffer(lastChunk)) return false
10531
10532 var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1)))
10533 var redeemScriptChunks = bscript.decompile(lastChunk)
10534
10535 // is redeemScript a valid script?
10536 if (redeemScriptChunks.length === 0) return false
10537
10538 // is redeemScriptSig push only?
10539 if (!bscript.isPushOnly(scriptSigChunks)) return false
10540
10541 // is witness?
10542 if (chunks.length === 1) {
10543 return p2wsho.check(redeemScriptChunks) ||
10544 p2wpkho.check(redeemScriptChunks)
10545 }
10546
10547 // match types
10548 if (p2pkh.input.check(scriptSigChunks) &&
10549 p2pkh.output.check(redeemScriptChunks)) return true
10550
10551 if (p2ms.input.check(scriptSigChunks, allowIncomplete) &&
10552 p2ms.output.check(redeemScriptChunks)) return true
10553
10554 if (p2pk.input.check(scriptSigChunks) &&
10555 p2pk.output.check(redeemScriptChunks)) return true
10556
10557 return false
10558 }
10559 check.toJSON = function () { return 'scriptHash input' }
10560
10561 function encodeStack (redeemScriptStack, redeemScript) {
10562 var serializedScriptPubKey = bscript.compile(redeemScript)
10563
10564 return [].concat(redeemScriptStack, serializedScriptPubKey)
10565 }
10566
10567 function encode (redeemScriptSig, redeemScript) {
10568 var redeemScriptStack = bscript.decompile(redeemScriptSig)
10569
10570 return bscript.compile(encodeStack(redeemScriptStack, redeemScript))
10571 }
10572
10573 function decodeStack (stack) {
10574 typeforce(typeforce.Array, stack)
10575 typeforce(check, stack)
10576
10577 return {
10578 redeemScriptStack: stack.slice(0, -1),
10579 redeemScript: stack[stack.length - 1]
10580 }
10581 }
10582
10583 function decode (buffer) {
10584 var stack = bscript.decompile(buffer)
10585 var result = decodeStack(stack)
10586 result.redeemScriptSig = bscript.compile(result.redeemScriptStack)
10587 delete result.redeemScriptStack
10588 return result
10589 }
10590
10591 module.exports = {
10592 check: check,
10593 decode: decode,
10594 decodeStack: decodeStack,
10595 encode: encode,
10596 encodeStack: encodeStack
10597 }
10598
10599 },{"../../script":54,"../multisig/":57,"../pubkey/":61,"../pubkeyhash/":64,"../witnesspubkeyhash/output":74,"../witnessscripthash/output":77,"safe-buffer":101,"typeforce":112}],69:[function(require,module,exports){
10600 // OP_HASH160 {scriptHash} OP_EQUAL
10601
10602 var bscript = require('../../script')
10603 var types = require('../../types')
10604 var typeforce = require('typeforce')
10605 var OPS = require('bitcoin-ops')
10606
10607 function check (script) {
10608 var buffer = bscript.compile(script)
10609
10610 return buffer.length === 23 &&
10611 buffer[0] === OPS.OP_HASH160 &&
10612 buffer[1] === 0x14 &&
10613 buffer[22] === OPS.OP_EQUAL
10614 }
10615 check.toJSON = function () { return 'scriptHash output' }
10616
10617 function encode (scriptHash) {
10618 typeforce(types.Hash160bit, scriptHash)
10619
10620 return bscript.compile([OPS.OP_HASH160, scriptHash, OPS.OP_EQUAL])
10621 }
10622
10623 function decode (buffer) {
10624 typeforce(check, buffer)
10625
10626 return buffer.slice(2, 22)
10627 }
10628
10629 module.exports = {
10630 check: check,
10631 decode: decode,
10632 encode: encode
10633 }
10634
10635 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],70:[function(require,module,exports){
10636 module.exports = {
10637 output: require('./output')
10638 }
10639
10640 },{"./output":71}],71:[function(require,module,exports){
10641 // OP_RETURN {aa21a9ed} {commitment}
10642
10643 var Buffer = require('safe-buffer').Buffer
10644 var bscript = require('../../script')
10645 var types = require('../../types')
10646 var typeforce = require('typeforce')
10647 var OPS = require('bitcoin-ops')
10648
10649 var HEADER = Buffer.from('aa21a9ed', 'hex')
10650
10651 function check (script) {
10652 var buffer = bscript.compile(script)
10653
10654 return buffer.length > 37 &&
10655 buffer[0] === OPS.OP_RETURN &&
10656 buffer[1] === 0x24 &&
10657 buffer.slice(2, 6).equals(HEADER)
10658 }
10659
10660 check.toJSON = function () { return 'Witness commitment output' }
10661
10662 function encode (commitment) {
10663 typeforce(types.Hash256bit, commitment)
10664
10665 var buffer = Buffer.allocUnsafe(36)
10666 HEADER.copy(buffer, 0)
10667 commitment.copy(buffer, 4)
10668
10669 return bscript.compile([OPS.OP_RETURN, buffer])
10670 }
10671
10672 function decode (buffer) {
10673 typeforce(check, buffer)
10674
10675 return bscript.decompile(buffer)[1].slice(4, 36)
10676 }
10677
10678 module.exports = {
10679 check: check,
10680 decode: decode,
10681 encode: encode
10682 }
10683
10684 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],72:[function(require,module,exports){
10685 arguments[4][57][0].apply(exports,arguments)
10686 },{"./input":73,"./output":74,"dup":57}],73:[function(require,module,exports){
10687 // {signature} {pubKey}
10688
10689 var bscript = require('../../script')
10690 var typeforce = require('typeforce')
10691
10692 function isCompressedCanonicalPubKey (pubKey) {
10693 return bscript.isCanonicalPubKey(pubKey) && pubKey.length === 33
10694 }
10695
10696 function check (script) {
10697 var chunks = bscript.decompile(script)
10698
10699 return chunks.length === 2 &&
10700 bscript.isCanonicalSignature(chunks[0]) &&
10701 isCompressedCanonicalPubKey(chunks[1])
10702 }
10703 check.toJSON = function () { return 'witnessPubKeyHash input' }
10704
10705 function encodeStack (signature, pubKey) {
10706 typeforce({
10707 signature: bscript.isCanonicalSignature,
10708 pubKey: isCompressedCanonicalPubKey
10709 }, {
10710 signature: signature,
10711 pubKey: pubKey
10712 })
10713
10714 return [signature, pubKey]
10715 }
10716
10717 function decodeStack (stack) {
10718 typeforce(typeforce.Array, stack)
10719 typeforce(check, stack)
10720
10721 return {
10722 signature: stack[0],
10723 pubKey: stack[1]
10724 }
10725 }
10726
10727 module.exports = {
10728 check: check,
10729 decodeStack: decodeStack,
10730 encodeStack: encodeStack
10731 }
10732
10733 },{"../../script":54,"typeforce":112}],74:[function(require,module,exports){
10734 // OP_0 {pubKeyHash}
10735
10736 var bscript = require('../../script')
10737 var types = require('../../types')
10738 var typeforce = require('typeforce')
10739 var OPS = require('bitcoin-ops')
10740
10741 function check (script) {
10742 var buffer = bscript.compile(script)
10743
10744 return buffer.length === 22 &&
10745 buffer[0] === OPS.OP_0 &&
10746 buffer[1] === 0x14
10747 }
10748 check.toJSON = function () { return 'Witness pubKeyHash output' }
10749
10750 function encode (pubKeyHash) {
10751 typeforce(types.Hash160bit, pubKeyHash)
10752
10753 return bscript.compile([OPS.OP_0, pubKeyHash])
10754 }
10755
10756 function decode (buffer) {
10757 typeforce(check, buffer)
10758
10759 return buffer.slice(2)
10760 }
10761
10762 module.exports = {
10763 check: check,
10764 decode: decode,
10765 encode: encode
10766 }
10767
10768 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],75:[function(require,module,exports){
10769 arguments[4][57][0].apply(exports,arguments)
10770 },{"./input":76,"./output":77,"dup":57}],76:[function(require,module,exports){
10771 (function (Buffer){
10772 // <scriptSig> {serialized scriptPubKey script}
10773
10774 var bscript = require('../../script')
10775 var types = require('../../types')
10776 var typeforce = require('typeforce')
10777
10778 var p2ms = require('../multisig/')
10779 var p2pk = require('../pubkey/')
10780 var p2pkh = require('../pubkeyhash/')
10781
10782 function check (chunks, allowIncomplete) {
10783 typeforce(types.Array, chunks)
10784 if (chunks.length < 1) return false
10785
10786 var witnessScript = chunks[chunks.length - 1]
10787 if (!Buffer.isBuffer(witnessScript)) return false
10788
10789 var witnessScriptChunks = bscript.decompile(witnessScript)
10790
10791 // is witnessScript a valid script?
10792 if (witnessScriptChunks.length === 0) return false
10793
10794 var witnessRawScriptSig = bscript.compile(chunks.slice(0, -1))
10795
10796 // match types
10797 if (p2pkh.input.check(witnessRawScriptSig) &&
10798 p2pkh.output.check(witnessScriptChunks)) return true
10799
10800 if (p2ms.input.check(witnessRawScriptSig, allowIncomplete) &&
10801 p2ms.output.check(witnessScriptChunks)) return true
10802
10803 if (p2pk.input.check(witnessRawScriptSig) &&
10804 p2pk.output.check(witnessScriptChunks)) return true
10805
10806 return false
10807 }
10808 check.toJSON = function () { return 'witnessScriptHash input' }
10809
10810 function encodeStack (witnessData, witnessScript) {
10811 typeforce({
10812 witnessData: [types.Buffer],
10813 witnessScript: types.Buffer
10814 }, {
10815 witnessData: witnessData,
10816 witnessScript: witnessScript
10817 })
10818
10819 return [].concat(witnessData, witnessScript)
10820 }
10821
10822 function decodeStack (stack) {
10823 typeforce(typeforce.Array, stack)
10824 typeforce(check, stack)
10825 return {
10826 witnessData: stack.slice(0, -1),
10827 witnessScript: stack[stack.length - 1]
10828 }
10829 }
10830
10831 module.exports = {
10832 check: check,
10833 decodeStack: decodeStack,
10834 encodeStack: encodeStack
10835 }
10836
10837 }).call(this,{"isBuffer":require("../../../../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
10838 },{"../../../../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":10,"../../script":54,"../../types":80,"../multisig/":57,"../pubkey/":61,"../pubkeyhash/":64,"typeforce":112}],77:[function(require,module,exports){
10839 // OP_0 {scriptHash}
10840
10841 var bscript = require('../../script')
10842 var types = require('../../types')
10843 var typeforce = require('typeforce')
10844 var OPS = require('bitcoin-ops')
10845
10846 function check (script) {
10847 var buffer = bscript.compile(script)
10848
10849 return buffer.length === 34 &&
10850 buffer[0] === OPS.OP_0 &&
10851 buffer[1] === 0x20
10852 }
10853 check.toJSON = function () { return 'Witness scriptHash output' }
10854
10855 function encode (scriptHash) {
10856 typeforce(types.Hash256bit, scriptHash)
10857
10858 return bscript.compile([OPS.OP_0, scriptHash])
10859 }
10860
10861 function decode (buffer) {
10862 typeforce(check, buffer)
10863
10864 return buffer.slice(2)
10865 }
10866
10867 module.exports = {
10868 check: check,
10869 decode: decode,
10870 encode: encode
10871 }
10872
10873 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],78:[function(require,module,exports){
10874 var Buffer = require('safe-buffer').Buffer
10875 var bcrypto = require('./crypto')
10876 var bscript = require('./script')
10877 var bufferutils = require('./bufferutils')
10878 var opcodes = require('bitcoin-ops')
10879 var typeforce = require('typeforce')
10880 var types = require('./types')
10881 var varuint = require('varuint-bitcoin')
10882
10883 function varSliceSize (someScript) {
10884 var length = someScript.length
10885
10886 return varuint.encodingLength(length) + length
10887 }
10888
10889 function vectorSize (someVector) {
10890 var length = someVector.length
10891
10892 return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) {
10893 return sum + varSliceSize(witness)
10894 }, 0)
10895 }
10896
10897 function Transaction () {
10898 this.version = 1
10899 this.locktime = 0
10900 this.ins = []
10901 this.outs = []
10902 }
10903
10904 Transaction.DEFAULT_SEQUENCE = 0xffffffff
10905 Transaction.SIGHASH_ALL = 0x01
10906 Transaction.SIGHASH_NONE = 0x02
10907 Transaction.SIGHASH_SINGLE = 0x03
10908 Transaction.SIGHASH_ANYONECANPAY = 0x80
10909 Transaction.ADVANCED_TRANSACTION_MARKER = 0x00
10910 Transaction.ADVANCED_TRANSACTION_FLAG = 0x01
10911
10912 var EMPTY_SCRIPT = Buffer.allocUnsafe(0)
10913 var EMPTY_WITNESS = []
10914 var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
10915 var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
10916 var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex')
10917 var BLANK_OUTPUT = {
10918 script: EMPTY_SCRIPT,
10919 valueBuffer: VALUE_UINT64_MAX
10920 }
10921
10922 Transaction.fromBuffer = function (buffer, __noStrict) {
10923 var offset = 0
10924 function readSlice (n) {
10925 offset += n
10926 return buffer.slice(offset - n, offset)
10927 }
10928
10929 function readUInt32 () {
10930 var i = buffer.readUInt32LE(offset)
10931 offset += 4
10932 return i
10933 }
10934
10935 function readInt32 () {
10936 var i = buffer.readInt32LE(offset)
10937 offset += 4
10938 return i
10939 }
10940
10941 function readUInt64 () {
10942 var i = bufferutils.readUInt64LE(buffer, offset)
10943 offset += 8
10944 return i
10945 }
10946
10947 function readVarInt () {
10948 var vi = varuint.decode(buffer, offset)
10949 offset += varuint.decode.bytes
10950 return vi
10951 }
10952
10953 function readVarSlice () {
10954 return readSlice(readVarInt())
10955 }
10956
10957 function readVector () {
10958 var count = readVarInt()
10959 var vector = []
10960 for (var i = 0; i < count; i++) vector.push(readVarSlice())
10961 return vector
10962 }
10963
10964 var tx = new Transaction()
10965 tx.version = readInt32()
10966
10967 var marker = buffer.readUInt8(offset)
10968 var flag = buffer.readUInt8(offset + 1)
10969
10970 var hasWitnesses = false
10971 if (marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
10972 flag === Transaction.ADVANCED_TRANSACTION_FLAG) {
10973 offset += 2
10974 hasWitnesses = true
10975 }
10976
10977 var vinLen = readVarInt()
10978 for (var i = 0; i < vinLen; ++i) {
10979 tx.ins.push({
10980 hash: readSlice(32),
10981 index: readUInt32(),
10982 script: readVarSlice(),
10983 sequence: readUInt32(),
10984 witness: EMPTY_WITNESS
10985 })
10986 }
10987
10988 var voutLen = readVarInt()
10989 for (i = 0; i < voutLen; ++i) {
10990 tx.outs.push({
10991 value: readUInt64(),
10992 script: readVarSlice()
10993 })
10994 }
10995
10996 if (hasWitnesses) {
10997 for (i = 0; i < vinLen; ++i) {
10998 tx.ins[i].witness = readVector()
10999 }
11000
11001 // was this pointless?
11002 if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
11003 }
11004
11005 tx.locktime = readUInt32()
11006
11007 if (__noStrict) return tx
11008 if (offset !== buffer.length) throw new Error('Transaction has unexpected data')
11009
11010 return tx
11011 }
11012
11013 Transaction.fromHex = function (hex) {
11014 return Transaction.fromBuffer(Buffer.from(hex, 'hex'))
11015 }
11016
11017 Transaction.isCoinbaseHash = function (buffer) {
11018 typeforce(types.Hash256bit, buffer)
11019 for (var i = 0; i < 32; ++i) {
11020 if (buffer[i] !== 0) return false
11021 }
11022 return true
11023 }
11024
11025 Transaction.prototype.isCoinbase = function () {
11026 return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
11027 }
11028
11029 Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) {
11030 typeforce(types.tuple(
11031 types.Hash256bit,
11032 types.UInt32,
11033 types.maybe(types.UInt32),
11034 types.maybe(types.Buffer)
11035 ), arguments)
11036
11037 if (types.Null(sequence)) {
11038 sequence = Transaction.DEFAULT_SEQUENCE
11039 }
11040
11041 // Add the input and return the input's index
11042 return (this.ins.push({
11043 hash: hash,
11044 index: index,
11045 script: scriptSig || EMPTY_SCRIPT,
11046 sequence: sequence,
11047 witness: EMPTY_WITNESS
11048 }) - 1)
11049 }
11050
11051 Transaction.prototype.addOutput = function (scriptPubKey, value) {
11052 typeforce(types.tuple(types.Buffer, types.Satoshi), arguments)
11053
11054 // Add the output and return the output's index
11055 return (this.outs.push({
11056 script: scriptPubKey,
11057 value: value
11058 }) - 1)
11059 }
11060
11061 Transaction.prototype.hasWitnesses = function () {
11062 return this.ins.some(function (x) {
11063 return x.witness.length !== 0
11064 })
11065 }
11066
11067 Transaction.prototype.weight = function () {
11068 var base = this.__byteLength(false)
11069 var total = this.__byteLength(true)
11070 return base * 3 + total
11071 }
11072
11073 Transaction.prototype.virtualSize = function () {
11074 return Math.ceil(this.weight() / 4)
11075 }
11076
11077 Transaction.prototype.byteLength = function () {
11078 return this.__byteLength(true)
11079 }
11080
11081 Transaction.prototype.__byteLength = function (__allowWitness) {
11082 var hasWitnesses = __allowWitness && this.hasWitnesses()
11083
11084 return (
11085 (hasWitnesses ? 10 : 8) +
11086 varuint.encodingLength(this.ins.length) +
11087 varuint.encodingLength(this.outs.length) +
11088 this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) +
11089 this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) +
11090 (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0)
11091 )
11092 }
11093
11094 Transaction.prototype.clone = function () {
11095 var newTx = new Transaction()
11096 newTx.version = this.version
11097 newTx.locktime = this.locktime
11098
11099 newTx.ins = this.ins.map(function (txIn) {
11100 return {
11101 hash: txIn.hash,
11102 index: txIn.index,
11103 script: txIn.script,
11104 sequence: txIn.sequence,
11105 witness: txIn.witness
11106 }
11107 })
11108
11109 newTx.outs = this.outs.map(function (txOut) {
11110 return {
11111 script: txOut.script,
11112 value: txOut.value
11113 }
11114 })
11115
11116 return newTx
11117 }
11118
11119 /**
11120 * Hash transaction for signing a specific input.
11121 *
11122 * Bitcoin uses a different hash for each signed transaction input.
11123 * This method copies the transaction, makes the necessary changes based on the
11124 * hashType, and then hashes the result.
11125 * This hash can then be used to sign the provided transaction input.
11126 */
11127 Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
11128 typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)
11129
11130 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
11131 if (inIndex >= this.ins.length) return ONE
11132
11133 // ignore OP_CODESEPARATOR
11134 var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) {
11135 return x !== opcodes.OP_CODESEPARATOR
11136 }))
11137
11138 var txTmp = this.clone()
11139
11140 // SIGHASH_NONE: ignore all outputs? (wildcard payee)
11141 if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
11142 txTmp.outs = []
11143
11144 // ignore sequence numbers (except at inIndex)
11145 txTmp.ins.forEach(function (input, i) {
11146 if (i === inIndex) return
11147
11148 input.sequence = 0
11149 })
11150
11151 // SIGHASH_SINGLE: ignore all outputs, except at the same index?
11152 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
11153 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
11154 if (inIndex >= this.outs.length) return ONE
11155
11156 // truncate outputs after
11157 txTmp.outs.length = inIndex + 1
11158
11159 // "blank" outputs before
11160 for (var i = 0; i < inIndex; i++) {
11161 txTmp.outs[i] = BLANK_OUTPUT
11162 }
11163
11164 // ignore sequence numbers (except at inIndex)
11165 txTmp.ins.forEach(function (input, y) {
11166 if (y === inIndex) return
11167
11168 input.sequence = 0
11169 })
11170 }
11171
11172 // SIGHASH_ANYONECANPAY: ignore inputs entirely?
11173 if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
11174 txTmp.ins = [txTmp.ins[inIndex]]
11175 txTmp.ins[0].script = ourScript
11176
11177 // SIGHASH_ALL: only ignore input scripts
11178 } else {
11179 // "blank" others input scripts
11180 txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT })
11181 txTmp.ins[inIndex].script = ourScript
11182 }
11183
11184 // serialize and hash
11185 var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4)
11186 buffer.writeInt32LE(hashType, buffer.length - 4)
11187 txTmp.__toBuffer(buffer, 0, false)
11188
11189 return bcrypto.hash256(buffer)
11190 }
11191
11192 Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) {
11193 typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments)
11194
11195 var tbuffer, toffset
11196 function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) }
11197 function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) }
11198 function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) }
11199 function writeVarInt (i) {
11200 varuint.encode(i, tbuffer, toffset)
11201 toffset += varuint.encode.bytes
11202 }
11203 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
11204
11205 var hashOutputs = ZERO
11206 var hashPrevouts = ZERO
11207 var hashSequence = ZERO
11208
11209 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) {
11210 tbuffer = Buffer.allocUnsafe(36 * this.ins.length)
11211 toffset = 0
11212
11213 this.ins.forEach(function (txIn) {
11214 writeSlice(txIn.hash)
11215 writeUInt32(txIn.index)
11216 })
11217
11218 hashPrevouts = bcrypto.hash256(tbuffer)
11219 }
11220
11221 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) &&
11222 (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
11223 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
11224 tbuffer = Buffer.allocUnsafe(4 * this.ins.length)
11225 toffset = 0
11226
11227 this.ins.forEach(function (txIn) {
11228 writeUInt32(txIn.sequence)
11229 })
11230
11231 hashSequence = bcrypto.hash256(tbuffer)
11232 }
11233
11234 if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
11235 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
11236 var txOutsSize = this.outs.reduce(function (sum, output) {
11237 return sum + 8 + varSliceSize(output.script)
11238 }, 0)
11239
11240 tbuffer = Buffer.allocUnsafe(txOutsSize)
11241 toffset = 0
11242
11243 this.outs.forEach(function (out) {
11244 writeUInt64(out.value)
11245 writeVarSlice(out.script)
11246 })
11247
11248 hashOutputs = bcrypto.hash256(tbuffer)
11249 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) {
11250 var output = this.outs[inIndex]
11251
11252 tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script))
11253 toffset = 0
11254 writeUInt64(output.value)
11255 writeVarSlice(output.script)
11256
11257 hashOutputs = bcrypto.hash256(tbuffer)
11258 }
11259
11260 tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript))
11261 toffset = 0
11262
11263 var input = this.ins[inIndex]
11264 writeUInt32(this.version)
11265 writeSlice(hashPrevouts)
11266 writeSlice(hashSequence)
11267 writeSlice(input.hash)
11268 writeUInt32(input.index)
11269 writeVarSlice(prevOutScript)
11270 writeUInt64(value)
11271 writeUInt32(input.sequence)
11272 writeSlice(hashOutputs)
11273 writeUInt32(this.locktime)
11274 writeUInt32(hashType)
11275 return bcrypto.hash256(tbuffer)
11276 }
11277
11278 Transaction.prototype.getHash = function () {
11279 return bcrypto.hash256(this.__toBuffer(undefined, undefined, false))
11280 }
11281
11282 Transaction.prototype.getId = function () {
11283 // transaction hash's are displayed in reverse order
11284 return this.getHash().reverse().toString('hex')
11285 }
11286
11287 Transaction.prototype.toBuffer = function (buffer, initialOffset) {
11288 return this.__toBuffer(buffer, initialOffset, true)
11289 }
11290
11291 Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) {
11292 if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness))
11293
11294 var offset = initialOffset || 0
11295 function writeSlice (slice) { offset += slice.copy(buffer, offset) }
11296 function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) }
11297 function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) }
11298 function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) }
11299 function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) }
11300 function writeVarInt (i) {
11301 varuint.encode(i, buffer, offset)
11302 offset += varuint.encode.bytes
11303 }
11304 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
11305 function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) }
11306
11307 writeInt32(this.version)
11308
11309 var hasWitnesses = __allowWitness && this.hasWitnesses()
11310
11311 if (hasWitnesses) {
11312 writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER)
11313 writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG)
11314 }
11315
11316 writeVarInt(this.ins.length)
11317
11318 this.ins.forEach(function (txIn) {
11319 writeSlice(txIn.hash)
11320 writeUInt32(txIn.index)
11321 writeVarSlice(txIn.script)
11322 writeUInt32(txIn.sequence)
11323 })
11324
11325 writeVarInt(this.outs.length)
11326 this.outs.forEach(function (txOut) {
11327 if (!txOut.valueBuffer) {
11328 writeUInt64(txOut.value)
11329 } else {
11330 writeSlice(txOut.valueBuffer)
11331 }
11332
11333 writeVarSlice(txOut.script)
11334 })
11335
11336 if (hasWitnesses) {
11337 this.ins.forEach(function (input) {
11338 writeVector(input.witness)
11339 })
11340 }
11341
11342 writeUInt32(this.locktime)
11343
11344 // avoid slicing unless necessary
11345 if (initialOffset !== undefined) return buffer.slice(initialOffset, offset)
11346 return buffer
11347 }
11348
11349 Transaction.prototype.toHex = function () {
11350 return this.toBuffer().toString('hex')
11351 }
11352
11353 Transaction.prototype.setInputScript = function (index, scriptSig) {
11354 typeforce(types.tuple(types.Number, types.Buffer), arguments)
11355
11356 this.ins[index].script = scriptSig
11357 }
11358
11359 Transaction.prototype.setWitness = function (index, witness) {
11360 typeforce(types.tuple(types.Number, [types.Buffer]), arguments)
11361
11362 this.ins[index].witness = witness
11363 }
11364
11365 module.exports = Transaction
11366
11367 },{"./bufferutils":46,"./crypto":47,"./script":54,"./types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112,"varuint-bitcoin":114}],79:[function(require,module,exports){
11368 var Buffer = require('safe-buffer').Buffer
11369 var baddress = require('./address')
11370 var bcrypto = require('./crypto')
11371 var bscript = require('./script')
11372 var btemplates = require('./templates')
11373 var networks = require('./networks')
11374 var ops = require('bitcoin-ops')
11375 var typeforce = require('typeforce')
11376 var types = require('./types')
11377 var scriptTypes = btemplates.types
11378 var SIGNABLE = [btemplates.types.P2PKH, btemplates.types.P2PK, btemplates.types.MULTISIG]
11379 var P2SH = SIGNABLE.concat([btemplates.types.P2WPKH, btemplates.types.P2WSH])
11380
11381 var ECPair = require('./ecpair')
11382 var ECSignature = require('./ecsignature')
11383 var Transaction = require('./transaction')
11384
11385 function supportedType (type) {
11386 return SIGNABLE.indexOf(type) !== -1
11387 }
11388
11389 function supportedP2SHType (type) {
11390 return P2SH.indexOf(type) !== -1
11391 }
11392
11393 function extractChunks (type, chunks, script) {
11394 var pubKeys = []
11395 var signatures = []
11396 switch (type) {
11397 case scriptTypes.P2PKH:
11398 // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')
11399 pubKeys = chunks.slice(1)
11400 signatures = chunks.slice(0, 1)
11401 break
11402
11403 case scriptTypes.P2PK:
11404 pubKeys[0] = script ? btemplates.pubKey.output.decode(script) : undefined
11405 signatures = chunks.slice(0, 1)
11406 break
11407
11408 case scriptTypes.MULTISIG:
11409 if (script) {
11410 var multisig = btemplates.multisig.output.decode(script)
11411 pubKeys = multisig.pubKeys
11412 }
11413
11414 signatures = chunks.slice(1).map(function (chunk) {
11415 return chunk.length === 0 ? undefined : chunk
11416 })
11417 break
11418 }
11419
11420 return {
11421 pubKeys: pubKeys,
11422 signatures: signatures
11423 }
11424 }
11425 function expandInput (scriptSig, witnessStack) {
11426 if (scriptSig.length === 0 && witnessStack.length === 0) return {}
11427
11428 var prevOutScript
11429 var prevOutType
11430 var scriptType
11431 var script
11432 var redeemScript
11433 var witnessScript
11434 var witnessScriptType
11435 var redeemScriptType
11436 var witness = false
11437 var p2wsh = false
11438 var p2sh = false
11439 var witnessProgram
11440 var chunks
11441
11442 var scriptSigChunks = bscript.decompile(scriptSig)
11443 var sigType = btemplates.classifyInput(scriptSigChunks, true)
11444 if (sigType === scriptTypes.P2SH) {
11445 p2sh = true
11446 redeemScript = scriptSigChunks[scriptSigChunks.length - 1]
11447 redeemScriptType = btemplates.classifyOutput(redeemScript)
11448 prevOutScript = btemplates.scriptHash.output.encode(bcrypto.hash160(redeemScript))
11449 prevOutType = scriptTypes.P2SH
11450 script = redeemScript
11451 }
11452
11453 var classifyWitness = btemplates.classifyWitness(witnessStack, true)
11454 if (classifyWitness === scriptTypes.P2WSH) {
11455 witnessScript = witnessStack[witnessStack.length - 1]
11456 witnessScriptType = btemplates.classifyOutput(witnessScript)
11457 p2wsh = true
11458 witness = true
11459 if (scriptSig.length === 0) {
11460 prevOutScript = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
11461 prevOutType = scriptTypes.P2WSH
11462 if (redeemScript !== undefined) {
11463 throw new Error('Redeem script given when unnecessary')
11464 }
11465 // bare witness
11466 } else {
11467 if (!redeemScript) {
11468 throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty')
11469 }
11470 witnessProgram = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
11471 if (!redeemScript.equals(witnessProgram)) {
11472 throw new Error('Redeem script didn\'t match witnessScript')
11473 }
11474 }
11475
11476 if (!supportedType(btemplates.classifyOutput(witnessScript))) {
11477 throw new Error('unsupported witness script')
11478 }
11479
11480 script = witnessScript
11481 scriptType = witnessScriptType
11482 chunks = witnessStack.slice(0, -1)
11483 } else if (classifyWitness === scriptTypes.P2WPKH) {
11484 witness = true
11485 var key = witnessStack[witnessStack.length - 1]
11486 var keyHash = bcrypto.hash160(key)
11487 if (scriptSig.length === 0) {
11488 prevOutScript = btemplates.witnessPubKeyHash.output.encode(keyHash)
11489 prevOutType = scriptTypes.P2WPKH
11490 if (typeof redeemScript !== 'undefined') {
11491 throw new Error('Redeem script given when unnecessary')
11492 }
11493 } else {
11494 if (!redeemScript) {
11495 throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty')
11496 }
11497 witnessProgram = btemplates.witnessPubKeyHash.output.encode(keyHash)
11498 if (!redeemScript.equals(witnessProgram)) {
11499 throw new Error('Redeem script did not have the right witness program')
11500 }
11501 }
11502
11503 scriptType = scriptTypes.P2PKH
11504 chunks = witnessStack
11505 } else if (redeemScript) {
11506 if (!supportedP2SHType(redeemScriptType)) {
11507 throw new Error('Bad redeemscript!')
11508 }
11509
11510 script = redeemScript
11511 scriptType = redeemScriptType
11512 chunks = scriptSigChunks.slice(0, -1)
11513 } else {
11514 prevOutType = scriptType = btemplates.classifyInput(scriptSig)
11515 chunks = scriptSigChunks
11516 }
11517
11518 var expanded = extractChunks(scriptType, chunks, script)
11519
11520 var result = {
11521 pubKeys: expanded.pubKeys,
11522 signatures: expanded.signatures,
11523 prevOutScript: prevOutScript,
11524 prevOutType: prevOutType,
11525 signType: scriptType,
11526 signScript: script,
11527 witness: Boolean(witness)
11528 }
11529
11530 if (p2sh) {
11531 result.redeemScript = redeemScript
11532 result.redeemScriptType = redeemScriptType
11533 }
11534
11535 if (p2wsh) {
11536 result.witnessScript = witnessScript
11537 result.witnessScriptType = witnessScriptType
11538 }
11539
11540 return result
11541 }
11542
11543 // could be done in expandInput, but requires the original Transaction for hashForSignature
11544 function fixMultisigOrder (input, transaction, vin) {
11545 if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return
11546 if (input.pubKeys.length === input.signatures.length) return
11547
11548 var unmatched = input.signatures.concat()
11549
11550 input.signatures = input.pubKeys.map(function (pubKey) {
11551 var keyPair = ECPair.fromPublicKeyBuffer(pubKey)
11552 var match
11553
11554 // check for a signature
11555 unmatched.some(function (signature, i) {
11556 // skip if undefined || OP_0
11557 if (!signature) return false
11558
11559 // TODO: avoid O(n) hashForSignature
11560 var parsed = ECSignature.parseScriptSignature(signature)
11561 var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType)
11562
11563 // skip if signature does not match pubKey
11564 if (!keyPair.verify(hash, parsed.signature)) return false
11565
11566 // remove matched signature from unmatched
11567 unmatched[i] = undefined
11568 match = signature
11569
11570 return true
11571 })
11572
11573 return match
11574 })
11575 }
11576
11577 function expandOutput (script, scriptType, ourPubKey) {
11578 typeforce(types.Buffer, script)
11579
11580 var scriptChunks = bscript.decompile(script)
11581 if (!scriptType) {
11582 scriptType = btemplates.classifyOutput(script)
11583 }
11584
11585 var pubKeys = []
11586
11587 switch (scriptType) {
11588 // does our hash160(pubKey) match the output scripts?
11589 case scriptTypes.P2PKH:
11590 if (!ourPubKey) break
11591
11592 var pkh1 = scriptChunks[2]
11593 var pkh2 = bcrypto.hash160(ourPubKey)
11594 if (pkh1.equals(pkh2)) pubKeys = [ourPubKey]
11595 break
11596
11597 // does our hash160(pubKey) match the output scripts?
11598 case scriptTypes.P2WPKH:
11599 if (!ourPubKey) break
11600
11601 var wpkh1 = scriptChunks[1]
11602 var wpkh2 = bcrypto.hash160(ourPubKey)
11603 if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey]
11604 break
11605
11606 case scriptTypes.P2PK:
11607 pubKeys = scriptChunks.slice(0, 1)
11608 break
11609
11610 case scriptTypes.MULTISIG:
11611 pubKeys = scriptChunks.slice(1, -2)
11612 break
11613
11614 default: return { scriptType: scriptType }
11615 }
11616
11617 return {
11618 pubKeys: pubKeys,
11619 scriptType: scriptType,
11620 signatures: pubKeys.map(function () { return undefined })
11621 }
11622 }
11623
11624 function checkP2SHInput (input, redeemScriptHash) {
11625 if (input.prevOutType) {
11626 if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH')
11627
11628 var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1]
11629 if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)')
11630 }
11631 }
11632
11633 function checkP2WSHInput (input, witnessScriptHash) {
11634 if (input.prevOutType) {
11635 if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH')
11636
11637 var scriptHash = bscript.decompile(input.prevOutScript)[1]
11638 if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)')
11639 }
11640 }
11641
11642 function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) {
11643 var expanded
11644 var prevOutType
11645 var prevOutScript
11646
11647 var p2sh = false
11648 var p2shType
11649 var redeemScriptHash
11650
11651 var witness = false
11652 var p2wsh = false
11653 var witnessType
11654 var witnessScriptHash
11655
11656 var signType
11657 var signScript
11658
11659 if (redeemScript && witnessScript) {
11660 redeemScriptHash = bcrypto.hash160(redeemScript)
11661 witnessScriptHash = bcrypto.sha256(witnessScript)
11662 checkP2SHInput(input, redeemScriptHash)
11663
11664 if (!redeemScript.equals(btemplates.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script')
11665
11666 expanded = expandOutput(witnessScript, undefined, kpPubKey)
11667 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
11668
11669 prevOutType = btemplates.types.P2SH
11670 prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash)
11671 p2sh = witness = p2wsh = true
11672 p2shType = btemplates.types.P2WSH
11673 signType = witnessType = expanded.scriptType
11674 signScript = witnessScript
11675 } else if (redeemScript) {
11676 redeemScriptHash = bcrypto.hash160(redeemScript)
11677 checkP2SHInput(input, redeemScriptHash)
11678
11679 expanded = expandOutput(redeemScript, undefined, kpPubKey)
11680 if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"')
11681
11682 prevOutType = btemplates.types.P2SH
11683 prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash)
11684 p2sh = true
11685 signType = p2shType = expanded.scriptType
11686 signScript = redeemScript
11687 witness = signType === btemplates.types.P2WPKH
11688 } else if (witnessScript) {
11689 witnessScriptHash = bcrypto.sha256(witnessScript)
11690 checkP2WSHInput(input, witnessScriptHash)
11691
11692 expanded = expandOutput(witnessScript, undefined, kpPubKey)
11693 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
11694
11695 prevOutType = btemplates.types.P2WSH
11696 prevOutScript = btemplates.witnessScriptHash.output.encode(witnessScriptHash)
11697 witness = p2wsh = true
11698 signType = witnessType = expanded.scriptType
11699 signScript = witnessScript
11700 } else if (input.prevOutType) {
11701 // embedded scripts are not possible without a redeemScript
11702 if (input.prevOutType === scriptTypes.P2SH ||
11703 input.prevOutType === scriptTypes.P2WSH) {
11704 throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript')
11705 }
11706
11707 prevOutType = input.prevOutType
11708 prevOutScript = input.prevOutScript
11709 expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey)
11710 if (!expanded.pubKeys) return
11711
11712 witness = (input.prevOutType === scriptTypes.P2WPKH)
11713 signType = prevOutType
11714 signScript = prevOutScript
11715 } else {
11716 prevOutScript = btemplates.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey))
11717 expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey)
11718
11719 prevOutType = scriptTypes.P2PKH
11720 witness = false
11721 signType = prevOutType
11722 signScript = prevOutScript
11723 }
11724
11725 if (signType === scriptTypes.P2WPKH) {
11726 signScript = btemplates.pubKeyHash.output.encode(btemplates.witnessPubKeyHash.output.decode(signScript))
11727 }
11728
11729 if (p2sh) {
11730 input.redeemScript = redeemScript
11731 input.redeemScriptType = p2shType
11732 }
11733
11734 if (p2wsh) {
11735 input.witnessScript = witnessScript
11736 input.witnessScriptType = witnessType
11737 }
11738
11739 input.pubKeys = expanded.pubKeys
11740 input.signatures = expanded.signatures
11741 input.signScript = signScript
11742 input.signType = signType
11743 input.prevOutScript = prevOutScript
11744 input.prevOutType = prevOutType
11745 input.witness = witness
11746 }
11747
11748 function buildStack (type, signatures, pubKeys, allowIncomplete) {
11749 if (type === scriptTypes.P2PKH) {
11750 if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return btemplates.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0])
11751 } else if (type === scriptTypes.P2PK) {
11752 if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return btemplates.pubKey.input.encodeStack(signatures[0])
11753 } else if (type === scriptTypes.MULTISIG) {
11754 if (signatures.length > 0) {
11755 signatures = signatures.map(function (signature) {
11756 return signature || ops.OP_0
11757 })
11758 if (!allowIncomplete) {
11759 // remove blank signatures
11760 signatures = signatures.filter(function (x) { return x !== ops.OP_0 })
11761 }
11762
11763 return btemplates.multisig.input.encodeStack(signatures)
11764 }
11765 } else {
11766 throw new Error('Not yet supported')
11767 }
11768
11769 if (!allowIncomplete) throw new Error('Not enough signatures provided')
11770 return []
11771 }
11772
11773 function buildInput (input, allowIncomplete) {
11774 var scriptType = input.prevOutType
11775 var sig = []
11776 var witness = []
11777
11778 if (supportedType(scriptType)) {
11779 sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete)
11780 }
11781
11782 var p2sh = false
11783 if (scriptType === btemplates.types.P2SH) {
11784 // We can remove this error later when we have a guarantee prepareInput
11785 // rejects unsignable scripts - it MUST be signable at this point.
11786 if (!allowIncomplete && !supportedP2SHType(input.redeemScriptType)) {
11787 throw new Error('Impossible to sign this type')
11788 }
11789
11790 if (supportedType(input.redeemScriptType)) {
11791 sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete)
11792 }
11793
11794 // If it wasn't SIGNABLE, it's witness, defer to that
11795 if (input.redeemScriptType) {
11796 p2sh = true
11797 scriptType = input.redeemScriptType
11798 }
11799 }
11800
11801 switch (scriptType) {
11802 // P2WPKH is a special case of P2PKH
11803 case btemplates.types.P2WPKH:
11804 witness = buildStack(btemplates.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete)
11805 break
11806
11807 case btemplates.types.P2WSH:
11808 // We can remove this check later
11809 if (!allowIncomplete && !supportedType(input.witnessScriptType)) {
11810 throw new Error('Impossible to sign this type')
11811 }
11812
11813 if (supportedType(input.witnessScriptType)) {
11814 witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete)
11815 witness.push(input.witnessScript)
11816 scriptType = input.witnessScriptType
11817 }
11818
11819 break
11820 }
11821
11822 // append redeemScript if necessary
11823 if (p2sh) {
11824 sig.push(input.redeemScript)
11825 }
11826
11827 return {
11828 type: scriptType,
11829 script: bscript.compile(sig),
11830 witness: witness
11831 }
11832 }
11833
11834 function TransactionBuilder (network, maximumFeeRate) {
11835 this.prevTxMap = {}
11836 this.network = network || networks.bitcoin
11837
11838 // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
11839 this.maximumFeeRate = maximumFeeRate || 2500
11840
11841 this.inputs = []
11842 this.tx = new Transaction()
11843 }
11844
11845 TransactionBuilder.prototype.setLockTime = function (locktime) {
11846 typeforce(types.UInt32, locktime)
11847
11848 // if any signatures exist, throw
11849 if (this.inputs.some(function (input) {
11850 if (!input.signatures) return false
11851
11852 return input.signatures.some(function (s) { return s })
11853 })) {
11854 throw new Error('No, this would invalidate signatures')
11855 }
11856
11857 this.tx.locktime = locktime
11858 }
11859
11860 TransactionBuilder.prototype.setVersion = function (version) {
11861 typeforce(types.UInt32, version)
11862
11863 // XXX: this might eventually become more complex depending on what the versions represent
11864 this.tx.version = version
11865 }
11866
11867 TransactionBuilder.fromTransaction = function (transaction, network) {
11868 var txb = new TransactionBuilder(network)
11869
11870 // Copy transaction fields
11871 txb.setVersion(transaction.version)
11872 txb.setLockTime(transaction.locktime)
11873
11874 // Copy outputs (done first to avoid signature invalidation)
11875 transaction.outs.forEach(function (txOut) {
11876 txb.addOutput(txOut.script, txOut.value)
11877 })
11878
11879 // Copy inputs
11880 transaction.ins.forEach(function (txIn) {
11881 txb.__addInputUnsafe(txIn.hash, txIn.index, {
11882 sequence: txIn.sequence,
11883 script: txIn.script,
11884 witness: txIn.witness
11885 })
11886 })
11887
11888 // fix some things not possible through the public API
11889 txb.inputs.forEach(function (input, i) {
11890 fixMultisigOrder(input, transaction, i)
11891 })
11892
11893 return txb
11894 }
11895
11896 TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) {
11897 if (!this.__canModifyInputs()) {
11898 throw new Error('No, this would invalidate signatures')
11899 }
11900
11901 var value
11902
11903 // is it a hex string?
11904 if (typeof txHash === 'string') {
11905 // transaction hashs's are displayed in reverse order, un-reverse it
11906 txHash = Buffer.from(txHash, 'hex').reverse()
11907
11908 // is it a Transaction object?
11909 } else if (txHash instanceof Transaction) {
11910 var txOut = txHash.outs[vout]
11911 prevOutScript = txOut.script
11912 value = txOut.value
11913
11914 txHash = txHash.getHash()
11915 }
11916
11917 return this.__addInputUnsafe(txHash, vout, {
11918 sequence: sequence,
11919 prevOutScript: prevOutScript,
11920 value: value
11921 })
11922 }
11923
11924 TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) {
11925 if (Transaction.isCoinbaseHash(txHash)) {
11926 throw new Error('coinbase inputs not supported')
11927 }
11928
11929 var prevTxOut = txHash.toString('hex') + ':' + vout
11930 if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut)
11931
11932 var input = {}
11933
11934 // derive what we can from the scriptSig
11935 if (options.script !== undefined) {
11936 input = expandInput(options.script, options.witness || [])
11937 }
11938
11939 // if an input value was given, retain it
11940 if (options.value !== undefined) {
11941 input.value = options.value
11942 }
11943
11944 // derive what we can from the previous transactions output script
11945 if (!input.prevOutScript && options.prevOutScript) {
11946 var prevOutType
11947
11948 if (!input.pubKeys && !input.signatures) {
11949 var expanded = expandOutput(options.prevOutScript)
11950
11951 if (expanded.pubKeys) {
11952 input.pubKeys = expanded.pubKeys
11953 input.signatures = expanded.signatures
11954 }
11955
11956 prevOutType = expanded.scriptType
11957 }
11958
11959 input.prevOutScript = options.prevOutScript
11960 input.prevOutType = prevOutType || btemplates.classifyOutput(options.prevOutScript)
11961 }
11962
11963 var vin = this.tx.addInput(txHash, vout, options.sequence, options.scriptSig)
11964 this.inputs[vin] = input
11965 this.prevTxMap[prevTxOut] = vin
11966 return vin
11967 }
11968
11969 TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) {
11970 if (!this.__canModifyOutputs()) {
11971 throw new Error('No, this would invalidate signatures')
11972 }
11973
11974 // Attempt to get a script if it's a base58 address string
11975 if (typeof scriptPubKey === 'string') {
11976 scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network)
11977 }
11978
11979 return this.tx.addOutput(scriptPubKey, value)
11980 }
11981
11982 TransactionBuilder.prototype.build = function () {
11983 return this.__build(false)
11984 }
11985 TransactionBuilder.prototype.buildIncomplete = function () {
11986 return this.__build(true)
11987 }
11988
11989 TransactionBuilder.prototype.__build = function (allowIncomplete) {
11990 if (!allowIncomplete) {
11991 if (!this.tx.ins.length) throw new Error('Transaction has no inputs')
11992 if (!this.tx.outs.length) throw new Error('Transaction has no outputs')
11993 }
11994
11995 var tx = this.tx.clone()
11996 // Create script signatures from inputs
11997 this.inputs.forEach(function (input, i) {
11998 var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType
11999 if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete')
12000 var result = buildInput(input, allowIncomplete)
12001
12002 // skip if no result
12003 if (!allowIncomplete) {
12004 if (!supportedType(result.type) && result.type !== btemplates.types.P2WPKH) {
12005 throw new Error(result.type + ' not supported')
12006 }
12007 }
12008
12009 tx.setInputScript(i, result.script)
12010 tx.setWitness(i, result.witness)
12011 })
12012
12013 if (!allowIncomplete) {
12014 // do not rely on this, its merely a last resort
12015 if (this.__overMaximumFees(tx.virtualSize())) {
12016 throw new Error('Transaction has absurd fees')
12017 }
12018 }
12019
12020 return tx
12021 }
12022
12023 function canSign (input) {
12024 return input.prevOutScript !== undefined &&
12025 input.signScript !== undefined &&
12026 input.pubKeys !== undefined &&
12027 input.signatures !== undefined &&
12028 input.signatures.length === input.pubKeys.length &&
12029 input.pubKeys.length > 0 &&
12030 (
12031 input.witness === false ||
12032 (input.witness === true && input.value !== undefined)
12033 )
12034 }
12035
12036 TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) {
12037 // TODO: remove keyPair.network matching in 4.0.0
12038 if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network')
12039 if (!this.inputs[vin]) throw new Error('No input at index: ' + vin)
12040 hashType = hashType || Transaction.SIGHASH_ALL
12041
12042 var input = this.inputs[vin]
12043
12044 // if redeemScript was previously provided, enforce consistency
12045 if (input.redeemScript !== undefined &&
12046 redeemScript &&
12047 !input.redeemScript.equals(redeemScript)) {
12048 throw new Error('Inconsistent redeemScript')
12049 }
12050
12051 var kpPubKey = keyPair.publicKey || keyPair.getPublicKeyBuffer()
12052 if (!canSign(input)) {
12053 if (witnessValue !== undefined) {
12054 if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input didn\'t match witnessValue')
12055 typeforce(types.Satoshi, witnessValue)
12056 input.value = witnessValue
12057 }
12058
12059 if (!canSign(input)) prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript)
12060 if (!canSign(input)) throw Error(input.prevOutType + ' not supported')
12061 }
12062
12063 // ready to sign
12064 var signatureHash
12065 if (input.witness) {
12066 signatureHash = this.tx.hashForWitnessV0(vin, input.signScript, input.value, hashType)
12067 } else {
12068 signatureHash = this.tx.hashForSignature(vin, input.signScript, hashType)
12069 }
12070
12071 // enforce in order signing of public keys
12072 var signed = input.pubKeys.some(function (pubKey, i) {
12073 if (!kpPubKey.equals(pubKey)) return false
12074 if (input.signatures[i]) throw new Error('Signature already exists')
12075 if (kpPubKey.length !== 33 &&
12076 input.signType === scriptTypes.P2WPKH) throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH')
12077
12078 var signature = keyPair.sign(signatureHash)
12079 if (Buffer.isBuffer(signature)) signature = ECSignature.fromRSBuffer(signature)
12080
12081 input.signatures[i] = signature.toScriptSignature(hashType)
12082 return true
12083 })
12084
12085 if (!signed) throw new Error('Key pair cannot sign for this input')
12086 }
12087
12088 function signatureHashType (buffer) {
12089 return buffer.readUInt8(buffer.length - 1)
12090 }
12091
12092 TransactionBuilder.prototype.__canModifyInputs = function () {
12093 return this.inputs.every(function (input) {
12094 // any signatures?
12095 if (input.signatures === undefined) return true
12096
12097 return input.signatures.every(function (signature) {
12098 if (!signature) return true
12099 var hashType = signatureHashType(signature)
12100
12101 // if SIGHASH_ANYONECANPAY is set, signatures would not
12102 // be invalidated by more inputs
12103 return hashType & Transaction.SIGHASH_ANYONECANPAY
12104 })
12105 })
12106 }
12107
12108 TransactionBuilder.prototype.__canModifyOutputs = function () {
12109 var nInputs = this.tx.ins.length
12110 var nOutputs = this.tx.outs.length
12111
12112 return this.inputs.every(function (input) {
12113 if (input.signatures === undefined) return true
12114
12115 return input.signatures.every(function (signature) {
12116 if (!signature) return true
12117 var hashType = signatureHashType(signature)
12118
12119 var hashTypeMod = hashType & 0x1f
12120 if (hashTypeMod === Transaction.SIGHASH_NONE) return true
12121 if (hashTypeMod === Transaction.SIGHASH_SINGLE) {
12122 // if SIGHASH_SINGLE is set, and nInputs > nOutputs
12123 // some signatures would be invalidated by the addition
12124 // of more outputs
12125 return nInputs <= nOutputs
12126 }
12127 })
12128 })
12129 }
12130
12131 TransactionBuilder.prototype.__overMaximumFees = function (bytes) {
12132 // not all inputs will have .value defined
12133 var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0)
12134
12135 // but all outputs do, and if we have any input value
12136 // we can immediately determine if the outputs are too small
12137 var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0)
12138 var fee = incoming - outgoing
12139 var feeRate = fee / bytes
12140
12141 return feeRate > this.maximumFeeRate
12142 }
12143
12144 module.exports = TransactionBuilder
12145
12146 },{"./address":44,"./crypto":47,"./ecpair":49,"./ecsignature":50,"./networks":53,"./script":54,"./templates":56,"./transaction":78,"./types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],80:[function(require,module,exports){
12147 var typeforce = require('typeforce')
12148
12149 var UINT31_MAX = Math.pow(2, 31) - 1
12150 function UInt31 (value) {
12151 return typeforce.UInt32(value) && value <= UINT31_MAX
12152 }
12153
12154 function BIP32Path (value) {
12155 return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/)
12156 }
12157 BIP32Path.toJSON = function () { return 'BIP32 derivation path' }
12158
12159 var SATOSHI_MAX = 21 * 1e14
12160 function Satoshi (value) {
12161 return typeforce.UInt53(value) && value <= SATOSHI_MAX
12162 }
12163
12164 // external dependent types
12165 var BigInt = typeforce.quacksLike('BigInteger')
12166 var ECPoint = typeforce.quacksLike('Point')
12167
12168 // exposed, external API
12169 var ECSignature = typeforce.compile({ r: BigInt, s: BigInt })
12170 var Network = typeforce.compile({
12171 messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String),
12172 bip32: {
12173 public: typeforce.UInt32,
12174 private: typeforce.UInt32
12175 },
12176 pubKeyHash: typeforce.oneOf(typeforce.UInt8, typeforce.UInt16),
12177 scriptHash: typeforce.oneOf(typeforce.UInt8, typeforce.UInt16),
12178 wif: typeforce.UInt8
12179 })
12180
12181 // extend typeforce types with ours
12182 var types = {
12183 BigInt: BigInt,
12184 BIP32Path: BIP32Path,
12185 Buffer256bit: typeforce.BufferN(32),
12186 ECPoint: ECPoint,
12187 ECSignature: ECSignature,
12188 Hash160bit: typeforce.BufferN(20),
12189 Hash256bit: typeforce.BufferN(32),
12190 Network: Network,
12191 Satoshi: Satoshi,
12192 UInt31: UInt31
12193 }
12194
12195 for (var typeName in typeforce) {
12196 types[typeName] = typeforce[typeName]
12197 }
12198
12199 module.exports = types
12200
12201 },{"typeforce":112}],81:[function(require,module,exports){
12202 var basex = require('base-x')
12203 var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
12204
12205 module.exports = basex(ALPHABET)
12206
12207 },{"base-x":35}],82:[function(require,module,exports){
12208 'use strict'
12209
12210 var base58 = require('bs58')
12211 var Buffer = require('safe-buffer').Buffer
12212
12213 module.exports = function (checksumFn) {
12214 // Encode a buffer as a base58-check encoded string
12215 function encode (payload) {
12216 var checksum = checksumFn(payload)
12217
12218 return base58.encode(Buffer.concat([
12219 payload,
12220 checksum
12221 ], payload.length + 4))
12222 }
12223
12224 function decodeRaw (buffer) {
12225 var payload = buffer.slice(0, -4)
12226 var checksum = buffer.slice(-4)
12227 var newChecksum = checksumFn(payload)
12228
12229 if (checksum[0] ^ newChecksum[0] |
12230 checksum[1] ^ newChecksum[1] |
12231 checksum[2] ^ newChecksum[2] |
12232 checksum[3] ^ newChecksum[3]) return
12233
12234 return payload
12235 }
12236
12237 // Decode a base58-check encoded string to a buffer, no result if checksum is wrong
12238 function decodeUnsafe (string) {
12239 var buffer = base58.decodeUnsafe(string)
12240 if (!buffer) return
12241
12242 return decodeRaw(buffer)
12243 }
12244
12245 function decode (string) {
12246 var buffer = base58.decode(string)
12247 var payload = decodeRaw(buffer, checksumFn)
12248 if (!payload) throw new Error('Invalid checksum')
12249 return payload
12250 }
12251
12252 return {
12253 encode: encode,
12254 decode: decode,
12255 decodeUnsafe: decodeUnsafe
12256 }
12257 }
12258
12259 },{"bs58":81,"safe-buffer":101}],83:[function(require,module,exports){
12260 'use strict'
12261
12262 var createHash = require('create-hash')
12263 var bs58checkBase = require('./base')
12264
12265 // SHA256(SHA256(buffer))
12266 function sha256x2 (buffer) {
12267 var tmp = createHash('sha256').update(buffer).digest()
12268 return createHash('sha256').update(tmp).digest()
12269 }
12270
12271 module.exports = bs58checkBase(sha256x2)
12272
12273 },{"./base":82,"create-hash":85}],84:[function(require,module,exports){
12274 var Buffer = require('safe-buffer').Buffer
12275 var Transform = require('stream').Transform
12276 var StringDecoder = require('string_decoder').StringDecoder
12277 var inherits = require('inherits')
12278
12279 function CipherBase (hashMode) {
12280 Transform.call(this)
12281 this.hashMode = typeof hashMode === 'string'
12282 if (this.hashMode) {
12283 this[hashMode] = this._finalOrDigest
12284 } else {
12285 this.final = this._finalOrDigest
12286 }
12287 if (this._final) {
12288 this.__final = this._final
12289 this._final = null
12290 }
12291 this._decoder = null
12292 this._encoding = null
12293 }
12294 inherits(CipherBase, Transform)
12295
12296 CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
12297 if (typeof data === 'string') {
12298 data = Buffer.from(data, inputEnc)
12299 }
12300
12301 var outData = this._update(data)
12302 if (this.hashMode) return this
12303
12304 if (outputEnc) {
12305 outData = this._toString(outData, outputEnc)
12306 }
12307
12308 return outData
12309 }
12310
12311 CipherBase.prototype.setAutoPadding = function () {}
12312 CipherBase.prototype.getAuthTag = function () {
12313 throw new Error('trying to get auth tag in unsupported state')
12314 }
12315
12316 CipherBase.prototype.setAuthTag = function () {
12317 throw new Error('trying to set auth tag in unsupported state')
12318 }
12319
12320 CipherBase.prototype.setAAD = function () {
12321 throw new Error('trying to set aad in unsupported state')
12322 }
12323
12324 CipherBase.prototype._transform = function (data, _, next) {
12325 var err
12326 try {
12327 if (this.hashMode) {
12328 this._update(data)
12329 } else {
12330 this.push(this._update(data))
12331 }
12332 } catch (e) {
12333 err = e
12334 } finally {
12335 next(err)
12336 }
12337 }
12338 CipherBase.prototype._flush = function (done) {
12339 var err
12340 try {
12341 this.push(this.__final())
12342 } catch (e) {
12343 err = e
12344 }
12345
12346 done(err)
12347 }
12348 CipherBase.prototype._finalOrDigest = function (outputEnc) {
12349 var outData = this.__final() || Buffer.alloc(0)
12350 if (outputEnc) {
12351 outData = this._toString(outData, outputEnc, true)
12352 }
12353 return outData
12354 }
12355
12356 CipherBase.prototype._toString = function (value, enc, fin) {
12357 if (!this._decoder) {
12358 this._decoder = new StringDecoder(enc)
12359 this._encoding = enc
12360 }
12361
12362 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
12363
12364 var out = this._decoder.write(value)
12365 if (fin) {
12366 out += this._decoder.end()
12367 }
12368
12369 return out
12370 }
12371
12372 module.exports = CipherBase
12373
12374 },{"inherits":96,"safe-buffer":101,"stream":28,"string_decoder":29}],85:[function(require,module,exports){
12375 (function (Buffer){
12376 'use strict'
12377 var inherits = require('inherits')
12378 var md5 = require('./md5')
12379 var RIPEMD160 = require('ripemd160')
12380 var sha = require('sha.js')
12381
12382 var Base = require('cipher-base')
12383
12384 function HashNoConstructor (hash) {
12385 Base.call(this, 'digest')
12386
12387 this._hash = hash
12388 this.buffers = []
12389 }
12390
12391 inherits(HashNoConstructor, Base)
12392
12393 HashNoConstructor.prototype._update = function (data) {
12394 this.buffers.push(data)
12395 }
12396
12397 HashNoConstructor.prototype._final = function () {
12398 var buf = Buffer.concat(this.buffers)
12399 var r = this._hash(buf)
12400 this.buffers = null
12401
12402 return r
12403 }
12404
12405 function Hash (hash) {
12406 Base.call(this, 'digest')
12407
12408 this._hash = hash
12409 }
12410
12411 inherits(Hash, Base)
12412
12413 Hash.prototype._update = function (data) {
12414 this._hash.update(data)
12415 }
12416
12417 Hash.prototype._final = function () {
12418 return this._hash.digest()
12419 }
12420
12421 module.exports = function createHash (alg) {
12422 alg = alg.toLowerCase()
12423 if (alg === 'md5') return new HashNoConstructor(md5)
12424 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
12425
12426 return new Hash(sha(alg))
12427 }
12428
12429 }).call(this,require("buffer").Buffer)
12430 },{"./md5":87,"buffer":5,"cipher-base":84,"inherits":96,"ripemd160":100,"sha.js":103}],86:[function(require,module,exports){
12431 (function (Buffer){
12432 'use strict'
12433 var intSize = 4
12434 var zeroBuffer = new Buffer(intSize)
12435 zeroBuffer.fill(0)
12436
12437 var charSize = 8
12438 var hashSize = 16
12439
12440 function toArray (buf) {
12441 if ((buf.length % intSize) !== 0) {
12442 var len = buf.length + (intSize - (buf.length % intSize))
12443 buf = Buffer.concat([buf, zeroBuffer], len)
12444 }
12445
12446 var arr = new Array(buf.length >>> 2)
12447 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
12448 arr[j] = buf.readInt32LE(i)
12449 }
12450
12451 return arr
12452 }
12453
12454 module.exports = function hash (buf, fn) {
12455 var arr = fn(toArray(buf), buf.length * charSize)
12456 buf = new Buffer(hashSize)
12457 for (var i = 0; i < arr.length; i++) {
12458 buf.writeInt32LE(arr[i], i << 2, true)
12459 }
12460 return buf
12461 }
12462
12463 }).call(this,require("buffer").Buffer)
12464 },{"buffer":5}],87:[function(require,module,exports){
12465 'use strict'
12466 /*
12467 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
12468 * Digest Algorithm, as defined in RFC 1321.
12469 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
12470 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
12471 * Distributed under the BSD License
12472 * See http://pajhome.org.uk/crypt/md5 for more info.
12473 */
12474
12475 var makeHash = require('./make-hash')
12476
12477 /*
12478 * Calculate the MD5 of an array of little-endian words, and a bit length
12479 */
12480 function core_md5 (x, len) {
12481 /* append padding */
12482 x[len >> 5] |= 0x80 << ((len) % 32)
12483 x[(((len + 64) >>> 9) << 4) + 14] = len
12484
12485 var a = 1732584193
12486 var b = -271733879
12487 var c = -1732584194
12488 var d = 271733878
12489
12490 for (var i = 0; i < x.length; i += 16) {
12491 var olda = a
12492 var oldb = b
12493 var oldc = c
12494 var oldd = d
12495
12496 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
12497 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
12498 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
12499 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
12500 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
12501 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
12502 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
12503 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
12504 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
12505 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
12506 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
12507 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
12508 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
12509 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
12510 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
12511 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
12512
12513 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
12514 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
12515 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
12516 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
12517 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
12518 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
12519 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
12520 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
12521 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
12522 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
12523 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
12524 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
12525 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
12526 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
12527 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
12528 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
12529
12530 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
12531 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
12532 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
12533 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
12534 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
12535 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
12536 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
12537 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
12538 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
12539 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
12540 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
12541 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
12542 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
12543 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
12544 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
12545 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
12546
12547 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
12548 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
12549 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
12550 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
12551 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
12552 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
12553 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
12554 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
12555 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
12556 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
12557 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
12558 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
12559 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
12560 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
12561 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
12562 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
12563
12564 a = safe_add(a, olda)
12565 b = safe_add(b, oldb)
12566 c = safe_add(c, oldc)
12567 d = safe_add(d, oldd)
12568 }
12569
12570 return [a, b, c, d]
12571 }
12572
12573 /*
12574 * These functions implement the four basic operations the algorithm uses.
12575 */
12576 function md5_cmn (q, a, b, x, s, t) {
12577 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
12578 }
12579
12580 function md5_ff (a, b, c, d, x, s, t) {
12581 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
12582 }
12583
12584 function md5_gg (a, b, c, d, x, s, t) {
12585 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
12586 }
12587
12588 function md5_hh (a, b, c, d, x, s, t) {
12589 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
12590 }
12591
12592 function md5_ii (a, b, c, d, x, s, t) {
12593 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
12594 }
12595
12596 /*
12597 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
12598 * to work around bugs in some JS interpreters.
12599 */
12600 function safe_add (x, y) {
12601 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
12602 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
12603 return (msw << 16) | (lsw & 0xFFFF)
12604 }
12605
12606 /*
12607 * Bitwise rotate a 32-bit number to the left.
12608 */
12609 function bit_rol (num, cnt) {
12610 return (num << cnt) | (num >>> (32 - cnt))
12611 }
12612
12613 module.exports = function md5 (buf) {
12614 return makeHash(buf, core_md5)
12615 }
12616
12617 },{"./make-hash":86}],88:[function(require,module,exports){
12618 'use strict'
12619 var inherits = require('inherits')
12620 var Legacy = require('./legacy')
12621 var Base = require('cipher-base')
12622 var Buffer = require('safe-buffer').Buffer
12623 var md5 = require('create-hash/md5')
12624 var RIPEMD160 = require('ripemd160')
12625
12626 var sha = require('sha.js')
12627
12628 var ZEROS = Buffer.alloc(128)
12629
12630 function Hmac (alg, key) {
12631 Base.call(this, 'digest')
12632 if (typeof key === 'string') {
12633 key = Buffer.from(key)
12634 }
12635
12636 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
12637
12638 this._alg = alg
12639 this._key = key
12640 if (key.length > blocksize) {
12641 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12642 key = hash.update(key).digest()
12643 } else if (key.length < blocksize) {
12644 key = Buffer.concat([key, ZEROS], blocksize)
12645 }
12646
12647 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12648 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12649
12650 for (var i = 0; i < blocksize; i++) {
12651 ipad[i] = key[i] ^ 0x36
12652 opad[i] = key[i] ^ 0x5C
12653 }
12654 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12655 this._hash.update(ipad)
12656 }
12657
12658 inherits(Hmac, Base)
12659
12660 Hmac.prototype._update = function (data) {
12661 this._hash.update(data)
12662 }
12663
12664 Hmac.prototype._final = function () {
12665 var h = this._hash.digest()
12666 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
12667 return hash.update(this._opad).update(h).digest()
12668 }
12669
12670 module.exports = function createHmac (alg, key) {
12671 alg = alg.toLowerCase()
12672 if (alg === 'rmd160' || alg === 'ripemd160') {
12673 return new Hmac('rmd160', key)
12674 }
12675 if (alg === 'md5') {
12676 return new Legacy(md5, key)
12677 }
12678 return new Hmac(alg, key)
12679 }
12680
12681 },{"./legacy":89,"cipher-base":84,"create-hash/md5":87,"inherits":96,"ripemd160":100,"safe-buffer":101,"sha.js":103}],89:[function(require,module,exports){
12682 'use strict'
12683 var inherits = require('inherits')
12684 var Buffer = require('safe-buffer').Buffer
12685
12686 var Base = require('cipher-base')
12687
12688 var ZEROS = Buffer.alloc(128)
12689 var blocksize = 64
12690
12691 function Hmac (alg, key) {
12692 Base.call(this, 'digest')
12693 if (typeof key === 'string') {
12694 key = Buffer.from(key)
12695 }
12696
12697 this._alg = alg
12698 this._key = key
12699
12700 if (key.length > blocksize) {
12701 key = alg(key)
12702 } else if (key.length < blocksize) {
12703 key = Buffer.concat([key, ZEROS], blocksize)
12704 }
12705
12706 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12707 var opad = this._opad = Buffer.allocUnsafe(blocksize)
12708
12709 for (var i = 0; i < blocksize; i++) {
12710 ipad[i] = key[i] ^ 0x36
12711 opad[i] = key[i] ^ 0x5C
12712 }
12713
12714 this._hash = [ipad]
12715 }
12716
12717 inherits(Hmac, Base)
12718
12719 Hmac.prototype._update = function (data) {
12720 this._hash.push(data)
12721 }
12722
12723 Hmac.prototype._final = function () {
12724 var h = this._alg(Buffer.concat(this._hash))
12725 return this._alg(Buffer.concat([this._opad, h]))
12726 }
12727 module.exports = Hmac
12728
12729 },{"cipher-base":84,"inherits":96,"safe-buffer":101}],90:[function(require,module,exports){
12730 var assert = require('assert')
12731 var BigInteger = require('bigi')
12732
12733 var Point = require('./point')
12734
12735 function Curve (p, a, b, Gx, Gy, n, h) {
12736 this.p = p
12737 this.a = a
12738 this.b = b
12739 this.G = Point.fromAffine(this, Gx, Gy)
12740 this.n = n
12741 this.h = h
12742
12743 this.infinity = new Point(this, null, null, BigInteger.ZERO)
12744
12745 // result caching
12746 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
12747
12748 // determine size of p in bytes
12749 this.pLength = Math.floor((this.p.bitLength() + 7) / 8)
12750 }
12751
12752 Curve.prototype.pointFromX = function (isOdd, x) {
12753 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
12754 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
12755
12756 var y = beta
12757 if (beta.isEven() ^ !isOdd) {
12758 y = this.p.subtract(y) // -y % p
12759 }
12760
12761 return Point.fromAffine(this, x, y)
12762 }
12763
12764 Curve.prototype.isInfinity = function (Q) {
12765 if (Q === this.infinity) return true
12766
12767 return Q.z.signum() === 0 && Q.y.signum() !== 0
12768 }
12769
12770 Curve.prototype.isOnCurve = function (Q) {
12771 if (this.isInfinity(Q)) return true
12772
12773 var x = Q.affineX
12774 var y = Q.affineY
12775 var a = this.a
12776 var b = this.b
12777 var p = this.p
12778
12779 // Check that xQ and yQ are integers in the interval [0, p - 1]
12780 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
12781 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
12782
12783 // and check that y^2 = x^3 + ax + b (mod p)
12784 var lhs = y.square().mod(p)
12785 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
12786 return lhs.equals(rhs)
12787 }
12788
12789 /**
12790 * Validate an elliptic curve point.
12791 *
12792 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
12793 */
12794 Curve.prototype.validate = function (Q) {
12795 // Check Q != O
12796 assert(!this.isInfinity(Q), 'Point is at infinity')
12797 assert(this.isOnCurve(Q), 'Point is not on the curve')
12798
12799 // Check nQ = O (where Q is a scalar multiple of G)
12800 var nQ = Q.multiply(this.n)
12801 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
12802
12803 return true
12804 }
12805
12806 module.exports = Curve
12807
12808 },{"./point":94,"assert":1,"bigi":39}],91:[function(require,module,exports){
12809 module.exports={
12810 "secp128r1": {
12811 "p": "fffffffdffffffffffffffffffffffff",
12812 "a": "fffffffdfffffffffffffffffffffffc",
12813 "b": "e87579c11079f43dd824993c2cee5ed3",
12814 "n": "fffffffe0000000075a30d1b9038a115",
12815 "h": "01",
12816 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
12817 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
12818 },
12819 "secp160k1": {
12820 "p": "fffffffffffffffffffffffffffffffeffffac73",
12821 "a": "00",
12822 "b": "07",
12823 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
12824 "h": "01",
12825 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
12826 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
12827 },
12828 "secp160r1": {
12829 "p": "ffffffffffffffffffffffffffffffff7fffffff",
12830 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
12831 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
12832 "n": "0100000000000000000001f4c8f927aed3ca752257",
12833 "h": "01",
12834 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
12835 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
12836 },
12837 "secp192k1": {
12838 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
12839 "a": "00",
12840 "b": "03",
12841 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
12842 "h": "01",
12843 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
12844 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
12845 },
12846 "secp192r1": {
12847 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
12848 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
12849 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
12850 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
12851 "h": "01",
12852 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
12853 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
12854 },
12855 "secp256k1": {
12856 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
12857 "a": "00",
12858 "b": "07",
12859 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
12860 "h": "01",
12861 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
12862 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
12863 },
12864 "secp256r1": {
12865 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
12866 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
12867 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
12868 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
12869 "h": "01",
12870 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
12871 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
12872 }
12873 }
12874
12875 },{}],92:[function(require,module,exports){
12876 var Point = require('./point')
12877 var Curve = require('./curve')
12878
12879 var getCurveByName = require('./names')
12880
12881 module.exports = {
12882 Curve: Curve,
12883 Point: Point,
12884 getCurveByName: getCurveByName
12885 }
12886
12887 },{"./curve":90,"./names":93,"./point":94}],93:[function(require,module,exports){
12888 var BigInteger = require('bigi')
12889
12890 var curves = require('./curves.json')
12891 var Curve = require('./curve')
12892
12893 function getCurveByName (name) {
12894 var curve = curves[name]
12895 if (!curve) return null
12896
12897 var p = new BigInteger(curve.p, 16)
12898 var a = new BigInteger(curve.a, 16)
12899 var b = new BigInteger(curve.b, 16)
12900 var n = new BigInteger(curve.n, 16)
12901 var h = new BigInteger(curve.h, 16)
12902 var Gx = new BigInteger(curve.Gx, 16)
12903 var Gy = new BigInteger(curve.Gy, 16)
12904
12905 return new Curve(p, a, b, Gx, Gy, n, h)
12906 }
12907
12908 module.exports = getCurveByName
12909
12910 },{"./curve":90,"./curves.json":91,"bigi":39}],94:[function(require,module,exports){
12911 var assert = require('assert')
12912 var Buffer = require('safe-buffer').Buffer
12913 var BigInteger = require('bigi')
12914
12915 var THREE = BigInteger.valueOf(3)
12916
12917 function Point (curve, x, y, z) {
12918 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
12919
12920 this.curve = curve
12921 this.x = x
12922 this.y = y
12923 this.z = z
12924 this._zInv = null
12925
12926 this.compressed = true
12927 }
12928
12929 Object.defineProperty(Point.prototype, 'zInv', {
12930 get: function () {
12931 if (this._zInv === null) {
12932 this._zInv = this.z.modInverse(this.curve.p)
12933 }
12934
12935 return this._zInv
12936 }
12937 })
12938
12939 Object.defineProperty(Point.prototype, 'affineX', {
12940 get: function () {
12941 return this.x.multiply(this.zInv).mod(this.curve.p)
12942 }
12943 })
12944
12945 Object.defineProperty(Point.prototype, 'affineY', {
12946 get: function () {
12947 return this.y.multiply(this.zInv).mod(this.curve.p)
12948 }
12949 })
12950
12951 Point.fromAffine = function (curve, x, y) {
12952 return new Point(curve, x, y, BigInteger.ONE)
12953 }
12954
12955 Point.prototype.equals = function (other) {
12956 if (other === this) return true
12957 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
12958 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
12959
12960 // u = Y2 * Z1 - Y1 * Z2
12961 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
12962
12963 if (u.signum() !== 0) return false
12964
12965 // v = X2 * Z1 - X1 * Z2
12966 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
12967
12968 return v.signum() === 0
12969 }
12970
12971 Point.prototype.negate = function () {
12972 var y = this.curve.p.subtract(this.y)
12973
12974 return new Point(this.curve, this.x, y, this.z)
12975 }
12976
12977 Point.prototype.add = function (b) {
12978 if (this.curve.isInfinity(this)) return b
12979 if (this.curve.isInfinity(b)) return this
12980
12981 var x1 = this.x
12982 var y1 = this.y
12983 var x2 = b.x
12984 var y2 = b.y
12985
12986 // u = Y2 * Z1 - Y1 * Z2
12987 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
12988 // v = X2 * Z1 - X1 * Z2
12989 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
12990
12991 if (v.signum() === 0) {
12992 if (u.signum() === 0) {
12993 return this.twice() // this == b, so double
12994 }
12995
12996 return this.curve.infinity // this = -b, so infinity
12997 }
12998
12999 var v2 = v.square()
13000 var v3 = v2.multiply(v)
13001 var x1v2 = x1.multiply(v2)
13002 var zu2 = u.square().multiply(this.z)
13003
13004 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
13005 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
13006 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
13007 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p)
13008 // z3 = v^3 * z1 * z2
13009 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
13010
13011 return new Point(this.curve, x3, y3, z3)
13012 }
13013
13014 Point.prototype.twice = function () {
13015 if (this.curve.isInfinity(this)) return this
13016 if (this.y.signum() === 0) return this.curve.infinity
13017
13018 var x1 = this.x
13019 var y1 = this.y
13020
13021 var y1z1 = y1.multiply(this.z).mod(this.curve.p)
13022 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
13023 var a = this.curve.a
13024
13025 // w = 3 * x1^2 + a * z1^2
13026 var w = x1.square().multiply(THREE)
13027
13028 if (a.signum() !== 0) {
13029 w = w.add(this.z.square().multiply(a))
13030 }
13031
13032 w = w.mod(this.curve.p)
13033 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
13034 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
13035 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
13036 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
13037 // z3 = 8 * (y1 * z1)^3
13038 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
13039
13040 return new Point(this.curve, x3, y3, z3)
13041 }
13042
13043 // Simple NAF (Non-Adjacent Form) multiplication algorithm
13044 // TODO: modularize the multiplication algorithm
13045 Point.prototype.multiply = function (k) {
13046 if (this.curve.isInfinity(this)) return this
13047 if (k.signum() === 0) return this.curve.infinity
13048
13049 var e = k
13050 var h = e.multiply(THREE)
13051
13052 var neg = this.negate()
13053 var R = this
13054
13055 for (var i = h.bitLength() - 2; i > 0; --i) {
13056 var hBit = h.testBit(i)
13057 var eBit = e.testBit(i)
13058
13059 R = R.twice()
13060
13061 if (hBit !== eBit) {
13062 R = R.add(hBit ? this : neg)
13063 }
13064 }
13065
13066 return R
13067 }
13068
13069 // Compute this*j + x*k (simultaneous multiplication)
13070 Point.prototype.multiplyTwo = function (j, x, k) {
13071 var i = Math.max(j.bitLength(), k.bitLength()) - 1
13072 var R = this.curve.infinity
13073 var both = this.add(x)
13074
13075 while (i >= 0) {
13076 var jBit = j.testBit(i)
13077 var kBit = k.testBit(i)
13078
13079 R = R.twice()
13080
13081 if (jBit) {
13082 if (kBit) {
13083 R = R.add(both)
13084 } else {
13085 R = R.add(this)
13086 }
13087 } else if (kBit) {
13088 R = R.add(x)
13089 }
13090 --i
13091 }
13092
13093 return R
13094 }
13095
13096 Point.prototype.getEncoded = function (compressed) {
13097 if (compressed == null) compressed = this.compressed
13098 if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00'
13099
13100 var x = this.affineX
13101 var y = this.affineY
13102 var byteLength = this.curve.pLength
13103 var buffer
13104
13105 // 0x02/0x03 | X
13106 if (compressed) {
13107 buffer = Buffer.allocUnsafe(1 + byteLength)
13108 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
13109
13110 // 0x04 | X | Y
13111 } else {
13112 buffer = Buffer.allocUnsafe(1 + byteLength + byteLength)
13113 buffer.writeUInt8(0x04, 0)
13114
13115 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
13116 }
13117
13118 x.toBuffer(byteLength).copy(buffer, 1)
13119
13120 return buffer
13121 }
13122
13123 Point.decodeFrom = function (curve, buffer) {
13124 var type = buffer.readUInt8(0)
13125 var compressed = (type !== 4)
13126
13127 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
13128 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
13129
13130 var Q
13131 if (compressed) {
13132 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
13133 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
13134
13135 var isOdd = (type === 0x03)
13136 Q = curve.pointFromX(isOdd, x)
13137 } else {
13138 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
13139
13140 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
13141 Q = Point.fromAffine(curve, x, y)
13142 }
13143
13144 Q.compressed = compressed
13145 return Q
13146 }
13147
13148 Point.prototype.toString = function () {
13149 if (this.curve.isInfinity(this)) return '(INFINITY)'
13150
13151 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
13152 }
13153
13154 module.exports = Point
13155
13156 },{"assert":1,"bigi":39,"safe-buffer":101}],95:[function(require,module,exports){
13157 (function (Buffer){
13158 'use strict'
13159 var Transform = require('stream').Transform
13160 var inherits = require('inherits')
13161
13162 function HashBase (blockSize) {
13163 Transform.call(this)
13164
13165 this._block = new Buffer(blockSize)
13166 this._blockSize = blockSize
13167 this._blockOffset = 0
13168 this._length = [0, 0, 0, 0]
13169
13170 this._finalized = false
13171 }
13172
13173 inherits(HashBase, Transform)
13174
13175 HashBase.prototype._transform = function (chunk, encoding, callback) {
13176 var error = null
13177 try {
13178 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
13179 this.update(chunk)
13180 } catch (err) {
13181 error = err
13182 }
13183
13184 callback(error)
13185 }
13186
13187 HashBase.prototype._flush = function (callback) {
13188 var error = null
13189 try {
13190 this.push(this._digest())
13191 } catch (err) {
13192 error = err
13193 }
13194
13195 callback(error)
13196 }
13197
13198 HashBase.prototype.update = function (data, encoding) {
13199 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
13200 if (this._finalized) throw new Error('Digest already called')
13201 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
13202
13203 // consume data
13204 var block = this._block
13205 var offset = 0
13206 while (this._blockOffset + data.length - offset >= this._blockSize) {
13207 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
13208 this._update()
13209 this._blockOffset = 0
13210 }
13211 while (offset < data.length) block[this._blockOffset++] = data[offset++]
13212
13213 // update length
13214 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
13215 this._length[j] += carry
13216 carry = (this._length[j] / 0x0100000000) | 0
13217 if (carry > 0) this._length[j] -= 0x0100000000 * carry
13218 }
13219
13220 return this
13221 }
13222
13223 HashBase.prototype._update = function (data) {
13224 throw new Error('_update is not implemented')
13225 }
13226
13227 HashBase.prototype.digest = function (encoding) {
13228 if (this._finalized) throw new Error('Digest already called')
13229 this._finalized = true
13230
13231 var digest = this._digest()
13232 if (encoding !== undefined) digest = digest.toString(encoding)
13233 return digest
13234 }
13235
13236 HashBase.prototype._digest = function () {
13237 throw new Error('_digest is not implemented')
13238 }
13239
13240 module.exports = HashBase
13241
13242 }).call(this,require("buffer").Buffer)
13243 },{"buffer":5,"inherits":96,"stream":28}],96:[function(require,module,exports){
13244 arguments[4][9][0].apply(exports,arguments)
13245 },{"dup":9}],97:[function(require,module,exports){
13246 (function (Buffer){
13247 // constant-space merkle root calculation algorithm
13248 module.exports = function fastRoot (values, digestFn) {
13249 if (!Array.isArray(values)) throw TypeError('Expected values Array')
13250 if (typeof digestFn !== 'function') throw TypeError('Expected digest Function')
13251
13252 var length = values.length
13253 var results = values.concat()
13254
13255 while (length > 1) {
13256 var j = 0
13257
13258 for (var i = 0; i < length; i += 2, ++j) {
13259 var left = results[i]
13260 var right = i + 1 === length ? left : results[i + 1]
13261 var data = Buffer.concat([left, right])
13262
13263 results[j] = digestFn(data)
13264 }
13265
13266 length = j
13267 }
13268
13269 return results[0]
13270 }
13271
13272 }).call(this,require("buffer").Buffer)
13273 },{"buffer":5}],98:[function(require,module,exports){
13274 var OPS = require('bitcoin-ops')
13275
13276 function encodingLength (i) {
13277 return i < OPS.OP_PUSHDATA1 ? 1
13278 : i <= 0xff ? 2
13279 : i <= 0xffff ? 3
13280 : 5
13281 }
13282
13283 function encode (buffer, number, offset) {
13284 var size = encodingLength(number)
13285
13286 // ~6 bit
13287 if (size === 1) {
13288 buffer.writeUInt8(number, offset)
13289
13290 // 8 bit
13291 } else if (size === 2) {
13292 buffer.writeUInt8(OPS.OP_PUSHDATA1, offset)
13293 buffer.writeUInt8(number, offset + 1)
13294
13295 // 16 bit
13296 } else if (size === 3) {
13297 buffer.writeUInt8(OPS.OP_PUSHDATA2, offset)
13298 buffer.writeUInt16LE(number, offset + 1)
13299
13300 // 32 bit
13301 } else {
13302 buffer.writeUInt8(OPS.OP_PUSHDATA4, offset)
13303 buffer.writeUInt32LE(number, offset + 1)
13304 }
13305
13306 return size
13307 }
13308
13309 function decode (buffer, offset) {
13310 var opcode = buffer.readUInt8(offset)
13311 var number, size
13312
13313 // ~6 bit
13314 if (opcode < OPS.OP_PUSHDATA1) {
13315 number = opcode
13316 size = 1
13317
13318 // 8 bit
13319 } else if (opcode === OPS.OP_PUSHDATA1) {
13320 if (offset + 2 > buffer.length) return null
13321 number = buffer.readUInt8(offset + 1)
13322 size = 2
13323
13324 // 16 bit
13325 } else if (opcode === OPS.OP_PUSHDATA2) {
13326 if (offset + 3 > buffer.length) return null
13327 number = buffer.readUInt16LE(offset + 1)
13328 size = 3
13329
13330 // 32 bit
13331 } else {
13332 if (offset + 5 > buffer.length) return null
13333 if (opcode !== OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode')
13334
13335 number = buffer.readUInt32LE(offset + 1)
13336 size = 5
13337 }
13338
13339 return {
13340 opcode: opcode,
13341 number: number,
13342 size: size
13343 }
13344 }
13345
13346 module.exports = {
13347 encodingLength: encodingLength,
13348 encode: encode,
13349 decode: decode
13350 }
13351
13352 },{"bitcoin-ops":42}],99:[function(require,module,exports){
13353 (function (process,global){
13354 'use strict'
13355
13356 function oldBrowser () {
13357 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
13358 }
13359
13360 var Buffer = require('safe-buffer').Buffer
13361 var crypto = global.crypto || global.msCrypto
13362
13363 if (crypto && crypto.getRandomValues) {
13364 module.exports = randomBytes
13365 } else {
13366 module.exports = oldBrowser
13367 }
13368
13369 function randomBytes (size, cb) {
13370 // phantomjs needs to throw
13371 if (size > 65536) throw new Error('requested too many random bytes')
13372 // in case browserify isn't using the Uint8Array version
13373 var rawBytes = new global.Uint8Array(size)
13374
13375 // This will not work in older browsers.
13376 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
13377 if (size > 0) { // getRandomValues fails on IE if size == 0
13378 crypto.getRandomValues(rawBytes)
13379 }
13380
13381 // XXX: phantomjs doesn't like a buffer being passed here
13382 var bytes = Buffer.from(rawBytes.buffer)
13383
13384 if (typeof cb === 'function') {
13385 return process.nextTick(function () {
13386 cb(null, bytes)
13387 })
13388 }
13389
13390 return bytes
13391 }
13392
13393 }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13394 },{"_process":13,"safe-buffer":101}],100:[function(require,module,exports){
13395 (function (Buffer){
13396 'use strict'
13397 var inherits = require('inherits')
13398 var HashBase = require('hash-base')
13399
13400 function RIPEMD160 () {
13401 HashBase.call(this, 64)
13402
13403 // state
13404 this._a = 0x67452301
13405 this._b = 0xefcdab89
13406 this._c = 0x98badcfe
13407 this._d = 0x10325476
13408 this._e = 0xc3d2e1f0
13409 }
13410
13411 inherits(RIPEMD160, HashBase)
13412
13413 RIPEMD160.prototype._update = function () {
13414 var m = new Array(16)
13415 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
13416
13417 var al = this._a
13418 var bl = this._b
13419 var cl = this._c
13420 var dl = this._d
13421 var el = this._e
13422
13423 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
13424 // K = 0x00000000
13425 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
13426 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
13427 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
13428 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
13429 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
13430 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
13431 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
13432 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
13433 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
13434 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
13435 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
13436 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
13437 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
13438 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
13439 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
13440 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
13441 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
13442
13443 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
13444 // K = 0x5a827999
13445 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
13446 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
13447 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
13448 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
13449 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
13450 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
13451 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
13452 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
13453 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
13454 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
13455 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
13456 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
13457 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
13458 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
13459 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
13460 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
13461 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
13462
13463 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
13464 // K = 0x6ed9eba1
13465 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
13466 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
13467 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
13468 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
13469 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
13470 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
13471 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
13472 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
13473 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
13474 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
13475 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
13476 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
13477 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
13478 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
13479 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
13480 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
13481 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
13482
13483 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
13484 // K = 0x8f1bbcdc
13485 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
13486 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
13487 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
13488 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
13489 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
13490 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
13491 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
13492 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
13493 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
13494 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
13495 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
13496 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
13497 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
13498 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
13499 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
13500 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
13501 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
13502
13503 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
13504 // K = 0xa953fd4e
13505 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
13506 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
13507 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
13508 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
13509 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
13510 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
13511 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
13512 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
13513 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
13514 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
13515 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
13516 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
13517 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
13518 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
13519 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
13520 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
13521 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
13522
13523 var ar = this._a
13524 var br = this._b
13525 var cr = this._c
13526 var dr = this._d
13527 var er = this._e
13528
13529 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
13530 // K' = 0x50a28be6
13531 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
13532 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
13533 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
13534 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
13535 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
13536 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
13537 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
13538 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
13539 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
13540 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
13541 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
13542 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
13543 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
13544 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
13545 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
13546 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
13547 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
13548
13549 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
13550 // K' = 0x5c4dd124
13551 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
13552 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
13553 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
13554 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
13555 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
13556 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
13557 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
13558 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
13559 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
13560 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
13561 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
13562 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
13563 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
13564 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
13565 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
13566 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
13567 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
13568
13569 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
13570 // K' = 0x6d703ef3
13571 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
13572 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
13573 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
13574 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
13575 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
13576 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
13577 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
13578 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
13579 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
13580 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
13581 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
13582 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
13583 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
13584 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
13585 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
13586 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
13587 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
13588
13589 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
13590 // K' = 0x7a6d76e9
13591 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
13592 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
13593 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
13594 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
13595 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
13596 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
13597 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
13598 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
13599 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
13600 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
13601 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
13602 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
13603 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
13604 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
13605 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
13606 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
13607 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
13608
13609 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
13610 // K' = 0x00000000
13611 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
13612 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
13613 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
13614 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
13615 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
13616 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
13617 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
13618 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
13619 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
13620 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
13621 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
13622 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
13623 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
13624 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
13625 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
13626 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
13627 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
13628
13629 // change state
13630 var t = (this._b + cl + dr) | 0
13631 this._b = (this._c + dl + er) | 0
13632 this._c = (this._d + el + ar) | 0
13633 this._d = (this._e + al + br) | 0
13634 this._e = (this._a + bl + cr) | 0
13635 this._a = t
13636 }
13637
13638 RIPEMD160.prototype._digest = function () {
13639 // create padding and handle blocks
13640 this._block[this._blockOffset++] = 0x80
13641 if (this._blockOffset > 56) {
13642 this._block.fill(0, this._blockOffset, 64)
13643 this._update()
13644 this._blockOffset = 0
13645 }
13646
13647 this._block.fill(0, this._blockOffset, 56)
13648 this._block.writeUInt32LE(this._length[0], 56)
13649 this._block.writeUInt32LE(this._length[1], 60)
13650 this._update()
13651
13652 // produce result
13653 var buffer = new Buffer(20)
13654 buffer.writeInt32LE(this._a, 0)
13655 buffer.writeInt32LE(this._b, 4)
13656 buffer.writeInt32LE(this._c, 8)
13657 buffer.writeInt32LE(this._d, 12)
13658 buffer.writeInt32LE(this._e, 16)
13659 return buffer
13660 }
13661
13662 function rotl (x, n) {
13663 return (x << n) | (x >>> (32 - n))
13664 }
13665
13666 function fn1 (a, b, c, d, e, m, k, s) {
13667 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
13668 }
13669
13670 function fn2 (a, b, c, d, e, m, k, s) {
13671 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
13672 }
13673
13674 function fn3 (a, b, c, d, e, m, k, s) {
13675 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
13676 }
13677
13678 function fn4 (a, b, c, d, e, m, k, s) {
13679 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
13680 }
13681
13682 function fn5 (a, b, c, d, e, m, k, s) {
13683 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
13684 }
13685
13686 module.exports = RIPEMD160
13687
13688 }).call(this,require("buffer").Buffer)
13689 },{"buffer":5,"hash-base":95,"inherits":96}],101:[function(require,module,exports){
13690 /* eslint-disable node/no-deprecated-api */
13691 var buffer = require('buffer')
13692 var Buffer = buffer.Buffer
13693
13694 // alternative to using Object.keys for old browsers
13695 function copyProps (src, dst) {
13696 for (var key in src) {
13697 dst[key] = src[key]
13698 }
13699 }
13700 if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13701 module.exports = buffer
13702 } else {
13703 // Copy properties from require('buffer')
13704 copyProps(buffer, exports)
13705 exports.Buffer = SafeBuffer
13706 }
13707
13708 function SafeBuffer (arg, encodingOrOffset, length) {
13709 return Buffer(arg, encodingOrOffset, length)
13710 }
13711
13712 // Copy static methods from Buffer
13713 copyProps(Buffer, SafeBuffer)
13714
13715 SafeBuffer.from = function (arg, encodingOrOffset, length) {
13716 if (typeof arg === 'number') {
13717 throw new TypeError('Argument must not be a number')
13718 }
13719 return Buffer(arg, encodingOrOffset, length)
13720 }
13721
13722 SafeBuffer.alloc = function (size, fill, encoding) {
13723 if (typeof size !== 'number') {
13724 throw new TypeError('Argument must be a number')
13725 }
13726 var buf = Buffer(size)
13727 if (fill !== undefined) {
13728 if (typeof encoding === 'string') {
13729 buf.fill(fill, encoding)
13730 } else {
13731 buf.fill(fill)
13732 }
13733 } else {
13734 buf.fill(0)
13735 }
13736 return buf
13737 }
13738
13739 SafeBuffer.allocUnsafe = function (size) {
13740 if (typeof size !== 'number') {
13741 throw new TypeError('Argument must be a number')
13742 }
13743 return Buffer(size)
13744 }
13745
13746 SafeBuffer.allocUnsafeSlow = function (size) {
13747 if (typeof size !== 'number') {
13748 throw new TypeError('Argument must be a number')
13749 }
13750 return buffer.SlowBuffer(size)
13751 }
13752
13753 },{"buffer":5}],102:[function(require,module,exports){
13754 var Buffer = require('safe-buffer').Buffer
13755
13756 // prototype class for hash functions
13757 function Hash (blockSize, finalSize) {
13758 this._block = Buffer.alloc(blockSize)
13759 this._finalSize = finalSize
13760 this._blockSize = blockSize
13761 this._len = 0
13762 }
13763
13764 Hash.prototype.update = function (data, enc) {
13765 if (typeof data === 'string') {
13766 enc = enc || 'utf8'
13767 data = Buffer.from(data, enc)
13768 }
13769
13770 var block = this._block
13771 var blockSize = this._blockSize
13772 var length = data.length
13773 var accum = this._len
13774
13775 for (var offset = 0; offset < length;) {
13776 var assigned = accum % blockSize
13777 var remainder = Math.min(length - offset, blockSize - assigned)
13778
13779 for (var i = 0; i < remainder; i++) {
13780 block[assigned + i] = data[offset + i]
13781 }
13782
13783 accum += remainder
13784 offset += remainder
13785
13786 if ((accum % blockSize) === 0) {
13787 this._update(block)
13788 }
13789 }
13790
13791 this._len += length
13792 return this
13793 }
13794
13795 Hash.prototype.digest = function (enc) {
13796 var rem = this._len % this._blockSize
13797
13798 this._block[rem] = 0x80
13799
13800 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
13801 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
13802 this._block.fill(0, rem + 1)
13803
13804 if (rem >= this._finalSize) {
13805 this._update(this._block)
13806 this._block.fill(0)
13807 }
13808
13809 var bits = this._len * 8
13810
13811 // uint32
13812 if (bits <= 0xffffffff) {
13813 this._block.writeUInt32BE(bits, this._blockSize - 4)
13814
13815 // uint64
13816 } else {
13817 var lowBits = (bits & 0xffffffff) >>> 0
13818 var highBits = (bits - lowBits) / 0x100000000
13819
13820 this._block.writeUInt32BE(highBits, this._blockSize - 8)
13821 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
13822 }
13823
13824 this._update(this._block)
13825 var hash = this._hash()
13826
13827 return enc ? hash.toString(enc) : hash
13828 }
13829
13830 Hash.prototype._update = function () {
13831 throw new Error('_update must be implemented by subclass')
13832 }
13833
13834 module.exports = Hash
13835
13836 },{"safe-buffer":101}],103:[function(require,module,exports){
13837 var exports = module.exports = function SHA (algorithm) {
13838 algorithm = algorithm.toLowerCase()
13839
13840 var Algorithm = exports[algorithm]
13841 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
13842
13843 return new Algorithm()
13844 }
13845
13846 exports.sha = require('./sha')
13847 exports.sha1 = require('./sha1')
13848 exports.sha224 = require('./sha224')
13849 exports.sha256 = require('./sha256')
13850 exports.sha384 = require('./sha384')
13851 exports.sha512 = require('./sha512')
13852
13853 },{"./sha":104,"./sha1":105,"./sha224":106,"./sha256":107,"./sha384":108,"./sha512":109}],104:[function(require,module,exports){
13854 /*
13855 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
13856 * in FIPS PUB 180-1
13857 * This source code is derived from sha1.js of the same repository.
13858 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
13859 * operation was added.
13860 */
13861
13862 var inherits = require('inherits')
13863 var Hash = require('./hash')
13864 var Buffer = require('safe-buffer').Buffer
13865
13866 var K = [
13867 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13868 ]
13869
13870 var W = new Array(80)
13871
13872 function Sha () {
13873 this.init()
13874 this._w = W
13875
13876 Hash.call(this, 64, 56)
13877 }
13878
13879 inherits(Sha, Hash)
13880
13881 Sha.prototype.init = function () {
13882 this._a = 0x67452301
13883 this._b = 0xefcdab89
13884 this._c = 0x98badcfe
13885 this._d = 0x10325476
13886 this._e = 0xc3d2e1f0
13887
13888 return this
13889 }
13890
13891 function rotl5 (num) {
13892 return (num << 5) | (num >>> 27)
13893 }
13894
13895 function rotl30 (num) {
13896 return (num << 30) | (num >>> 2)
13897 }
13898
13899 function ft (s, b, c, d) {
13900 if (s === 0) return (b & c) | ((~b) & d)
13901 if (s === 2) return (b & c) | (b & d) | (c & d)
13902 return b ^ c ^ d
13903 }
13904
13905 Sha.prototype._update = function (M) {
13906 var W = this._w
13907
13908 var a = this._a | 0
13909 var b = this._b | 0
13910 var c = this._c | 0
13911 var d = this._d | 0
13912 var e = this._e | 0
13913
13914 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
13915 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
13916
13917 for (var j = 0; j < 80; ++j) {
13918 var s = ~~(j / 20)
13919 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
13920
13921 e = d
13922 d = c
13923 c = rotl30(b)
13924 b = a
13925 a = t
13926 }
13927
13928 this._a = (a + this._a) | 0
13929 this._b = (b + this._b) | 0
13930 this._c = (c + this._c) | 0
13931 this._d = (d + this._d) | 0
13932 this._e = (e + this._e) | 0
13933 }
13934
13935 Sha.prototype._hash = function () {
13936 var H = Buffer.allocUnsafe(20)
13937
13938 H.writeInt32BE(this._a | 0, 0)
13939 H.writeInt32BE(this._b | 0, 4)
13940 H.writeInt32BE(this._c | 0, 8)
13941 H.writeInt32BE(this._d | 0, 12)
13942 H.writeInt32BE(this._e | 0, 16)
13943
13944 return H
13945 }
13946
13947 module.exports = Sha
13948
13949 },{"./hash":102,"inherits":96,"safe-buffer":101}],105:[function(require,module,exports){
13950 /*
13951 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
13952 * in FIPS PUB 180-1
13953 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
13954 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
13955 * Distributed under the BSD License
13956 * See http://pajhome.org.uk/crypt/md5 for details.
13957 */
13958
13959 var inherits = require('inherits')
13960 var Hash = require('./hash')
13961 var Buffer = require('safe-buffer').Buffer
13962
13963 var K = [
13964 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13965 ]
13966
13967 var W = new Array(80)
13968
13969 function Sha1 () {
13970 this.init()
13971 this._w = W
13972
13973 Hash.call(this, 64, 56)
13974 }
13975
13976 inherits(Sha1, Hash)
13977
13978 Sha1.prototype.init = function () {
13979 this._a = 0x67452301
13980 this._b = 0xefcdab89
13981 this._c = 0x98badcfe
13982 this._d = 0x10325476
13983 this._e = 0xc3d2e1f0
13984
13985 return this
13986 }
13987
13988 function rotl1 (num) {
13989 return (num << 1) | (num >>> 31)
13990 }
13991
13992 function rotl5 (num) {
13993 return (num << 5) | (num >>> 27)
13994 }
13995
13996 function rotl30 (num) {
13997 return (num << 30) | (num >>> 2)
13998 }
13999
14000 function ft (s, b, c, d) {
14001 if (s === 0) return (b & c) | ((~b) & d)
14002 if (s === 2) return (b & c) | (b & d) | (c & d)
14003 return b ^ c ^ d
14004 }
14005
14006 Sha1.prototype._update = function (M) {
14007 var W = this._w
14008
14009 var a = this._a | 0
14010 var b = this._b | 0
14011 var c = this._c | 0
14012 var d = this._d | 0
14013 var e = this._e | 0
14014
14015 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
14016 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
14017
14018 for (var j = 0; j < 80; ++j) {
14019 var s = ~~(j / 20)
14020 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
14021
14022 e = d
14023 d = c
14024 c = rotl30(b)
14025 b = a
14026 a = t
14027 }
14028
14029 this._a = (a + this._a) | 0
14030 this._b = (b + this._b) | 0
14031 this._c = (c + this._c) | 0
14032 this._d = (d + this._d) | 0
14033 this._e = (e + this._e) | 0
14034 }
14035
14036 Sha1.prototype._hash = function () {
14037 var H = Buffer.allocUnsafe(20)
14038
14039 H.writeInt32BE(this._a | 0, 0)
14040 H.writeInt32BE(this._b | 0, 4)
14041 H.writeInt32BE(this._c | 0, 8)
14042 H.writeInt32BE(this._d | 0, 12)
14043 H.writeInt32BE(this._e | 0, 16)
14044
14045 return H
14046 }
14047
14048 module.exports = Sha1
14049
14050 },{"./hash":102,"inherits":96,"safe-buffer":101}],106:[function(require,module,exports){
14051 /**
14052 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14053 * in FIPS 180-2
14054 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14055 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14056 *
14057 */
14058
14059 var inherits = require('inherits')
14060 var Sha256 = require('./sha256')
14061 var Hash = require('./hash')
14062 var Buffer = require('safe-buffer').Buffer
14063
14064 var W = new Array(64)
14065
14066 function Sha224 () {
14067 this.init()
14068
14069 this._w = W // new Array(64)
14070
14071 Hash.call(this, 64, 56)
14072 }
14073
14074 inherits(Sha224, Sha256)
14075
14076 Sha224.prototype.init = function () {
14077 this._a = 0xc1059ed8
14078 this._b = 0x367cd507
14079 this._c = 0x3070dd17
14080 this._d = 0xf70e5939
14081 this._e = 0xffc00b31
14082 this._f = 0x68581511
14083 this._g = 0x64f98fa7
14084 this._h = 0xbefa4fa4
14085
14086 return this
14087 }
14088
14089 Sha224.prototype._hash = function () {
14090 var H = Buffer.allocUnsafe(28)
14091
14092 H.writeInt32BE(this._a, 0)
14093 H.writeInt32BE(this._b, 4)
14094 H.writeInt32BE(this._c, 8)
14095 H.writeInt32BE(this._d, 12)
14096 H.writeInt32BE(this._e, 16)
14097 H.writeInt32BE(this._f, 20)
14098 H.writeInt32BE(this._g, 24)
14099
14100 return H
14101 }
14102
14103 module.exports = Sha224
14104
14105 },{"./hash":102,"./sha256":107,"inherits":96,"safe-buffer":101}],107:[function(require,module,exports){
14106 /**
14107 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14108 * in FIPS 180-2
14109 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14110 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14111 *
14112 */
14113
14114 var inherits = require('inherits')
14115 var Hash = require('./hash')
14116 var Buffer = require('safe-buffer').Buffer
14117
14118 var K = [
14119 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
14120 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
14121 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
14122 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
14123 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
14124 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
14125 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
14126 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
14127 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
14128 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
14129 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
14130 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
14131 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
14132 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
14133 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
14134 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
14135 ]
14136
14137 var W = new Array(64)
14138
14139 function Sha256 () {
14140 this.init()
14141
14142 this._w = W // new Array(64)
14143
14144 Hash.call(this, 64, 56)
14145 }
14146
14147 inherits(Sha256, Hash)
14148
14149 Sha256.prototype.init = function () {
14150 this._a = 0x6a09e667
14151 this._b = 0xbb67ae85
14152 this._c = 0x3c6ef372
14153 this._d = 0xa54ff53a
14154 this._e = 0x510e527f
14155 this._f = 0x9b05688c
14156 this._g = 0x1f83d9ab
14157 this._h = 0x5be0cd19
14158
14159 return this
14160 }
14161
14162 function ch (x, y, z) {
14163 return z ^ (x & (y ^ z))
14164 }
14165
14166 function maj (x, y, z) {
14167 return (x & y) | (z & (x | y))
14168 }
14169
14170 function sigma0 (x) {
14171 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
14172 }
14173
14174 function sigma1 (x) {
14175 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
14176 }
14177
14178 function gamma0 (x) {
14179 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
14180 }
14181
14182 function gamma1 (x) {
14183 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
14184 }
14185
14186 Sha256.prototype._update = function (M) {
14187 var W = this._w
14188
14189 var a = this._a | 0
14190 var b = this._b | 0
14191 var c = this._c | 0
14192 var d = this._d | 0
14193 var e = this._e | 0
14194 var f = this._f | 0
14195 var g = this._g | 0
14196 var h = this._h | 0
14197
14198 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
14199 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
14200
14201 for (var j = 0; j < 64; ++j) {
14202 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
14203 var T2 = (sigma0(a) + maj(a, b, c)) | 0
14204
14205 h = g
14206 g = f
14207 f = e
14208 e = (d + T1) | 0
14209 d = c
14210 c = b
14211 b = a
14212 a = (T1 + T2) | 0
14213 }
14214
14215 this._a = (a + this._a) | 0
14216 this._b = (b + this._b) | 0
14217 this._c = (c + this._c) | 0
14218 this._d = (d + this._d) | 0
14219 this._e = (e + this._e) | 0
14220 this._f = (f + this._f) | 0
14221 this._g = (g + this._g) | 0
14222 this._h = (h + this._h) | 0
14223 }
14224
14225 Sha256.prototype._hash = function () {
14226 var H = Buffer.allocUnsafe(32)
14227
14228 H.writeInt32BE(this._a, 0)
14229 H.writeInt32BE(this._b, 4)
14230 H.writeInt32BE(this._c, 8)
14231 H.writeInt32BE(this._d, 12)
14232 H.writeInt32BE(this._e, 16)
14233 H.writeInt32BE(this._f, 20)
14234 H.writeInt32BE(this._g, 24)
14235 H.writeInt32BE(this._h, 28)
14236
14237 return H
14238 }
14239
14240 module.exports = Sha256
14241
14242 },{"./hash":102,"inherits":96,"safe-buffer":101}],108:[function(require,module,exports){
14243 var inherits = require('inherits')
14244 var SHA512 = require('./sha512')
14245 var Hash = require('./hash')
14246 var Buffer = require('safe-buffer').Buffer
14247
14248 var W = new Array(160)
14249
14250 function Sha384 () {
14251 this.init()
14252 this._w = W
14253
14254 Hash.call(this, 128, 112)
14255 }
14256
14257 inherits(Sha384, SHA512)
14258
14259 Sha384.prototype.init = function () {
14260 this._ah = 0xcbbb9d5d
14261 this._bh = 0x629a292a
14262 this._ch = 0x9159015a
14263 this._dh = 0x152fecd8
14264 this._eh = 0x67332667
14265 this._fh = 0x8eb44a87
14266 this._gh = 0xdb0c2e0d
14267 this._hh = 0x47b5481d
14268
14269 this._al = 0xc1059ed8
14270 this._bl = 0x367cd507
14271 this._cl = 0x3070dd17
14272 this._dl = 0xf70e5939
14273 this._el = 0xffc00b31
14274 this._fl = 0x68581511
14275 this._gl = 0x64f98fa7
14276 this._hl = 0xbefa4fa4
14277
14278 return this
14279 }
14280
14281 Sha384.prototype._hash = function () {
14282 var H = Buffer.allocUnsafe(48)
14283
14284 function writeInt64BE (h, l, offset) {
14285 H.writeInt32BE(h, offset)
14286 H.writeInt32BE(l, offset + 4)
14287 }
14288
14289 writeInt64BE(this._ah, this._al, 0)
14290 writeInt64BE(this._bh, this._bl, 8)
14291 writeInt64BE(this._ch, this._cl, 16)
14292 writeInt64BE(this._dh, this._dl, 24)
14293 writeInt64BE(this._eh, this._el, 32)
14294 writeInt64BE(this._fh, this._fl, 40)
14295
14296 return H
14297 }
14298
14299 module.exports = Sha384
14300
14301 },{"./hash":102,"./sha512":109,"inherits":96,"safe-buffer":101}],109:[function(require,module,exports){
14302 var inherits = require('inherits')
14303 var Hash = require('./hash')
14304 var Buffer = require('safe-buffer').Buffer
14305
14306 var K = [
14307 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
14308 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
14309 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
14310 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
14311 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
14312 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
14313 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
14314 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
14315 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
14316 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
14317 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
14318 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
14319 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
14320 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
14321 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
14322 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
14323 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
14324 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
14325 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
14326 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
14327 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
14328 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
14329 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
14330 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
14331 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
14332 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
14333 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
14334 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
14335 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
14336 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
14337 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
14338 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
14339 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
14340 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
14341 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
14342 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
14343 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
14344 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
14345 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
14346 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
14347 ]
14348
14349 var W = new Array(160)
14350
14351 function Sha512 () {
14352 this.init()
14353 this._w = W
14354
14355 Hash.call(this, 128, 112)
14356 }
14357
14358 inherits(Sha512, Hash)
14359
14360 Sha512.prototype.init = function () {
14361 this._ah = 0x6a09e667
14362 this._bh = 0xbb67ae85
14363 this._ch = 0x3c6ef372
14364 this._dh = 0xa54ff53a
14365 this._eh = 0x510e527f
14366 this._fh = 0x9b05688c
14367 this._gh = 0x1f83d9ab
14368 this._hh = 0x5be0cd19
14369
14370 this._al = 0xf3bcc908
14371 this._bl = 0x84caa73b
14372 this._cl = 0xfe94f82b
14373 this._dl = 0x5f1d36f1
14374 this._el = 0xade682d1
14375 this._fl = 0x2b3e6c1f
14376 this._gl = 0xfb41bd6b
14377 this._hl = 0x137e2179
14378
14379 return this
14380 }
14381
14382 function Ch (x, y, z) {
14383 return z ^ (x & (y ^ z))
14384 }
14385
14386 function maj (x, y, z) {
14387 return (x & y) | (z & (x | y))
14388 }
14389
14390 function sigma0 (x, xl) {
14391 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
14392 }
14393
14394 function sigma1 (x, xl) {
14395 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
14396 }
14397
14398 function Gamma0 (x, xl) {
14399 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
14400 }
14401
14402 function Gamma0l (x, xl) {
14403 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
14404 }
14405
14406 function Gamma1 (x, xl) {
14407 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
14408 }
14409
14410 function Gamma1l (x, xl) {
14411 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
14412 }
14413
14414 function getCarry (a, b) {
14415 return (a >>> 0) < (b >>> 0) ? 1 : 0
14416 }
14417
14418 Sha512.prototype._update = function (M) {
14419 var W = this._w
14420
14421 var ah = this._ah | 0
14422 var bh = this._bh | 0
14423 var ch = this._ch | 0
14424 var dh = this._dh | 0
14425 var eh = this._eh | 0
14426 var fh = this._fh | 0
14427 var gh = this._gh | 0
14428 var hh = this._hh | 0
14429
14430 var al = this._al | 0
14431 var bl = this._bl | 0
14432 var cl = this._cl | 0
14433 var dl = this._dl | 0
14434 var el = this._el | 0
14435 var fl = this._fl | 0
14436 var gl = this._gl | 0
14437 var hl = this._hl | 0
14438
14439 for (var i = 0; i < 32; i += 2) {
14440 W[i] = M.readInt32BE(i * 4)
14441 W[i + 1] = M.readInt32BE(i * 4 + 4)
14442 }
14443 for (; i < 160; i += 2) {
14444 var xh = W[i - 15 * 2]
14445 var xl = W[i - 15 * 2 + 1]
14446 var gamma0 = Gamma0(xh, xl)
14447 var gamma0l = Gamma0l(xl, xh)
14448
14449 xh = W[i - 2 * 2]
14450 xl = W[i - 2 * 2 + 1]
14451 var gamma1 = Gamma1(xh, xl)
14452 var gamma1l = Gamma1l(xl, xh)
14453
14454 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
14455 var Wi7h = W[i - 7 * 2]
14456 var Wi7l = W[i - 7 * 2 + 1]
14457
14458 var Wi16h = W[i - 16 * 2]
14459 var Wi16l = W[i - 16 * 2 + 1]
14460
14461 var Wil = (gamma0l + Wi7l) | 0
14462 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
14463 Wil = (Wil + gamma1l) | 0
14464 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
14465 Wil = (Wil + Wi16l) | 0
14466 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
14467
14468 W[i] = Wih
14469 W[i + 1] = Wil
14470 }
14471
14472 for (var j = 0; j < 160; j += 2) {
14473 Wih = W[j]
14474 Wil = W[j + 1]
14475
14476 var majh = maj(ah, bh, ch)
14477 var majl = maj(al, bl, cl)
14478
14479 var sigma0h = sigma0(ah, al)
14480 var sigma0l = sigma0(al, ah)
14481 var sigma1h = sigma1(eh, el)
14482 var sigma1l = sigma1(el, eh)
14483
14484 // t1 = h + sigma1 + ch + K[j] + W[j]
14485 var Kih = K[j]
14486 var Kil = K[j + 1]
14487
14488 var chh = Ch(eh, fh, gh)
14489 var chl = Ch(el, fl, gl)
14490
14491 var t1l = (hl + sigma1l) | 0
14492 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
14493 t1l = (t1l + chl) | 0
14494 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
14495 t1l = (t1l + Kil) | 0
14496 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
14497 t1l = (t1l + Wil) | 0
14498 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
14499
14500 // t2 = sigma0 + maj
14501 var t2l = (sigma0l + majl) | 0
14502 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
14503
14504 hh = gh
14505 hl = gl
14506 gh = fh
14507 gl = fl
14508 fh = eh
14509 fl = el
14510 el = (dl + t1l) | 0
14511 eh = (dh + t1h + getCarry(el, dl)) | 0
14512 dh = ch
14513 dl = cl
14514 ch = bh
14515 cl = bl
14516 bh = ah
14517 bl = al
14518 al = (t1l + t2l) | 0
14519 ah = (t1h + t2h + getCarry(al, t1l)) | 0
14520 }
14521
14522 this._al = (this._al + al) | 0
14523 this._bl = (this._bl + bl) | 0
14524 this._cl = (this._cl + cl) | 0
14525 this._dl = (this._dl + dl) | 0
14526 this._el = (this._el + el) | 0
14527 this._fl = (this._fl + fl) | 0
14528 this._gl = (this._gl + gl) | 0
14529 this._hl = (this._hl + hl) | 0
14530
14531 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
14532 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
14533 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
14534 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
14535 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
14536 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
14537 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
14538 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
14539 }
14540
14541 Sha512.prototype._hash = function () {
14542 var H = Buffer.allocUnsafe(64)
14543
14544 function writeInt64BE (h, l, offset) {
14545 H.writeInt32BE(h, offset)
14546 H.writeInt32BE(l, offset + 4)
14547 }
14548
14549 writeInt64BE(this._ah, this._al, 0)
14550 writeInt64BE(this._bh, this._bl, 8)
14551 writeInt64BE(this._ch, this._cl, 16)
14552 writeInt64BE(this._dh, this._dl, 24)
14553 writeInt64BE(this._eh, this._el, 32)
14554 writeInt64BE(this._fh, this._fl, 40)
14555 writeInt64BE(this._gh, this._gl, 48)
14556 writeInt64BE(this._hh, this._hl, 56)
14557
14558 return H
14559 }
14560
14561 module.exports = Sha512
14562
14563 },{"./hash":102,"inherits":96,"safe-buffer":101}],110:[function(require,module,exports){
14564 var native = require('./native')
14565
14566 function getTypeName (fn) {
14567 return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1]
14568 }
14569
14570 function getValueTypeName (value) {
14571 return native.Nil(value) ? '' : getTypeName(value.constructor)
14572 }
14573
14574 function getValue (value) {
14575 if (native.Function(value)) return ''
14576 if (native.String(value)) return JSON.stringify(value)
14577 if (value && native.Object(value)) return ''
14578 return value
14579 }
14580
14581 function tfJSON (type) {
14582 if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type)
14583 if (native.Array(type)) return 'Array'
14584 if (type && native.Object(type)) return 'Object'
14585
14586 return type !== undefined ? type : ''
14587 }
14588
14589 function tfErrorString (type, value, valueTypeName) {
14590 var valueJson = getValue(value)
14591
14592 return 'Expected ' + tfJSON(type) + ', got' +
14593 (valueTypeName !== '' ? ' ' + valueTypeName : '') +
14594 (valueJson !== '' ? ' ' + valueJson : '')
14595 }
14596
14597 function TfTypeError (type, value, valueTypeName) {
14598 valueTypeName = valueTypeName || getValueTypeName(value)
14599 this.message = tfErrorString(type, value, valueTypeName)
14600
14601 Error.captureStackTrace(this, TfTypeError)
14602 this.__type = type
14603 this.__value = value
14604 this.__valueTypeName = valueTypeName
14605 }
14606
14607 TfTypeError.prototype = Object.create(Error.prototype)
14608 TfTypeError.prototype.constructor = TfTypeError
14609
14610 function tfPropertyErrorString (type, label, name, value, valueTypeName) {
14611 var description = '" of type '
14612 if (label === 'key') description = '" with key type '
14613
14614 return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName)
14615 }
14616
14617 function TfPropertyTypeError (type, property, label, value, valueTypeName) {
14618 if (type) {
14619 valueTypeName = valueTypeName || getValueTypeName(value)
14620 this.message = tfPropertyErrorString(type, label, property, value, valueTypeName)
14621 } else {
14622 this.message = 'Unexpected property "' + property + '"'
14623 }
14624
14625 Error.captureStackTrace(this, TfTypeError)
14626 this.__label = label
14627 this.__property = property
14628 this.__type = type
14629 this.__value = value
14630 this.__valueTypeName = valueTypeName
14631 }
14632
14633 TfPropertyTypeError.prototype = Object.create(Error.prototype)
14634 TfPropertyTypeError.prototype.constructor = TfTypeError
14635
14636 function tfCustomError (expected, actual) {
14637 return new TfTypeError(expected, {}, actual)
14638 }
14639
14640 function tfSubError (e, property, label) {
14641 // sub child?
14642 if (e instanceof TfPropertyTypeError) {
14643 property = property + '.' + e.__property
14644
14645 e = new TfPropertyTypeError(
14646 e.__type, property, e.__label, e.__value, e.__valueTypeName
14647 )
14648
14649 // child?
14650 } else if (e instanceof TfTypeError) {
14651 e = new TfPropertyTypeError(
14652 e.__type, property, label, e.__value, e.__valueTypeName
14653 )
14654 }
14655
14656 Error.captureStackTrace(e)
14657 return e
14658 }
14659
14660 module.exports = {
14661 TfTypeError: TfTypeError,
14662 TfPropertyTypeError: TfPropertyTypeError,
14663 tfCustomError: tfCustomError,
14664 tfSubError: tfSubError,
14665 tfJSON: tfJSON,
14666 getValueTypeName: getValueTypeName
14667 }
14668
14669 },{"./native":113}],111:[function(require,module,exports){
14670 (function (Buffer){
14671 var NATIVE = require('./native')
14672 var ERRORS = require('./errors')
14673
14674 function _Buffer (value) {
14675 return Buffer.isBuffer(value)
14676 }
14677
14678 function Hex (value) {
14679 return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value)
14680 }
14681
14682 function _LengthN (type, length) {
14683 var name = type.toJSON()
14684
14685 function Length (value) {
14686 if (!type(value)) return false
14687 if (value.length === length) return true
14688
14689 throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')')
14690 }
14691 Length.toJSON = function () { return name }
14692
14693 return Length
14694 }
14695
14696 var _ArrayN = _LengthN.bind(null, NATIVE.Array)
14697 var _BufferN = _LengthN.bind(null, _Buffer)
14698 var _HexN = _LengthN.bind(null, Hex)
14699 var _StringN = _LengthN.bind(null, NATIVE.String)
14700
14701 var UINT53_MAX = Math.pow(2, 53) - 1
14702
14703 function Finite (value) {
14704 return typeof value === 'number' && isFinite(value)
14705 }
14706 function Int8 (value) { return ((value << 24) >> 24) === value }
14707 function Int16 (value) { return ((value << 16) >> 16) === value }
14708 function Int32 (value) { return (value | 0) === value }
14709 function UInt8 (value) { return (value & 0xff) === value }
14710 function UInt16 (value) { return (value & 0xffff) === value }
14711 function UInt32 (value) { return (value >>> 0) === value }
14712 function UInt53 (value) {
14713 return typeof value === 'number' &&
14714 value >= 0 &&
14715 value <= UINT53_MAX &&
14716 Math.floor(value) === value
14717 }
14718
14719 var types = {
14720 ArrayN: _ArrayN,
14721 Buffer: _Buffer,
14722 BufferN: _BufferN,
14723 Finite: Finite,
14724 Hex: Hex,
14725 HexN: _HexN,
14726 Int8: Int8,
14727 Int16: Int16,
14728 Int32: Int32,
14729 StringN: _StringN,
14730 UInt8: UInt8,
14731 UInt16: UInt16,
14732 UInt32: UInt32,
14733 UInt53: UInt53
14734 }
14735
14736 for (var typeName in types) {
14737 types[typeName].toJSON = function (t) {
14738 return t
14739 }.bind(null, typeName)
14740 }
14741
14742 module.exports = types
14743
14744 }).call(this,{"isBuffer":require("../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
14745 },{"../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":10,"./errors":110,"./native":113}],112:[function(require,module,exports){
14746 var ERRORS = require('./errors')
14747 var NATIVE = require('./native')
14748
14749 // short-hand
14750 var tfJSON = ERRORS.tfJSON
14751 var TfTypeError = ERRORS.TfTypeError
14752 var TfPropertyTypeError = ERRORS.TfPropertyTypeError
14753 var tfSubError = ERRORS.tfSubError
14754 var getValueTypeName = ERRORS.getValueTypeName
14755
14756 var TYPES = {
14757 arrayOf: function arrayOf (type) {
14758 type = compile(type)
14759
14760 function _arrayOf (array, strict) {
14761 if (!NATIVE.Array(array)) return false
14762 if (NATIVE.Nil(array)) return false
14763
14764 return array.every(function (value, i) {
14765 try {
14766 return typeforce(type, value, strict)
14767 } catch (e) {
14768 throw tfSubError(e, i)
14769 }
14770 })
14771 }
14772 _arrayOf.toJSON = function () { return '[' + tfJSON(type) + ']' }
14773
14774 return _arrayOf
14775 },
14776
14777 maybe: function maybe (type) {
14778 type = compile(type)
14779
14780 function _maybe (value, strict) {
14781 return NATIVE.Nil(value) || type(value, strict, maybe)
14782 }
14783 _maybe.toJSON = function () { return '?' + tfJSON(type) }
14784
14785 return _maybe
14786 },
14787
14788 map: function map (propertyType, propertyKeyType) {
14789 propertyType = compile(propertyType)
14790 if (propertyKeyType) propertyKeyType = compile(propertyKeyType)
14791
14792 function _map (value, strict) {
14793 if (!NATIVE.Object(value)) return false
14794 if (NATIVE.Nil(value)) return false
14795
14796 for (var propertyName in value) {
14797 try {
14798 if (propertyKeyType) {
14799 typeforce(propertyKeyType, propertyName, strict)
14800 }
14801 } catch (e) {
14802 throw tfSubError(e, propertyName, 'key')
14803 }
14804
14805 try {
14806 var propertyValue = value[propertyName]
14807 typeforce(propertyType, propertyValue, strict)
14808 } catch (e) {
14809 throw tfSubError(e, propertyName)
14810 }
14811 }
14812
14813 return true
14814 }
14815
14816 if (propertyKeyType) {
14817 _map.toJSON = function () {
14818 return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}'
14819 }
14820 } else {
14821 _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }
14822 }
14823
14824 return _map
14825 },
14826
14827 object: function object (uncompiled) {
14828 var type = {}
14829
14830 for (var typePropertyName in uncompiled) {
14831 type[typePropertyName] = compile(uncompiled[typePropertyName])
14832 }
14833
14834 function _object (value, strict) {
14835 if (!NATIVE.Object(value)) return false
14836 if (NATIVE.Nil(value)) return false
14837
14838 var propertyName
14839
14840 try {
14841 for (propertyName in type) {
14842 var propertyType = type[propertyName]
14843 var propertyValue = value[propertyName]
14844
14845 typeforce(propertyType, propertyValue, strict)
14846 }
14847 } catch (e) {
14848 throw tfSubError(e, propertyName)
14849 }
14850
14851 if (strict) {
14852 for (propertyName in value) {
14853 if (type[propertyName]) continue
14854
14855 throw new TfPropertyTypeError(undefined, propertyName)
14856 }
14857 }
14858
14859 return true
14860 }
14861 _object.toJSON = function () { return tfJSON(type) }
14862
14863 return _object
14864 },
14865
14866 oneOf: function oneOf () {
14867 var types = [].slice.call(arguments).map(compile)
14868
14869 function _oneOf (value, strict) {
14870 return types.some(function (type) {
14871 try {
14872 return typeforce(type, value, strict)
14873 } catch (e) {
14874 return false
14875 }
14876 })
14877 }
14878 _oneOf.toJSON = function () { return types.map(tfJSON).join('|') }
14879
14880 return _oneOf
14881 },
14882
14883 quacksLike: function quacksLike (type) {
14884 function _quacksLike (value) {
14885 return type === getValueTypeName(value)
14886 }
14887 _quacksLike.toJSON = function () { return type }
14888
14889 return _quacksLike
14890 },
14891
14892 tuple: function tuple () {
14893 var types = [].slice.call(arguments).map(compile)
14894
14895 function _tuple (values, strict) {
14896 if (NATIVE.Nil(values)) return false
14897 if (NATIVE.Nil(values.length)) return false
14898 if (strict && (values.length !== types.length)) return false
14899
14900 return types.every(function (type, i) {
14901 try {
14902 return typeforce(type, values[i], strict)
14903 } catch (e) {
14904 throw tfSubError(e, i)
14905 }
14906 })
14907 }
14908 _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }
14909
14910 return _tuple
14911 },
14912
14913 value: function value (expected) {
14914 function _value (actual) {
14915 return actual === expected
14916 }
14917 _value.toJSON = function () { return expected }
14918
14919 return _value
14920 }
14921 }
14922
14923 function compile (type) {
14924 if (NATIVE.String(type)) {
14925 if (type[0] === '?') return TYPES.maybe(type.slice(1))
14926
14927 return NATIVE[type] || TYPES.quacksLike(type)
14928 } else if (type && NATIVE.Object(type)) {
14929 if (NATIVE.Array(type)) return TYPES.arrayOf(type[0])
14930
14931 return TYPES.object(type)
14932 } else if (NATIVE.Function(type)) {
14933 return type
14934 }
14935
14936 return TYPES.value(type)
14937 }
14938
14939 function typeforce (type, value, strict, surrogate) {
14940 if (NATIVE.Function(type)) {
14941 if (type(value, strict)) return true
14942
14943 throw new TfTypeError(surrogate || type, value)
14944 }
14945
14946 // JIT
14947 return typeforce(compile(type), value, strict)
14948 }
14949
14950 // assign types to typeforce function
14951 for (var typeName in NATIVE) {
14952 typeforce[typeName] = NATIVE[typeName]
14953 }
14954
14955 for (typeName in TYPES) {
14956 typeforce[typeName] = TYPES[typeName]
14957 }
14958
14959 var EXTRA = require('./extra')
14960 for (typeName in EXTRA) {
14961 typeforce[typeName] = EXTRA[typeName]
14962 }
14963
14964 // async wrapper
14965 function __async (type, value, strict, callback) {
14966 // default to falsy strict if using shorthand overload
14967 if (typeof strict === 'function') return __async(type, value, false, strict)
14968
14969 try {
14970 typeforce(type, value, strict)
14971 } catch (e) {
14972 return callback(e)
14973 }
14974
14975 callback()
14976 }
14977
14978 typeforce.async = __async
14979 typeforce.compile = compile
14980 typeforce.TfTypeError = TfTypeError
14981 typeforce.TfPropertyTypeError = TfPropertyTypeError
14982
14983 module.exports = typeforce
14984
14985 },{"./errors":110,"./extra":111,"./native":113}],113:[function(require,module,exports){
14986 var types = {
14987 Array: function (value) { return value !== null && value !== undefined && value.constructor === Array },
14988 Boolean: function (value) { return typeof value === 'boolean' },
14989 Function: function (value) { return typeof value === 'function' },
14990 Nil: function (value) { return value === undefined || value === null },
14991 Number: function (value) { return typeof value === 'number' },
14992 Object: function (value) { return typeof value === 'object' },
14993 String: function (value) { return typeof value === 'string' },
14994 '': function () { return true }
14995 }
14996
14997 // TODO: deprecate
14998 types.Null = types.Nil
14999
15000 for (var typeName in types) {
15001 types[typeName].toJSON = function (t) {
15002 return t
15003 }.bind(null, typeName)
15004 }
15005
15006 module.exports = types
15007
15008 },{}],114:[function(require,module,exports){
15009 'use strict'
15010 var Buffer = require('safe-buffer').Buffer
15011
15012 // Number.MAX_SAFE_INTEGER
15013 var MAX_SAFE_INTEGER = 9007199254740991
15014
15015 function checkUInt53 (n) {
15016 if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range')
15017 }
15018
15019 function encode (number, buffer, offset) {
15020 checkUInt53(number)
15021
15022 if (!buffer) buffer = Buffer.allocUnsafe(encodingLength(number))
15023 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
15024 if (!offset) offset = 0
15025
15026 // 8 bit
15027 if (number < 0xfd) {
15028 buffer.writeUInt8(number, offset)
15029 encode.bytes = 1
15030
15031 // 16 bit
15032 } else if (number <= 0xffff) {
15033 buffer.writeUInt8(0xfd, offset)
15034 buffer.writeUInt16LE(number, offset + 1)
15035 encode.bytes = 3
15036
15037 // 32 bit
15038 } else if (number <= 0xffffffff) {
15039 buffer.writeUInt8(0xfe, offset)
15040 buffer.writeUInt32LE(number, offset + 1)
15041 encode.bytes = 5
15042
15043 // 64 bit
15044 } else {
15045 buffer.writeUInt8(0xff, offset)
15046 buffer.writeUInt32LE(number >>> 0, offset + 1)
15047 buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5)
15048 encode.bytes = 9
15049 }
15050
15051 return buffer
15052 }
15053
15054 function decode (buffer, offset) {
15055 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
15056 if (!offset) offset = 0
15057
15058 var first = buffer.readUInt8(offset)
15059
15060 // 8 bit
15061 if (first < 0xfd) {
15062 decode.bytes = 1
15063 return first
15064
15065 // 16 bit
15066 } else if (first === 0xfd) {
15067 decode.bytes = 3
15068 return buffer.readUInt16LE(offset + 1)
15069
15070 // 32 bit
15071 } else if (first === 0xfe) {
15072 decode.bytes = 5
15073 return buffer.readUInt32LE(offset + 1)
15074
15075 // 64 bit
15076 } else {
15077 decode.bytes = 9
15078 var lo = buffer.readUInt32LE(offset + 1)
15079 var hi = buffer.readUInt32LE(offset + 5)
15080 var number = hi * 0x0100000000 + lo
15081 checkUInt53(number)
15082
15083 return number
15084 }
15085 }
15086
15087 function encodingLength (number) {
15088 checkUInt53(number)
15089
15090 return (
15091 number < 0xfd ? 1
15092 : number <= 0xffff ? 3
15093 : number <= 0xffffffff ? 5
15094 : 9
15095 )
15096 }
15097
15098 module.exports = { encode: encode, decode: decode, encodingLength: encodingLength }
15099
15100 },{"safe-buffer":101}],115:[function(require,module,exports){
15101 (function (Buffer){
15102 var bs58check = require('bs58check')
15103
15104 function decodeRaw (buffer, version) {
15105 // check version only if defined
15106 if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version')
15107
15108 // uncompressed
15109 if (buffer.length === 33) {
15110 return {
15111 version: buffer[0],
15112 privateKey: buffer.slice(1, 33),
15113 compressed: false
15114 }
15115 }
15116
15117 // invalid length
15118 if (buffer.length !== 34) throw new Error('Invalid WIF length')
15119
15120 // invalid compression flag
15121 if (buffer[33] !== 0x01) throw new Error('Invalid compression flag')
15122
15123 return {
15124 version: buffer[0],
15125 privateKey: buffer.slice(1, 33),
15126 compressed: true
15127 }
15128 }
15129
15130 function encodeRaw (version, privateKey, compressed) {
15131 var result = new Buffer(compressed ? 34 : 33)
15132
15133 result.writeUInt8(version, 0)
15134 privateKey.copy(result, 1)
15135
15136 if (compressed) {
15137 result[33] = 0x01
15138 }
15139
15140 return result
15141 }
15142
15143 function decode (string, version) {
15144 return decodeRaw(bs58check.decode(string), version)
15145 }
15146
15147 function encode (version, privateKey, compressed) {
15148 if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed))
15149
15150 return bs58check.encode(
15151 encodeRaw(
15152 version.version,
15153 version.privateKey,
15154 version.compressed
15155 )
15156 )
15157 }
15158
15159 module.exports = {
15160 decode: decode,
15161 decodeRaw: decodeRaw,
15162 encode: encode,
15163 encodeRaw: encodeRaw
15164 }
15165
15166 }).call(this,require("buffer").Buffer)
15167 },{"bs58check":83,"buffer":5}]},{},[34])(34)
15168 });