]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blame - src/js/bitcoinjs-3.3.2.js
Merge pull request #210 from potatohodler/patch/vertcoin
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / bitcoinjs-3.3.2.js
CommitLineData
a0091a40
IC
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 */
14function 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}
38function 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
71var util = require('util/');
72var hasOwn = Object.prototype.hasOwnProperty;
73var pSlice = Array.prototype.slice;
74var functionsHaveNames = (function () {
75 return function foo() {}.name === 'foo';
76}());
77function pToString (obj) {
78 return Object.prototype.toString.call(obj);
79}
80function 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
105var 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
112var regex = /\s*function\s+([^\(\s]*)\s*/;
113// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
114function 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}
125assert.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
162util.inherits(assert.AssertionError, Error);
163
164function 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}
171function 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}
179function 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
196function 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.
207assert.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
216function ok(value, message) {
217 if (!value) fail(value, true, message, '==', assert.ok);
218}
219assert.ok = ok;
220
221// 5. The equality assertion tests shallow, coercive equality with
222// ==.
223// assert.equal(actual, expected, message_opt);
224
225assert.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
232assert.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
241assert.deepEqual = function deepEqual(actual, expected, message) {
242 if (!_deepEqual(actual, expected, false)) {
243 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
244 }
245};
246
247assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
248 if (!_deepEqual(actual, expected, true)) {
249 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
250 }
251};
252
253function _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
319function isArguments(object) {
320 return Object.prototype.toString.call(object) == '[object Arguments]';
321}
322
323function 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
368assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
369 if (_deepEqual(actual, expected, false)) {
370 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
371 }
372};
373
374assert.notDeepStrictEqual = notDeepStrictEqual;
375function 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
385assert.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
394assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
395 if (actual === expected) {
396 fail(actual, expected, message, '!==', assert.notStrictEqual);
397 }
398};
399
400function 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
424function _tryBlock(block) {
425 var error;
426 try {
427 block();
428 } catch (e) {
429 error = e;
430 }
431 return error;
432}
433
434function _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
475assert.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.
480assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
481 _throws(false, block, error, message);
482};
483
484assert.ifError = function(err) { if (err) throw err; };
485
486var 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 : {})
9f59e99b 495},{"util/":33}],2:[function(require,module,exports){
a0091a40
IC
496'use strict'
497
498exports.byteLength = byteLength
499exports.toByteArray = toByteArray
500exports.fromByteArray = fromByteArray
501
502var lookup = []
503var revLookup = []
504var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
505
506var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
507for (var i = 0, len = code.length; i < len; ++i) {
508 lookup[i] = code[i]
509 revLookup[code.charCodeAt(i)] = i
510}
511
512revLookup['-'.charCodeAt(0)] = 62
513revLookup['_'.charCodeAt(0)] = 63
514
515function 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
529function byteLength (b64) {
530 // base64 is 4/3 + up to two characters of the original data
9f59e99b 531 return b64.length * 3 / 4 - placeHoldersCount(b64)
a0091a40
IC
532}
533
534function toByteArray (b64) {
9f59e99b 535 var i, j, l, tmp, placeHolders, arr
a0091a40
IC
536 var len = b64.length
537 placeHolders = placeHoldersCount(b64)
538
9f59e99b 539 arr = new Arr(len * 3 / 4 - placeHolders)
a0091a40
IC
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
9f59e99b 546 for (i = 0, j = 0; i < l; i += 4, j += 3) {
a0091a40
IC
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
565function tripletToBase64 (num) {
566 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
567}
568
569function 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
579function 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){
9f59e99b
IC
614(function (global){
615'use strict';
616
617var buffer = require('buffer');
618var Buffer = buffer.Buffer;
619var SlowBuffer = buffer.SlowBuffer;
620var MAX_LEN = buffer.kMaxLength || 2147483647;
621exports.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}
653exports.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}
665exports.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}
711exports.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){
a0091a40
IC
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
736var base64 = require('base64-js')
737var ieee754 = require('ieee754')
738
739exports.Buffer = Buffer
740exports.SlowBuffer = SlowBuffer
741exports.INSPECT_MAX_BYTES = 50
742
743var K_MAX_LENGTH = 0x7fffffff
744exports.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 */
760Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
761
762if (!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
770function 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
781function 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
801function 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
815if (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
825Buffer.poolSize = 8192 // not used by this implementation
826
827function 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 **/
851Buffer.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
857Buffer.prototype.__proto__ = Uint8Array.prototype
858Buffer.__proto__ = Uint8Array
859
860function 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
868function 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 **/
888Buffer.alloc = function (size, fill, encoding) {
889 return alloc(size, fill, encoding)
890}
891
892function 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 * */
900Buffer.allocUnsafe = function (size) {
901 return allocUnsafe(size)
902}
903/**
904 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
905 */
906Buffer.allocUnsafeSlow = function (size) {
907 return allocUnsafe(size)
908}
909
910function 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
934function 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
943function 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
966function 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
995function 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
1005function SlowBuffer (length) {
1006 if (+length != length) { // eslint-disable-line eqeqeq
1007 length = 0
1008 }
1009 return Buffer.alloc(+length)
1010}
1011
1012Buffer.isBuffer = function isBuffer (b) {
1013 return b != null && b._isBuffer === true
1014}
1015
1016Buffer.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
1039Buffer.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
1058Buffer.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
1088function 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}
1130Buffer.byteLength = byteLength
1131
1132function 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
1208Buffer.prototype._isBuffer = true
1209
1210function swap (b, n, m) {
1211 var i = b[n]
1212 b[n] = b[m]
1213 b[m] = i
1214}
1215
1216Buffer.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
1227Buffer.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
1239Buffer.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
1253Buffer.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
1260Buffer.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
1266Buffer.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
1276Buffer.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
1344function 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
1400function 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
1456Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
1457 return this.indexOf(val, byteOffset, encoding) !== -1
1458}
1459
1460Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
1461 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
1462}
1463
1464Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
1465 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
1466}
1467
1468function 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
1495function utf8Write (buf, string, offset, length) {
1496 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
1497}
1498
1499function asciiWrite (buf, string, offset, length) {
1500 return blitBuffer(asciiToBytes(string), buf, offset, length)
1501}
1502
1503function latin1Write (buf, string, offset, length) {
1504 return asciiWrite(buf, string, offset, length)
1505}
1506
1507function base64Write (buf, string, offset, length) {
1508 return blitBuffer(base64ToBytes(string), buf, offset, length)
1509}
1510
1511function ucs2Write (buf, string, offset, length) {
1512 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
1513}
1514
1515Buffer.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
1586Buffer.prototype.toJSON = function toJSON () {
1587 return {
1588 type: 'Buffer',
1589 data: Array.prototype.slice.call(this._arr || this, 0)
1590 }
1591}
1592
1593function 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
1601function 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
1677var MAX_ARGUMENTS_LENGTH = 0x1000
1678
1679function 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
1697function 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
1707function 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
1717function 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
1730function 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
1739Buffer.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 */
1769function 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
1774Buffer.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
1789Buffer.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
1805Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1806 offset = offset >>> 0
1807 if (!noAssert) checkOffset(offset, 1, this.length)
1808 return this[offset]
1809}
1810
1811Buffer.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
1817Buffer.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
1823Buffer.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
1833Buffer.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
1843Buffer.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
1861Buffer.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
1879Buffer.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
1886Buffer.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
1893Buffer.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
1900Buffer.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
1910Buffer.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
1920Buffer.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
1926Buffer.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
1932Buffer.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
1938Buffer.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
1944function 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
1950Buffer.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
1969Buffer.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
1988Buffer.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
1996Buffer.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
2005Buffer.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
2014Buffer.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
2025Buffer.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
2036Buffer.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
2059Buffer.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
2082Buffer.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
2091Buffer.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
2100Buffer.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
2109Buffer.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
2120Buffer.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
2132function 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
2137function 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
2147Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
2148 return writeFloat(this, value, offset, true, noAssert)
2149}
2150
2151Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
2152 return writeFloat(this, value, offset, false, noAssert)
2153}
2154
2155function 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
2165Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
2166 return writeDouble(this, value, offset, true, noAssert)
2167}
2168
2169Buffer.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)
2174Buffer.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])
2226Buffer.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
2288var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
2289
2290function 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
2302function toHex (n) {
2303 if (n < 16) return '0' + n.toString(16)
2304 return n.toString(16)
2305}
2306
2307function 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
2387function 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
2396function 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
2412function base64ToBytes (str) {
2413 return base64.toByteArray(base64clean(str))
2414}
2415
2416function 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`
2425function isArrayBufferView (obj) {
2426 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
2427}
2428
2429function numberIsNaN (obj) {
2430 return obj !== obj // eslint-disable-line no-self-compare
2431}
2432
9f59e99b 2433},{"base64-js":2,"ieee754":8}],6:[function(require,module,exports){
a0091a40
IC
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
2459function isArray(arg) {
2460 if (Array.isArray) {
2461 return Array.isArray(arg);
2462 }
2463 return objectToString(arg) === '[object Array]';
2464}
2465exports.isArray = isArray;
2466
2467function isBoolean(arg) {
2468 return typeof arg === 'boolean';
2469}
2470exports.isBoolean = isBoolean;
2471
2472function isNull(arg) {
2473 return arg === null;
2474}
2475exports.isNull = isNull;
2476
2477function isNullOrUndefined(arg) {
2478 return arg == null;
2479}
2480exports.isNullOrUndefined = isNullOrUndefined;
2481
2482function isNumber(arg) {
2483 return typeof arg === 'number';
2484}
2485exports.isNumber = isNumber;
2486
2487function isString(arg) {
2488 return typeof arg === 'string';
2489}
2490exports.isString = isString;
2491
2492function isSymbol(arg) {
2493 return typeof arg === 'symbol';
2494}
2495exports.isSymbol = isSymbol;
2496
2497function isUndefined(arg) {
2498 return arg === void 0;
2499}
2500exports.isUndefined = isUndefined;
2501
2502function isRegExp(re) {
2503 return objectToString(re) === '[object RegExp]';
2504}
2505exports.isRegExp = isRegExp;
2506
2507function isObject(arg) {
2508 return typeof arg === 'object' && arg !== null;
2509}
2510exports.isObject = isObject;
2511
2512function isDate(d) {
2513 return objectToString(d) === '[object Date]';
2514}
2515exports.isDate = isDate;
2516
2517function isError(e) {
2518 return (objectToString(e) === '[object Error]' || e instanceof Error);
2519}
2520exports.isError = isError;
2521
2522function isFunction(arg) {
2523 return typeof arg === 'function';
2524}
2525exports.isFunction = isFunction;
2526
2527function 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}
2535exports.isPrimitive = isPrimitive;
2536
2537exports.isBuffer = Buffer.isBuffer;
2538
2539function objectToString(o) {
2540 return Object.prototype.toString.call(o);
2541}
2542
2543}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
9f59e99b 2544},{"../../is-buffer/index.js":10}],7:[function(require,module,exports){
a0091a40
IC
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
2566function EventEmitter() {
2567 this._events = this._events || {};
2568 this._maxListeners = this._maxListeners || undefined;
2569}
2570module.exports = EventEmitter;
2571
2572// Backwards-compat with node 0.10.x
2573EventEmitter.EventEmitter = EventEmitter;
2574
2575EventEmitter.prototype._events = undefined;
2576EventEmitter.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.
2580EventEmitter.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.
2584EventEmitter.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
2591EventEmitter.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
2646EventEmitter.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
2696EventEmitter.prototype.on = EventEmitter.prototype.addListener;
2697
2698EventEmitter.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
2720EventEmitter.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
2765EventEmitter.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
2805EventEmitter.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
2816EventEmitter.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
2828EventEmitter.listenerCount = function(emitter, type) {
2829 return emitter.listenerCount(type);
2830};
2831
2832function isFunction(arg) {
2833 return typeof arg === 'function';
2834}
2835
2836function isNumber(arg) {
2837 return typeof arg === 'number';
2838}
2839
2840function isObject(arg) {
2841 return typeof arg === 'object' && arg !== null;
2842}
2843
2844function isUndefined(arg) {
2845 return arg === void 0;
2846}
2847
9f59e99b 2848},{}],8:[function(require,module,exports){
a0091a40
IC
2849exports.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
2882exports.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
9f59e99b 2934},{}],9:[function(require,module,exports){
a0091a40
IC
2935if (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
9f59e99b 2959},{}],10:[function(require,module,exports){
a0091a40
IC
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
2969module.exports = function (obj) {
2970 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
2971}
2972
2973function 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.
2978function isSlowBuffer (obj) {
2979 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
2980}
2981
9f59e99b 2982},{}],11:[function(require,module,exports){
a0091a40
IC
2983var toString = {}.toString;
2984
2985module.exports = Array.isArray || function (arr) {
2986 return toString.call(arr) == '[object Array]';
2987};
2988
9f59e99b 2989},{}],12:[function(require,module,exports){
a0091a40
IC
2990(function (process){
2991'use strict';
2992
2993if (!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
3001function 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'))
9f59e99b 3036},{"_process":13}],13:[function(require,module,exports){
a0091a40
IC
3037// shim for using process in browser
3038var 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
3045var cachedSetTimeout;
3046var cachedClearTimeout;
3047
3048function defaultSetTimout() {
3049 throw new Error('setTimeout has not been defined');
3050}
3051function 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} ())
3074function 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}
3099function 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}
3126var queue = [];
3127var draining = false;
3128var currentQueue;
3129var queueIndex = -1;
3130
3131function 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
3146function 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
3170process.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
3184function Item(fun, array) {
3185 this.fun = fun;
3186 this.array = array;
3187}
3188Item.prototype.run = function () {
3189 this.fun.apply(null, this.array);
3190};
3191process.title = 'browser';
3192process.browser = true;
3193process.env = {};
3194process.argv = [];
3195process.version = ''; // empty string to avoid regexp issues
3196process.versions = {};
3197
3198function noop() {}
3199
3200process.on = noop;
3201process.addListener = noop;
3202process.once = noop;
3203process.off = noop;
3204process.removeListener = noop;
3205process.removeAllListeners = noop;
3206process.emit = noop;
3207process.prependListener = noop;
3208process.prependOnceListener = noop;
3209
3210process.listeners = function (name) { return [] }
3211
3212process.binding = function (name) {
3213 throw new Error('process.binding is not supported');
3214};
3215
3216process.cwd = function () { return '/' };
3217process.chdir = function (dir) {
3218 throw new Error('process.chdir is not supported');
3219};
3220process.umask = function() { return 0; };
3221
9f59e99b 3222},{}],14:[function(require,module,exports){
a0091a40
IC
3223module.exports = require('./lib/_stream_duplex.js');
3224
9f59e99b 3225},{"./lib/_stream_duplex.js":15}],15:[function(require,module,exports){
a0091a40
IC
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
a0091a40
IC
3235var 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
3243module.exports = Duplex;
3244
9f59e99b
IC
3245/*<replacement>*/
3246var processNextTick = require('process-nextick-args');
3247/*</replacement>*/
3248
a0091a40
IC
3249/*<replacement>*/
3250var util = require('core-util-is');
3251util.inherits = require('inherits');
3252/*</replacement>*/
3253
3254var Readable = require('./_stream_readable');
3255var Writable = require('./_stream_writable');
3256
3257util.inherits(Duplex, Readable);
3258
3259var keys = objectKeys(Writable.prototype);
3260for (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
3265function 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
3282function 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
3292function onEndNT(self) {
3293 self.end();
3294}
3295
a0091a40
IC
3296function forEach(xs, f) {
3297 for (var i = 0, l = xs.length; i < l; i++) {
3298 f(xs[i], i);
3299 }
3300}
9f59e99b 3301},{"./_stream_readable":17,"./_stream_writable":19,"core-util-is":6,"inherits":9,"process-nextick-args":12}],16:[function(require,module,exports){
a0091a40
IC
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
3308module.exports = PassThrough;
3309
3310var Transform = require('./_stream_transform');
3311
3312/*<replacement>*/
3313var util = require('core-util-is');
3314util.inherits = require('inherits');
3315/*</replacement>*/
3316
3317util.inherits(PassThrough, Transform);
3318
3319function PassThrough(options) {
3320 if (!(this instanceof PassThrough)) return new PassThrough(options);
3321
3322 Transform.call(this, options);
3323}
3324
3325PassThrough.prototype._transform = function (chunk, encoding, cb) {
3326 cb(null, chunk);
3327};
9f59e99b
IC
3328},{"./_stream_transform":18,"core-util-is":6,"inherits":9}],17:[function(require,module,exports){
3329(function (process){
a0091a40
IC
3330'use strict';
3331
9f59e99b 3332module.exports = Readable;
a0091a40 3333
9f59e99b 3334/*<replacement>*/
a0091a40
IC
3335var processNextTick = require('process-nextick-args');
3336/*</replacement>*/
3337
a0091a40
IC
3338/*<replacement>*/
3339var isArray = require('isarray');
3340/*</replacement>*/
3341
3342/*<replacement>*/
3343var Duplex;
3344/*</replacement>*/
3345
3346Readable.ReadableState = ReadableState;
3347
3348/*<replacement>*/
3349var EE = require('events').EventEmitter;
3350
3351var EElistenerCount = function (emitter, type) {
3352 return emitter.listeners(type).length;
3353};
3354/*</replacement>*/
3355
3356/*<replacement>*/
3357var Stream = require('./internal/streams/stream');
3358/*</replacement>*/
3359
9f59e99b 3360var Buffer = require('buffer').Buffer;
a0091a40 3361/*<replacement>*/
9f59e99b 3362var bufferShim = require('buffer-shims');
a0091a40
IC
3363/*</replacement>*/
3364
3365/*<replacement>*/
3366var util = require('core-util-is');
3367util.inherits = require('inherits');
3368/*</replacement>*/
3369
3370/*<replacement>*/
3371var debugUtil = require('util');
3372var debug = void 0;
3373if (debugUtil && debugUtil.debuglog) {
3374 debug = debugUtil.debuglog('stream');
3375} else {
3376 debug = function () {};
3377}
3378/*</replacement>*/
3379
3380var BufferList = require('./internal/streams/BufferList');
a0091a40
IC
3381var StringDecoder;
3382
3383util.inherits(Readable, Stream);
3384
3385var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
3386
3387function 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
3401function 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.
9f59e99b 3419 this.highWaterMark = ~~this.highWaterMark;
a0091a40
IC
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
9f59e99b
IC
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.
a0091a40
IC
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
a0091a40
IC
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
9f59e99b
IC
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
a0091a40
IC
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
3470function 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
9f59e99b 3480 if (options && typeof options.read === 'function') this._read = options.read;
a0091a40
IC
3481
3482 Stream.call(this);
3483}
3484
a0091a40
IC
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.
3489Readable.prototype.push = function (chunk, encoding) {
3490 var state = this._readableState;
a0091a40 3491
9f59e99b
IC
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 = '';
a0091a40 3497 }
a0091a40
IC
3498 }
3499
9f59e99b 3500 return readableAddChunk(this, state, chunk, encoding, false);
a0091a40
IC
3501};
3502
3503// Unshift should *always* be something directly out of read()
3504Readable.prototype.unshift = function (chunk) {
9f59e99b
IC
3505 var state = this._readableState;
3506 return readableAddChunk(this, state, chunk, '', true);
a0091a40
IC
3507};
3508
9f59e99b
IC
3509Readable.prototype.isPaused = function () {
3510 return this._readableState.flowing === false;
3511};
3512
3513function 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) {
a0091a40
IC
3518 state.reading = false;
3519 onEofChunk(stream, state);
9f59e99b
IC
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);
a0091a40 3543 } else {
9f59e99b
IC
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);
a0091a40
IC
3549 }
3550 }
9f59e99b
IC
3551
3552 maybeReadMore(stream, state);
a0091a40 3553 }
9f59e99b
IC
3554 } else if (!addToFront) {
3555 state.reading = false;
a0091a40
IC
3556 }
3557
3558 return needMoreData(state);
3559}
3560
a0091a40
IC
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.
3568function needMoreData(state) {
3569 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
3570}
3571
a0091a40
IC
3572// backwards compatibility.
3573Readable.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
3581var MAX_HWM = 0x800000;
3582function 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.
3601function 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.
3620Readable.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
9f59e99b
IC
3720function 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
a0091a40
IC
3728function 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.
3746function 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
3756function 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.
3768function maybeReadMore(stream, state) {
3769 if (!state.readingMore) {
3770 state.readingMore = true;
3771 processNextTick(maybeReadMore_, stream, state);
3772 }
3773}
3774
3775function 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.
3791Readable.prototype._read = function (n) {
3792 this.emit('error', new Error('_read() is not implemented'));
3793};
3794
3795Readable.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
9f59e99b 3815 var endFn = doEnd ? onend : cleanup;
a0091a40
IC
3816 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
3817
3818 dest.on('unpipe', onunpipe);
9f59e99b 3819 function onunpipe(readable) {
a0091a40
IC
3820 debug('onunpipe');
3821 if (readable === src) {
9f59e99b 3822 cleanup();
a0091a40
IC
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);
9f59e99b 3848 src.removeListener('end', cleanup);
a0091a40
IC
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
3927function 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
3939Readable.prototype.unpipe = function (dest) {
3940 var state = this._readableState;
a0091a40
IC
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;
9f59e99b 3956 if (dest) dest.emit('unpipe', this);
a0091a40
IC
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++) {
9f59e99b 3971 dests[i].emit('unpipe', this);
a0091a40
IC
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
9f59e99b 3983 dest.emit('unpipe', this);
a0091a40
IC
3984
3985 return this;
3986};
3987
3988// set up data events if they are asked for
3989// Ensure readable listeners eventually get something
3990Readable.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) {
9f59e99b 4004 emitReadable(this, state);
a0091a40
IC
4005 }
4006 }
4007 }
4008
4009 return res;
4010};
4011Readable.prototype.addListener = Readable.prototype.on;
4012
4013function 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.
4020Readable.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
4030function resume(stream, state) {
4031 if (!state.resumeScheduled) {
4032 state.resumeScheduled = true;
4033 processNextTick(resume_, stream, state);
4034 }
4035}
4036
4037function 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
4050Readable.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
4060function 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.
4069Readable.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.
4129Readable._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.
4135function 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.
4155function 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.
4175function 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.
4204function copyFromBuffer(n, list) {
9f59e99b 4205 var ret = bufferShim.allocUnsafe(n);
a0091a40
IC
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
4231function 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
4244function 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
4253function forEach(xs, f) {
4254 for (var i = 0, l = xs.length; i < l; i++) {
4255 f(xs[i], i);
4256 }
4257}
4258
4259function 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}
9f59e99b
IC
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){
a0091a40
IC
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
4311module.exports = Transform;
4312
4313var Duplex = require('./_stream_duplex');
4314
4315/*<replacement>*/
4316var util = require('core-util-is');
4317util.inherits = require('inherits');
4318/*</replacement>*/
4319
4320util.inherits(Transform, Duplex);
4321
4322function 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
4334function afterTransform(stream, er, data) {
4335 var ts = stream._transformState;
4336 ts.transforming = false;
4337
4338 var cb = ts.writecb;
4339
9f59e99b 4340 if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
a0091a40
IC
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
4356function 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
4387Transform.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.
4402Transform.prototype._transform = function (chunk, encoding, cb) {
4403 throw new Error('_transform() is not implemented');
4404};
4405
4406Transform.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.
4420Transform.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
a0091a40
IC
4433function 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}
9f59e99b
IC
4449},{"./_stream_duplex":15,"core-util-is":6,"inherits":9}],19:[function(require,module,exports){
4450(function (process){
a0091a40
IC
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
9f59e99b 4457module.exports = Writable;
a0091a40 4458
9f59e99b 4459/*<replacement>*/
a0091a40
IC
4460var processNextTick = require('process-nextick-args');
4461/*</replacement>*/
4462
a0091a40
IC
4463/*<replacement>*/
4464var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
4465/*</replacement>*/
4466
4467/*<replacement>*/
4468var Duplex;
4469/*</replacement>*/
4470
4471Writable.WritableState = WritableState;
4472
4473/*<replacement>*/
4474var util = require('core-util-is');
4475util.inherits = require('inherits');
4476/*</replacement>*/
4477
4478/*<replacement>*/
4479var internalUtil = {
4480 deprecate: require('util-deprecate')
4481};
4482/*</replacement>*/
4483
4484/*<replacement>*/
4485var Stream = require('./internal/streams/stream');
4486/*</replacement>*/
4487
9f59e99b 4488var Buffer = require('buffer').Buffer;
a0091a40 4489/*<replacement>*/
9f59e99b 4490var bufferShim = require('buffer-shims');
a0091a40
IC
4491/*</replacement>*/
4492
a0091a40
IC
4493util.inherits(Writable, Stream);
4494
4495function nop() {}
4496
9f59e99b
IC
4497function WriteReq(chunk, encoding, cb) {
4498 this.chunk = chunk;
4499 this.encoding = encoding;
4500 this.callback = cb;
4501 this.next = null;
4502}
4503
a0091a40
IC
4504function 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.
9f59e99b 4523 this.highWaterMark = ~~this.highWaterMark;
a0091a40
IC
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
a0091a40
IC
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
4600WritableState.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();
9f59e99b 4615 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
a0091a40
IC
4616 });
4617 } catch (_) {}
4618})();
4619
4620// Test _writableState for inheritance to account for Duplex streams,
4621// whose prototype chain only points to Readable.
4622var realHasInstance;
4623if (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
4638function 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;
a0091a40
IC
4661 }
4662
4663 Stream.call(this);
4664}
4665
4666// Otherwise people can pipe Writable streams, which is just wrong.
4667Writable.prototype.pipe = function () {
4668 this.emit('error', new Error('Cannot pipe, not readable'));
4669};
4670
4671function 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.
4681function 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
4698Writable.prototype.write = function (chunk, encoding, cb) {
4699 var state = this._writableState;
4700 var ret = false;
9f59e99b 4701 var isBuf = Buffer.isBuffer(chunk);
a0091a40
IC
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
4720Writable.prototype.cork = function () {
4721 var state = this._writableState;
4722
4723 state.corked++;
4724};
4725
4726Writable.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
4736Writable.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
4744function decodeChunk(state, chunk, encoding) {
4745 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
9f59e99b 4746 chunk = bufferShim.from(chunk, encoding);
a0091a40
IC
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.
4754function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
4755 if (!isBuf) {
9f59e99b
IC
4756 chunk = decodeChunk(state, chunk, encoding);
4757 if (Buffer.isBuffer(chunk)) encoding = 'buffer';
a0091a40
IC
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;
9f59e99b 4769 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
a0091a40
IC
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
4783function 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
4792function onwriteError(stream, state, sync, er, cb) {
4793 --state.pendingcb;
9f59e99b 4794 if (sync) processNextTick(cb, er);else cb(er);
a0091a40 4795
9f59e99b
IC
4796 stream._writableState.errorEmitted = true;
4797 stream.emit('error', er);
a0091a40
IC
4798}
4799
4800function onwriteStateUpdate(state) {
4801 state.writing = false;
4802 state.writecb = null;
4803 state.length -= state.writelen;
4804 state.writelen = 0;
4805}
4806
4807function 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
4832function 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.
4842function 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
4850function 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;
a0091a40
IC
4862 while (entry) {
4863 buffer[count] = entry;
a0091a40
IC
4864 entry = entry.next;
4865 count += 1;
4866 }
a0091a40
IC
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
4907Writable.prototype._write = function (chunk, encoding, cb) {
4908 cb(new Error('_write() is not implemented'));
4909};
4910
4911Writable.prototype._writev = null;
4912
4913Writable.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
4937function needFinish(state) {
4938 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
4939}
9f59e99b
IC
4940
4941function prefinish(stream, state) {
4942 if (!state.prefinished) {
a0091a40
IC
4943 state.prefinished = true;
4944 stream.emit('prefinish');
a0091a40
IC
4945 }
4946}
4947
4948function finishMaybe(stream, state) {
4949 var need = needFinish(state);
4950 if (need) {
a0091a40 4951 if (state.pendingcb === 0) {
9f59e99b 4952 prefinish(stream, state);
a0091a40
IC
4953 state.finished = true;
4954 stream.emit('finish');
9f59e99b
IC
4955 } else {
4956 prefinish(stream, state);
a0091a40
IC
4957 }
4958 }
4959 return need;
4960}
4961
4962function 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
9f59e99b
IC
4972// It seems a linked list but it is not
4973// there will be only 2 of these for each stream
4974function CorkedRequest(state) {
4975 var _this = this;
a0091a40 4976
9f59e99b
IC
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;
a0091a40 4987 }
9f59e99b
IC
4988 if (state.corkedRequestsFree) {
4989 state.corkedRequestsFree.next = _this;
4990 } else {
4991 state.corkedRequestsFree = _this;
a0091a40 4992 }
9f59e99b
IC
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){
a0091a40
IC
4997'use strict';
4998
9f59e99b 4999var Buffer = require('buffer').Buffer;
a0091a40 5000/*<replacement>*/
9f59e99b 5001var bufferShim = require('buffer-shims');
a0091a40
IC
5002/*</replacement>*/
5003
9f59e99b 5004module.exports = BufferList;
a0091a40 5005
9f59e99b
IC
5006function BufferList() {
5007 this.head = null;
5008 this.tail = null;
5009 this.length = 0;
5010}
a0091a40 5011
9f59e99b
IC
5012BufferList.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};
a0091a40 5018
9f59e99b
IC
5019BufferList.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};
a0091a40 5025
9f59e99b
IC
5026BufferList.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};
a0091a40 5033
9f59e99b
IC
5034BufferList.prototype.clear = function () {
5035 this.head = this.tail = null;
5036 this.length = 0;
5037};
a0091a40 5038
9f59e99b
IC
5039BufferList.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};
a0091a40 5047
9f59e99b
IC
5048BufferList.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;
a0091a40 5058 }
9f59e99b
IC
5059 return ret;
5060};
5061},{"buffer":5,"buffer-shims":4}],21:[function(require,module,exports){
5062module.exports = require('events').EventEmitter;
a0091a40 5063
9f59e99b
IC
5064},{"events":7}],22:[function(require,module,exports){
5065'use strict';
a0091a40 5066
9f59e99b 5067var Buffer = require('safe-buffer').Buffer;
a0091a40 5068
9f59e99b
IC
5069var 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;
a0091a40 5076 }
9f59e99b 5077};
a0091a40 5078
9f59e99b
IC
5079function _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;
a0091a40 5103 }
a0091a40 5104 }
9f59e99b 5105};
a0091a40 5106
9f59e99b
IC
5107// Do not cache `Buffer.isEncoding` when checking encoding names as some
5108// modules monkey-patch it to support additional encodings
5109function 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;
a0091a40
IC
5113}
5114
9f59e99b
IC
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.
5118exports.StringDecoder = StringDecoder;
5119function 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);
a0091a40
IC
5145}
5146
9f59e99b
IC
5147StringDecoder.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 || '';
a0091a40 5161};
a0091a40 5162
9f59e99b 5163StringDecoder.prototype.end = utf8End;
a0091a40 5164
9f59e99b
IC
5165// Returns only complete characters in a Buffer
5166StringDecoder.prototype.text = utf8Text;
a0091a40 5167
9f59e99b
IC
5168// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
5169StringDecoder.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};
a0091a40 5177
9f59e99b
IC
5178// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
5179// continuation byte.
5180function 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}
a0091a40 5184
9f59e99b
IC
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.
5188function 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;
a0091a40 5209 }
9f59e99b 5210 return 0;
a0091a40 5211}
9f59e99b
IC
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.
5221function 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 }
a0091a40
IC
5238}
5239
9f59e99b
IC
5240// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
5241function 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;
a0091a40
IC
5251}
5252
9f59e99b
IC
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.
5256function 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}
a0091a40 5264
9f59e99b
IC
5265// For UTF-8, a replacement character for each buffered byte of a (partial)
5266// character needs to be added to the output.
5267function 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;
a0091a40
IC
5271}
5272
9f59e99b
IC
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.
5277function 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 }
a0091a40 5289 }
9f59e99b 5290 return r;
a0091a40 5291 }
9f59e99b
IC
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);
a0091a40
IC
5296}
5297
9f59e99b
IC
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.
5300function 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);
a0091a40 5305 }
9f59e99b 5306 return r;
a0091a40
IC
5307}
5308
9f59e99b
IC
5309function 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];
a0091a40 5319 }
9f59e99b
IC
5320 return buf.toString('base64', i, buf.length - n);
5321}
5322
5323function 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)
5330function simpleWrite(buf) {
5331 return buf.toString(this.encoding);
5332}
5333
5334function simpleEnd(buf) {
5335 return buf && buf.length ? this.write(buf) : '';
a0091a40 5336}
9f59e99b
IC
5337},{"safe-buffer":27}],23:[function(require,module,exports){
5338module.exports = require('./readable').PassThrough
5339
5340},{"./readable":24}],24:[function(require,module,exports){
5341exports = module.exports = require('./lib/_stream_readable.js');
5342exports.Stream = exports;
5343exports.Readable = exports;
5344exports.Writable = require('./lib/_stream_writable.js');
5345exports.Duplex = require('./lib/_stream_duplex.js');
5346exports.Transform = require('./lib/_stream_transform.js');
5347exports.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){
5350module.exports = require('./readable').Transform
5351
5352},{"./readable":24}],26:[function(require,module,exports){
5353module.exports = require('./lib/_stream_writable.js');
5354
5355},{"./lib/_stream_writable.js":19}],27:[function(require,module,exports){
5356module.exports = require('buffer')
a0091a40 5357
9f59e99b 5358},{"buffer":5}],28:[function(require,module,exports){
a0091a40
IC
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
5380module.exports = Stream;
5381
5382var EE = require('events').EventEmitter;
5383var inherits = require('inherits');
5384
5385inherits(Stream, EE);
5386Stream.Readable = require('readable-stream/readable.js');
5387Stream.Writable = require('readable-stream/writable.js');
5388Stream.Duplex = require('readable-stream/duplex.js');
5389Stream.Transform = require('readable-stream/transform.js');
5390Stream.PassThrough = require('readable-stream/passthrough.js');
5391
5392// Backwards-compat with node 0.4.x
5393Stream.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
5400function Stream() {
5401 EE.call(this);
5402}
5403
5404Stream.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
9f59e99b
IC
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.
a0091a40 5508
9f59e99b 5509var Buffer = require('buffer').Buffer;
a0091a40 5510
9f59e99b
IC
5511var 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 }
a0091a40 5518
a0091a40 5519
9f59e99b
IC
5520function assertEncoding(encoding) {
5521 if (encoding && !isBufferEncoding(encoding)) {
5522 throw new Error('Unknown encoding: ' + encoding);
5523 }
a0091a40
IC
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
9f59e99b
IC
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.
5534var StringDecoder = exports.StringDecoder = function(encoding) {
5535 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
5536 assertEncoding(encoding);
a0091a40 5537 switch (this.encoding) {
a0091a40 5538 case 'utf8':
9f59e99b
IC
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;
a0091a40
IC
5547 break;
5548 case 'base64':
9f59e99b
IC
5549 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
5550 this.surrogateSize = 3;
5551 this.detectIncompleteChar = base64DetectIncompleteChar;
a0091a40
IC
5552 break;
5553 default:
9f59e99b 5554 this.write = passThroughWrite;
a0091a40
IC
5555 return;
5556 }
a0091a40 5557
9f59e99b
IC
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;
a0091a40
IC
5565};
5566
a0091a40 5567
9f59e99b
IC
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/ .
5577StringDecoder.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 }
a0091a40 5594
9f59e99b
IC
5595 // remove bytes belonging to the current character from the buffer
5596 buffer = buffer.slice(available, buffer.length);
a0091a40 5597
9f59e99b
IC
5598 // get the character that was split
5599 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
a0091a40 5600
9f59e99b
IC
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;
a0091a40 5607 }
9f59e99b 5608 this.charReceived = this.charLength = 0;
a0091a40 5609
9f59e99b
IC
5610 // if there are no more bytes in this buffer, just emit our char
5611 if (buffer.length === 0) {
5612 return charStr;
a0091a40 5613 }
9f59e99b 5614 break;
a0091a40 5615 }
a0091a40 5616
9f59e99b
IC
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;
a0091a40 5625 }
a0091a40 5626
9f59e99b 5627 charStr += buffer.toString(this.encoding, 0, end);
a0091a40 5628
9f59e99b
IC
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 }
a0091a40 5640
9f59e99b
IC
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.
5649StringDecoder.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;
a0091a40 5664 }
a0091a40 5665
9f59e99b
IC
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 }
a0091a40 5677 }
9f59e99b
IC
5678 this.charReceived = i;
5679};
a0091a40 5680
9f59e99b
IC
5681StringDecoder.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);
a0091a40 5691 }
a0091a40 5692
9f59e99b
IC
5693 return res;
5694};
5695
5696function passThroughWrite(buffer) {
5697 return buffer.toString(this.encoding);
a0091a40
IC
5698}
5699
9f59e99b
IC
5700function utf16DetectIncompleteChar(buffer) {
5701 this.charReceived = buffer.length % 2;
5702 this.charLength = this.charReceived ? 2 : 0;
a0091a40
IC
5703}
5704
9f59e99b
IC
5705function base64DetectIncompleteChar(buffer) {
5706 this.charReceived = buffer.length % 3;
5707 this.charLength = this.charReceived ? 3 : 0;
a0091a40 5708}
9f59e99b
IC
5709
5710},{"buffer":5}],30:[function(require,module,exports){
a0091a40
IC
5711(function (global){
5712
5713/**
5714 * Module exports.
5715 */
5716
5717module.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
5737function 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
5768function 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 : {})
9f59e99b
IC
5781},{}],31:[function(require,module,exports){
5782arguments[4][9][0].apply(exports,arguments)
5783},{"dup":9}],32:[function(require,module,exports){
a0091a40
IC
5784module.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}
9f59e99b 5790},{}],33:[function(require,module,exports){
a0091a40
IC
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
5813var formatRegExp = /%[sdj%]/g;
5814exports.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.
5856exports.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
5887var debugs = {};
5888var debugEnviron;
5889exports.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*/
5916function 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}
5940exports.inspect = inspect;
5941
5942
5943// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
5944inspect.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
5961inspect.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
5974function 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
5986function stylizeNoColor(str, styleType) {
5987 return str;
5988}
5989
5990
5991function arrayToHash(array) {
5992 var hash = {};
5993
5994 array.forEach(function(val, idx) {
5995 hash[val] = true;
5996 });
5997
5998 return hash;
5999}
6000
6001
6002function 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
6115function 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
6134function formatError(value) {
6135 return '[' + Error.prototype.toString.call(value) + ']';
6136}
6137
6138
6139function 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
6159function 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
6218function 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()`.
6241function isArray(ar) {
6242 return Array.isArray(ar);
6243}
6244exports.isArray = isArray;
6245
6246function isBoolean(arg) {
6247 return typeof arg === 'boolean';
6248}
6249exports.isBoolean = isBoolean;
6250
6251function isNull(arg) {
6252 return arg === null;
6253}
6254exports.isNull = isNull;
6255
6256function isNullOrUndefined(arg) {
6257 return arg == null;
6258}
6259exports.isNullOrUndefined = isNullOrUndefined;
6260
6261function isNumber(arg) {
6262 return typeof arg === 'number';
6263}
6264exports.isNumber = isNumber;
6265
6266function isString(arg) {
6267 return typeof arg === 'string';
6268}
6269exports.isString = isString;
6270
6271function isSymbol(arg) {
6272 return typeof arg === 'symbol';
6273}
6274exports.isSymbol = isSymbol;
6275
6276function isUndefined(arg) {
6277 return arg === void 0;
6278}
6279exports.isUndefined = isUndefined;
6280
6281function isRegExp(re) {
6282 return isObject(re) && objectToString(re) === '[object RegExp]';
6283}
6284exports.isRegExp = isRegExp;
6285
6286function isObject(arg) {
6287 return typeof arg === 'object' && arg !== null;
6288}
6289exports.isObject = isObject;
6290
6291function isDate(d) {
6292 return isObject(d) && objectToString(d) === '[object Date]';
6293}
6294exports.isDate = isDate;
6295
6296function isError(e) {
6297 return isObject(e) &&
6298 (objectToString(e) === '[object Error]' || e instanceof Error);
6299}
6300exports.isError = isError;
6301
6302function isFunction(arg) {
6303 return typeof arg === 'function';
6304}
6305exports.isFunction = isFunction;
6306
6307function 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}
6315exports.isPrimitive = isPrimitive;
6316
6317exports.isBuffer = require('./support/isBuffer');
6318
6319function objectToString(o) {
6320 return Object.prototype.toString.call(o);
6321}
6322
6323
6324function pad(n) {
6325 return n < 10 ? '0' + n.toString(10) : n.toString(10);
6326}
6327
6328
6329var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
6330 'Oct', 'Nov', 'Dec'];
6331
6332// 26 Feb 16:19:34
6333function 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
6343exports.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 */
6361exports.inherits = require('inherits');
6362
6363exports._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
6375function 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 : {})
9f59e99b 6380},{"./support/isBuffer":32,"_process":13,"inherits":31}],34:[function(require,module,exports){
b777ff55 6381let bitcoin = require('bitcoinjs-lib');
a0091a40 6382
b777ff55
IC
6383module.exports = {
6384 bitcoin
6385}
9f59e99b 6386
b777ff55 6387},{"bitcoinjs-lib":52}],35:[function(require,module,exports){
a0091a40
IC
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
6396var Buffer = require('safe-buffer').Buffer
6397
6398module.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
b777ff55 6431 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
a0091a40
IC
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) {
b777ff55 6439 if (typeof string !== 'string') throw new TypeError('Expected String')
a0091a40
IC
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
b777ff55 6481},{"safe-buffer":101}],36:[function(require,module,exports){
9f59e99b 6482'use strict'
b777ff55 6483var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
a0091a40 6484
9f59e99b 6485// pre-compute lookup table
b777ff55
IC
6486var ALPHABET_MAP = {}
6487for (var z = 0; z < ALPHABET.length; z++) {
6488 var x = ALPHABET.charAt(z)
9f59e99b
IC
6489
6490 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
6491 ALPHABET_MAP[x] = z
a0091a40
IC
6492}
6493
9f59e99b 6494function polymodStep (pre) {
b777ff55 6495 var b = pre >> 25
9f59e99b
IC
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}
a0091a40 6503
9f59e99b 6504function prefixChk (prefix) {
b777ff55
IC
6505 var chk = 1
6506 for (var i = 0; i < prefix.length; ++i) {
6507 var c = prefix.charCodeAt(i)
9f59e99b
IC
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
b777ff55
IC
6514 for (i = 0; i < prefix.length; ++i) {
6515 var v = prefix.charCodeAt(i)
9f59e99b
IC
6516 chk = polymodStep(chk) ^ (v & 0x1f)
6517 }
6518 return chk
a0091a40
IC
6519}
6520
b777ff55
IC
6521function encode (prefix, words, LIMIT) {
6522 LIMIT = LIMIT || 90
6523 if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit')
6524
9f59e99b 6525 prefix = prefix.toLowerCase()
a0091a40 6526
9f59e99b 6527 // determine chk mod
b777ff55
IC
6528 var chk = prefixChk(prefix)
6529 var result = prefix + '1'
6530 for (var i = 0; i < words.length; ++i) {
6531 var x = words[i]
9f59e99b 6532 if ((x >> 5) !== 0) throw new Error('Non 5-bit word')
a0091a40 6533
9f59e99b
IC
6534 chk = polymodStep(chk) ^ x
6535 result += ALPHABET.charAt(x)
a0091a40 6536 }
9f59e99b 6537
b777ff55 6538 for (i = 0; i < 6; ++i) {
9f59e99b
IC
6539 chk = polymodStep(chk)
6540 }
6541 chk ^= 1
6542
b777ff55
IC
6543 for (i = 0; i < 6; ++i) {
6544 var v = (chk >> ((5 - i) * 5)) & 0x1f
9f59e99b
IC
6545 result += ALPHABET.charAt(v)
6546 }
6547
6548 return result
a0091a40 6549}
9f59e99b 6550
b777ff55
IC
6551function decode (str, LIMIT) {
6552 LIMIT = LIMIT || 90
9f59e99b 6553 if (str.length < 8) throw new TypeError(str + ' too short')
b777ff55 6554 if (str.length > LIMIT) throw new TypeError('Exceeds length limit')
9f59e99b
IC
6555
6556 // don't allow mixed case
b777ff55
IC
6557 var lowered = str.toLowerCase()
6558 var uppered = str.toUpperCase()
9f59e99b
IC
6559 if (str !== lowered && str !== uppered) throw new Error('Mixed-case string ' + str)
6560 str = lowered
6561
b777ff55
IC
6562 var split = str.lastIndexOf('1')
6563 if (split === -1) throw new Error('No separator character for ' + str)
9f59e99b
IC
6564 if (split === 0) throw new Error('Missing prefix for ' + str)
6565
b777ff55
IC
6566 var prefix = str.slice(0, split)
6567 var wordChars = str.slice(split + 1)
9f59e99b
IC
6568 if (wordChars.length < 6) throw new Error('Data too short')
6569
b777ff55
IC
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]
9f59e99b
IC
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)
b777ff55 6584 return { prefix: prefix, words: words }
9f59e99b
IC
6585}
6586
6587function convert (data, inBits, outBits, pad) {
b777ff55
IC
6588 var value = 0
6589 var bits = 0
6590 var maxV = (1 << outBits) - 1
9f59e99b 6591
b777ff55
IC
6592 var result = []
6593 for (var i = 0; i < data.length; ++i) {
9f59e99b
IC
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
6615function toWords (bytes) {
6616 return convert(bytes, 8, 5, true)
6617}
6618
6619function fromWords (words) {
6620 return convert(words, 5, 8, false)
6621}
6622
b777ff55
IC
6623module.exports = {
6624 decode: decode,
6625 encode: encode,
6626 toWords: toWords,
6627 fromWords: fromWords
6628}
9f59e99b
IC
6629
6630},{}],37:[function(require,module,exports){
6631// (public) Constructor
6632function 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
6643var proto = BigInteger.prototype
6644
6645// duck-typed isBigInteger
6646proto.__bigi = require('../package.json').version
6647BigInteger.isBigInteger = function (obj, check_ver) {
6648 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
6649}
6650
6651// Bits per digit
6652var 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)
6662function 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)
6673function am2(i, x, w, j, c, n) {
6674 var xl = x & 0x7fff,
a0091a40
IC
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.
6688function 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?
6703BigInteger.prototype.am = am1
6704dbits = 26
6705
6706BigInteger.prototype.DB = dbits
6707BigInteger.prototype.DM = ((1 << dbits) - 1)
6708var DV = BigInteger.prototype.DV = (1 << dbits)
6709
6710var BI_FP = 52
6711BigInteger.prototype.FV = Math.pow(2, BI_FP)
6712BigInteger.prototype.F1 = BI_FP - dbits
6713BigInteger.prototype.F2 = 2 * dbits - BI_FP
6714
6715// Digit conversions
6716var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
6717var BI_RC = new Array()
6718var rr, vv
6719rr = "0".charCodeAt(0)
6720for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
6721rr = "a".charCodeAt(0)
6722for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6723rr = "A".charCodeAt(0)
6724for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
6725
6726function int2char(n) {
6727 return BI_RM.charAt(n)
6728}
6729
6730function 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
6736function 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
6743function 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
6752function nbv(i) {
6753 var r = new BigInteger()
6754 r.fromInt(i)
6755 return r
6756}
6757
6758// (protected) set from string and radix
6759function 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
6804function 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
6810function 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
6850function bnNegate() {
6851 var r = new BigInteger()
6852 BigInteger.ZERO.subTo(this, r)
6853 return r
6854}
6855
6856// (public) |this|
6857function bnAbs() {
6858 return (this.s < 0) ? this.negate() : this
6859}
6860
6861// (public) return + if this > a, - if this < a, 0 if equal
6862function 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
6874function 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"
6901function 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"
6907function bnByteLength() {
6908 return this.bitLength() >> 3
6909}
6910
6911// (protected) r = this << n*DB
6912function 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
6921function 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
6928function 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
6948function 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
6970function 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.
7006function 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)
7019function 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.
7037function 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
7097function 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
7106function Classic(m) {
7107 this.m = m
7108}
7109
7110function cConvert(x) {
7111 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
7112 else return x
7113}
7114
7115function cRevert(x) {
7116 return x
7117}
7118
7119function cReduce(x) {
7120 x.divRemTo(this.m, null, x)
7121}
7122
7123function cMulTo(x, y, r) {
7124 x.multiplyTo(y, r)
7125 this.reduce(r)
7126}
7127
7128function cSqrTo(x, r) {
7129 x.squareTo(r)
7130 this.reduce(r)
7131}
7132
7133Classic.prototype.convert = cConvert
7134Classic.prototype.revert = cRevert
7135Classic.prototype.reduce = cReduce
7136Classic.prototype.mulTo = cMulTo
7137Classic.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.
7149function 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
7165function 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
7175function 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
7185function 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)
7193function 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
7215function montSqrTo(x, r) {
7216 x.squareTo(r)
7217 this.reduce(r)
7218}
7219
7220// r = "xy/R mod m"; x,y != r
7221function montMulTo(x, y, r) {
7222 x.multiplyTo(y, r)
7223 this.reduce(r)
7224}
7225
7226Montgomery.prototype.convert = montConvert
7227Montgomery.prototype.revert = montRevert
7228Montgomery.prototype.reduce = montReduce
7229Montgomery.prototype.mulTo = montMulTo
7230Montgomery.prototype.sqrTo = montSqrTo
7231
7232// (protected) true iff this is even
7233function 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)
7238function 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
7258function 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
7266proto.copyTo = bnpCopyTo
7267proto.fromInt = bnpFromInt
7268proto.fromString = bnpFromString
7269proto.clamp = bnpClamp
7270proto.dlShiftTo = bnpDLShiftTo
7271proto.drShiftTo = bnpDRShiftTo
7272proto.lShiftTo = bnpLShiftTo
7273proto.rShiftTo = bnpRShiftTo
7274proto.subTo = bnpSubTo
7275proto.multiplyTo = bnpMultiplyTo
7276proto.squareTo = bnpSquareTo
7277proto.divRemTo = bnpDivRemTo
7278proto.invDigit = bnpInvDigit
7279proto.isEven = bnpIsEven
7280proto.exp = bnpExp
7281
7282// public
7283proto.toString = bnToString
7284proto.negate = bnNegate
7285proto.abs = bnAbs
7286proto.compareTo = bnCompareTo
7287proto.bitLength = bnBitLength
7288proto.byteLength = bnByteLength
7289proto.mod = bnMod
7290proto.modPowInt = bnModPowInt
7291
7292// (public)
7293function bnClone() {
7294 var r = new BigInteger()
7295 this.copyTo(r)
7296 return r
7297}
7298
7299// (public) return value as integer
7300function 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
7311function bnByteValue() {
7312 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
7313}
7314
7315// (public) return value as short (assumes DB>=16)
7316function bnShortValue() {
7317 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
7318}
7319
7320// (protected) return x s.t. r^x < DV
7321function 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
7326function 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
7333function 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
7354function 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
7385function 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
7413function 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
7442function bnEquals(a) {
7443 return (this.compareTo(a) == 0)
7444}
7445
7446function bnMin(a) {
7447 return (this.compareTo(a) < 0) ? this : a
7448}
7449
7450function bnMax(a) {
7451 return (this.compareTo(a) > 0) ? this : a
7452}
7453
7454// (protected) r = this op a (bitwise)
7455function 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
7473function op_and(x, y) {
7474 return x & y
7475}
7476
7477function bnAnd(a) {
7478 var r = new BigInteger()
7479 this.bitwiseTo(a, op_and, r)
7480 return r
7481}
7482
7483// (public) this | a
7484function op_or(x, y) {
7485 return x | y
7486}
7487
7488function bnOr(a) {
7489 var r = new BigInteger()
7490 this.bitwiseTo(a, op_or, r)
7491 return r
7492}
7493
7494// (public) this ^ a
7495function op_xor(x, y) {
7496 return x ^ y
7497}
7498
7499function bnXor(a) {
7500 var r = new BigInteger()
7501 this.bitwiseTo(a, op_xor, r)
7502 return r
7503}
7504
7505// (public) this & ~a
7506function op_andnot(x, y) {
7507 return x & ~y
7508}
7509
7510function bnAndNot(a) {
7511 var r = new BigInteger()
7512 this.bitwiseTo(a, op_andnot, r)
7513 return r
7514}
7515
7516// (public) ~this
7517function 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
7526function 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
7534function 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
7542function 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)
7566function 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
7574function 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
7584function 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
7592function 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)
7599function 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)
7606function bnSetBit(n) {
7607 return this.changeBit(n, op_or)
7608}
7609
7610// (public) this & ~(1<<n)
7611function bnClearBit(n) {
7612 return this.changeBit(n, op_andnot)
7613}
7614
7615// (public) this ^ (1<<n)
7616function bnFlipBit(n) {
7617 return this.changeBit(n, op_xor)
7618}
7619
7620// (protected) r = this + a
7621function 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
7657function bnAdd(a) {
7658 var r = new BigInteger()
7659 this.addTo(a, r)
7660 return r
7661}
7662
7663// (public) this - a
7664function bnSubtract(a) {
7665 var r = new BigInteger()
7666 this.subTo(a, r)
7667 return r
7668}
7669
7670// (public) this * a
7671function bnMultiply(a) {
7672 var r = new BigInteger()
7673 this.multiplyTo(a, r)
7674 return r
7675}
7676
7677// (public) this^2
7678function bnSquare() {
7679 var r = new BigInteger()
7680 this.squareTo(r)
7681 return r
7682}
7683
7684// (public) this / a
7685function bnDivide(a) {
7686 var r = new BigInteger()
7687 this.divRemTo(a, r, null)
7688 return r
7689}
7690
7691// (public) this % a
7692function bnRemainder(a) {
7693 var r = new BigInteger()
7694 this.divRemTo(a, null, r)
7695 return r
7696}
7697
7698// (public) [this/a,this%a]
7699function 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
7707function 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
7714function 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
7726function NullExp() {}
7727
7728function nNop(x) {
7729 return x
7730}
7731
7732function nMulTo(x, y, r) {
7733 x.multiplyTo(y, r)
7734}
7735
7736function nSqrTo(x, r) {
7737 x.squareTo(r)
7738}
7739
7740NullExp.prototype.convert = nNop
7741NullExp.prototype.revert = nNop
7742NullExp.prototype.mulTo = nMulTo
7743NullExp.prototype.sqrTo = nSqrTo
7744
7745// (public) this^e
7746function 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.
7752function 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.
7765function 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
7777function 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
7786function 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
7797function barrettRevert(x) {
7798 return x
7799}
7800
7801// x = x mod m (HAC 14.42)
7802function 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
7817function barrettSqrTo(x, r) {
7818 x.squareTo(r)
7819 this.reduce(r)
7820}
7821
7822// r = x*y mod m; x,y != r
7823function barrettMulTo(x, y, r) {
7824 x.multiplyTo(y, r)
7825 this.reduce(r)
7826}
7827
7828Barrett.prototype.convert = barrettConvert
7829Barrett.prototype.revert = barrettRevert
7830Barrett.prototype.reduce = barrettReduce
7831Barrett.prototype.mulTo = barrettMulTo
7832Barrett.prototype.sqrTo = barrettSqrTo
7833
7834// (public) this^e % m (HAC 14.85)
7835function 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)
7922function 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
7954function 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)
7966function 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
8015var 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
8029var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
8030
8031// (public) test primality with certainty >= 1-.5^t
8032function 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)
8052function 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
8082proto.chunkSize = bnpChunkSize
8083proto.toRadix = bnpToRadix
8084proto.fromRadix = bnpFromRadix
8085proto.fromNumber = bnpFromNumber
8086proto.bitwiseTo = bnpBitwiseTo
8087proto.changeBit = bnpChangeBit
8088proto.addTo = bnpAddTo
8089proto.dMultiply = bnpDMultiply
8090proto.dAddOffset = bnpDAddOffset
8091proto.multiplyLowerTo = bnpMultiplyLowerTo
8092proto.multiplyUpperTo = bnpMultiplyUpperTo
8093proto.modInt = bnpModInt
8094proto.millerRabin = bnpMillerRabin
8095
8096// public
8097proto.clone = bnClone
8098proto.intValue = bnIntValue
8099proto.byteValue = bnByteValue
8100proto.shortValue = bnShortValue
8101proto.signum = bnSigNum
8102proto.toByteArray = bnToByteArray
8103proto.equals = bnEquals
8104proto.min = bnMin
8105proto.max = bnMax
8106proto.and = bnAnd
8107proto.or = bnOr
8108proto.xor = bnXor
8109proto.andNot = bnAndNot
8110proto.not = bnNot
8111proto.shiftLeft = bnShiftLeft
8112proto.shiftRight = bnShiftRight
8113proto.getLowestSetBit = bnGetLowestSetBit
8114proto.bitCount = bnBitCount
8115proto.testBit = bnTestBit
8116proto.setBit = bnSetBit
8117proto.clearBit = bnClearBit
8118proto.flipBit = bnFlipBit
8119proto.add = bnAdd
8120proto.subtract = bnSubtract
8121proto.multiply = bnMultiply
8122proto.divide = bnDivide
8123proto.remainder = bnRemainder
8124proto.divideAndRemainder = bnDivideAndRemainder
8125proto.modPow = bnModPow
8126proto.modInverse = bnModInverse
8127proto.pow = bnPow
8128proto.gcd = bnGCD
8129proto.isProbablePrime = bnIsProbablePrime
8130
8131// JSBN-specific extension
8132proto.square = bnSquare
8133
8134// constants
8135BigInteger.ZERO = nbv(0)
8136BigInteger.ONE = nbv(1)
8137BigInteger.valueOf = nbv
8138
8139module.exports = BigInteger
8140
9f59e99b 8141},{"../package.json":40}],38:[function(require,module,exports){
a0091a40
IC
8142(function (Buffer){
8143// FIXME: Kind of a weird way to throw exceptions, consider removing
8144var assert = require('assert')
8145var 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 */
8153BigInteger.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 */
8168BigInteger.prototype.toByteArrayUnsigned = function() {
8169 var byteArray = this.toByteArray()
8170 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
8171}
8172
8173BigInteger.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*/
8200BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
8201
8202BigInteger.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
8213BigInteger.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
8221BigInteger.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
8231BigInteger.prototype.toHex = function(size) {
8232 return this.toBuffer(size).toString('hex')
8233}
8234
8235}).call(this,require("buffer").Buffer)
9f59e99b 8236},{"./bigi":37,"assert":1,"buffer":5}],39:[function(require,module,exports){
a0091a40
IC
8237var BigInteger = require('./bigi')
8238
8239//addons
8240require('./convert')
8241
8242module.exports = BigInteger
9f59e99b 8243},{"./bigi":37,"./convert":38}],40:[function(require,module,exports){
a0091a40
IC
8244module.exports={
8245 "_args": [
8246 [
b777ff55
IC
8247 "bigi@^1.4.0",
8248 "/home/ian/git/bitcoin/bitcoinjs-lib-browser/node_modules/bitcoinjs-lib"
a0091a40
IC
8249 ]
8250 ],
b777ff55 8251 "_from": "bigi@>=1.4.0 <2.0.0",
a0091a40
IC
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",
b777ff55
IC
8269 "raw": "bigi@^1.4.0",
8270 "rawSpec": "^1.4.0",
a0091a40 8271 "scope": null,
b777ff55
IC
8272 "spec": ">=1.4.0 <2.0.0",
8273 "type": "range"
a0091a40
IC
8274 },
8275 "_requiredBy": [
a0091a40
IC
8276 "/bitcoinjs-lib",
8277 "/ecurve"
8278 ],
8279 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
8280 "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
8281 "_shrinkwrap": null,
b777ff55
IC
8282 "_spec": "bigi@^1.4.0",
8283 "_where": "/home/ian/git/bitcoin/bitcoinjs-lib-browser/node_modules/bitcoinjs-lib",
a0091a40
IC
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
9f59e99b 8369},{}],41:[function(require,module,exports){
a0091a40
IC
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
8374var Buffer = require('safe-buffer').Buffer
8375
8376function 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
8400function 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*/
8451function 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
8478module.exports = {
8479 check: check,
8480 decode: decode,
8481 encode: encode
8482}
8483
b777ff55 8484},{"safe-buffer":101}],42:[function(require,module,exports){
a0091a40
IC
8485module.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,
a0091a40 8493 "OP_TRUE": 81,
b777ff55 8494 "OP_1": 81,
a0091a40
IC
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,
b777ff55 8599
a0091a40
IC
8600 "OP_NOP2": 177,
8601 "OP_CHECKLOCKTIMEVERIFY": 177,
8602
8603 "OP_NOP3": 178,
b777ff55
IC
8604 "OP_CHECKSEQUENCEVERIFY": 178,
8605
a0091a40
IC
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
9f59e99b 8619},{}],43:[function(require,module,exports){
a0091a40
IC
8620var OPS = require('./index.json')
8621
8622var map = {}
8623for (var op in OPS) {
8624 var code = OPS[op]
8625 map[code] = op
8626}
8627
8628module.exports = map
8629
9f59e99b 8630},{"./index.json":42}],44:[function(require,module,exports){
a0091a40 8631var Buffer = require('safe-buffer').Buffer
9f59e99b 8632var bech32 = require('bech32')
a0091a40
IC
8633var bs58check = require('bs58check')
8634var bscript = require('./script')
9f59e99b 8635var btemplates = require('./templates')
a0091a40
IC
8636var networks = require('./networks')
8637var typeforce = require('typeforce')
8638var types = require('./types')
8639
8640function fromBase58Check (address) {
8641 var payload = bs58check.decode(address)
9f59e99b
IC
8642
8643 // TODO: 4.0.0, move to "toOutputScript"
a0091a40
IC
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
9f59e99b
IC
8650 return { version: version, hash: hash }
8651}
8652
8653function 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 }
a0091a40
IC
8662}
8663
8664function toBase58Check (hash, version) {
8665 typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments)
8666
8667 var payload = Buffer.allocUnsafe(21)
8668 payload.writeUInt8(version, 0)
8669 hash.copy(payload, 1)
8670
8671 return bs58check.encode(payload)
8672}
8673
9f59e99b
IC
8674function toBech32 (data, version, prefix) {
8675 var words = bech32.toWords(data)
8676 words.unshift(version)
8677
8678 return bech32.encode(prefix, words)
8679}
8680
a0091a40
IC
8681function fromOutputScript (outputScript, network) {
8682 network = network || networks.bitcoin
8683
9f59e99b
IC
8684 if (btemplates.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash)
8685 if (btemplates.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash)
8686 if (btemplates.witnessPubKeyHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 22), 0, network.bech32)
8687 if (btemplates.witnessScriptHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 34), 0, network.bech32)
a0091a40
IC
8688
8689 throw new Error(bscript.toASM(outputScript) + ' has no matching Address')
8690}
8691
8692function toOutputScript (address, network) {
8693 network = network || networks.bitcoin
8694
9f59e99b
IC
8695 var decode
8696 try {
8697 decode = fromBase58Check(address)
8698 } catch (e) {}
8699
8700 if (decode) {
8701 if (decode.version === network.pubKeyHash) return btemplates.pubKeyHash.output.encode(decode.hash)
8702 if (decode.version === network.scriptHash) return btemplates.scriptHash.output.encode(decode.hash)
8703 } else {
8704 try {
8705 decode = fromBech32(address)
8706 } catch (e) {}
8707
8708 if (decode) {
8709 if (decode.prefix !== network.bech32) throw new Error(address + ' has an invalid prefix')
8710 if (decode.version === 0) {
8711 if (decode.data.length === 20) return btemplates.witnessPubKeyHash.output.encode(decode.data)
8712 if (decode.data.length === 32) return btemplates.witnessScriptHash.output.encode(decode.data)
8713 }
8714 }
8715 }
a0091a40
IC
8716
8717 throw new Error(address + ' has no matching Script')
8718}
8719
8720module.exports = {
8721 fromBase58Check: fromBase58Check,
9f59e99b 8722 fromBech32: fromBech32,
a0091a40
IC
8723 fromOutputScript: fromOutputScript,
8724 toBase58Check: toBase58Check,
9f59e99b 8725 toBech32: toBech32,
a0091a40
IC
8726 toOutputScript: toOutputScript
8727}
8728
b777ff55 8729},{"./networks":53,"./script":54,"./templates":56,"./types":80,"bech32":36,"bs58check":83,"safe-buffer":101,"typeforce":112}],45:[function(require,module,exports){
a0091a40
IC
8730var Buffer = require('safe-buffer').Buffer
8731var bcrypto = require('./crypto')
8732var fastMerkleRoot = require('merkle-lib/fastRoot')
8733var typeforce = require('typeforce')
8734var types = require('./types')
8735var varuint = require('varuint-bitcoin')
8736
8737var Transaction = require('./transaction')
8738
8739function Block () {
8740 this.version = 1
8741 this.prevHash = null
8742 this.merkleRoot = null
8743 this.timestamp = 0
8744 this.bits = 0
8745 this.nonce = 0
8746}
8747
8748Block.fromBuffer = function (buffer) {
8749 if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)')
8750
8751 var offset = 0
8752 function readSlice (n) {
8753 offset += n
8754 return buffer.slice(offset - n, offset)
8755 }
8756
8757 function readUInt32 () {
8758 var i = buffer.readUInt32LE(offset)
8759 offset += 4
8760 return i
8761 }
8762
8763 function readInt32 () {
8764 var i = buffer.readInt32LE(offset)
8765 offset += 4
8766 return i
8767 }
8768
8769 var block = new Block()
8770 block.version = readInt32()
8771 block.prevHash = readSlice(32)
8772 block.merkleRoot = readSlice(32)
8773 block.timestamp = readUInt32()
8774 block.bits = readUInt32()
8775 block.nonce = readUInt32()
8776
8777 if (buffer.length === 80) return block
8778
8779 function readVarInt () {
8780 var vi = varuint.decode(buffer, offset)
8781 offset += varuint.decode.bytes
8782 return vi
8783 }
8784
8785 function readTransaction () {
8786 var tx = Transaction.fromBuffer(buffer.slice(offset), true)
8787 offset += tx.byteLength()
8788 return tx
8789 }
8790
8791 var nTransactions = readVarInt()
8792 block.transactions = []
8793
8794 for (var i = 0; i < nTransactions; ++i) {
8795 var tx = readTransaction()
8796 block.transactions.push(tx)
8797 }
8798
8799 return block
8800}
8801
8802Block.prototype.byteLength = function (headersOnly) {
8803 if (headersOnly || !this.transactions) return 80
8804
8805 return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) {
8806 return a + x.byteLength()
8807 }, 0)
8808}
8809
8810Block.fromHex = function (hex) {
8811 return Block.fromBuffer(Buffer.from(hex, 'hex'))
8812}
8813
8814Block.prototype.getHash = function () {
8815 return bcrypto.hash256(this.toBuffer(true))
8816}
8817
8818Block.prototype.getId = function () {
8819 return this.getHash().reverse().toString('hex')
8820}
8821
8822Block.prototype.getUTCDate = function () {
8823 var date = new Date(0) // epoch
8824 date.setUTCSeconds(this.timestamp)
8825
8826 return date
8827}
8828
8829// TODO: buffer, offset compatibility
8830Block.prototype.toBuffer = function (headersOnly) {
8831 var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly))
8832
8833 var offset = 0
8834 function writeSlice (slice) {
8835 slice.copy(buffer, offset)
8836 offset += slice.length
8837 }
8838
8839 function writeInt32 (i) {
8840 buffer.writeInt32LE(i, offset)
8841 offset += 4
8842 }
8843 function writeUInt32 (i) {
8844 buffer.writeUInt32LE(i, offset)
8845 offset += 4
8846 }
8847
8848 writeInt32(this.version)
8849 writeSlice(this.prevHash)
8850 writeSlice(this.merkleRoot)
8851 writeUInt32(this.timestamp)
8852 writeUInt32(this.bits)
8853 writeUInt32(this.nonce)
8854
8855 if (headersOnly || !this.transactions) return buffer
8856
8857 varuint.encode(this.transactions.length, buffer, offset)
8858 offset += varuint.encode.bytes
8859
8860 this.transactions.forEach(function (tx) {
8861 var txSize = tx.byteLength() // TODO: extract from toBuffer?
8862 tx.toBuffer(buffer, offset)
8863 offset += txSize
8864 })
8865
8866 return buffer
8867}
8868
8869Block.prototype.toHex = function (headersOnly) {
8870 return this.toBuffer(headersOnly).toString('hex')
8871}
8872
8873Block.calculateTarget = function (bits) {
8874 var exponent = ((bits & 0xff000000) >> 24) - 3
8875 var mantissa = bits & 0x007fffff
8876 var target = Buffer.alloc(32, 0)
8877 target.writeUInt32BE(mantissa, 28 - exponent)
8878 return target
8879}
8880
8881Block.calculateMerkleRoot = function (transactions) {
8882 typeforce([{ getHash: types.Function }], transactions)
8883 if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions')
8884
8885 var hashes = transactions.map(function (transaction) {
8886 return transaction.getHash()
8887 })
8888
8889 return fastMerkleRoot(hashes, bcrypto.hash256)
8890}
8891
8892Block.prototype.checkMerkleRoot = function () {
8893 if (!this.transactions) return false
8894
8895 var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions)
8896 return this.merkleRoot.compare(actualMerkleRoot) === 0
8897}
8898
8899Block.prototype.checkProofOfWork = function () {
8900 var hash = this.getHash().reverse()
8901 var target = Block.calculateTarget(this.bits)
8902
8903 return hash.compare(target) <= 0
8904}
8905
8906module.exports = Block
8907
b777ff55 8908},{"./crypto":47,"./transaction":78,"./types":80,"merkle-lib/fastRoot":97,"safe-buffer":101,"typeforce":112,"varuint-bitcoin":114}],46:[function(require,module,exports){
a0091a40
IC
8909var pushdata = require('pushdata-bitcoin')
8910var varuint = require('varuint-bitcoin')
8911
8912// https://github.com/feross/buffer/blob/master/index.js#L1127
8913function verifuint (value, max) {
8914 if (typeof value !== 'number') throw new Error('cannot write a non-number as a number')
8915 if (value < 0) throw new Error('specified a negative value for writing an unsigned value')
8916 if (value > max) throw new Error('RangeError: value out of range')
8917 if (Math.floor(value) !== value) throw new Error('value has a fractional component')
8918}
8919
8920function readUInt64LE (buffer, offset) {
8921 var a = buffer.readUInt32LE(offset)
8922 var b = buffer.readUInt32LE(offset + 4)
8923 b *= 0x100000000
8924
8925 verifuint(b + a, 0x001fffffffffffff)
8926
8927 return b + a
8928}
8929
8930function writeUInt64LE (buffer, value, offset) {
8931 verifuint(value, 0x001fffffffffffff)
8932
8933 buffer.writeInt32LE(value & -1, offset)
8934 buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4)
8935 return offset + 8
8936}
8937
8938// TODO: remove in 4.0.0?
8939function readVarInt (buffer, offset) {
8940 var result = varuint.decode(buffer, offset)
8941
8942 return {
8943 number: result,
8944 size: varuint.decode.bytes
8945 }
8946}
8947
8948// TODO: remove in 4.0.0?
8949function writeVarInt (buffer, number, offset) {
8950 varuint.encode(number, buffer, offset)
8951 return varuint.encode.bytes
8952}
8953
8954module.exports = {
8955 pushDataSize: pushdata.encodingLength,
8956 readPushDataInt: pushdata.decode,
8957 readUInt64LE: readUInt64LE,
8958 readVarInt: readVarInt,
8959 varIntBuffer: varuint.encode,
8960 varIntSize: varuint.encodingLength,
8961 writePushDataInt: pushdata.encode,
8962 writeUInt64LE: writeUInt64LE,
8963 writeVarInt: writeVarInt
8964}
8965
b777ff55 8966},{"pushdata-bitcoin":98,"varuint-bitcoin":114}],47:[function(require,module,exports){
a0091a40
IC
8967var createHash = require('create-hash')
8968
8969function ripemd160 (buffer) {
8970 return createHash('rmd160').update(buffer).digest()
8971}
8972
8973function sha1 (buffer) {
8974 return createHash('sha1').update(buffer).digest()
8975}
8976
8977function sha256 (buffer) {
8978 return createHash('sha256').update(buffer).digest()
8979}
8980
8981function hash160 (buffer) {
8982 return ripemd160(sha256(buffer))
8983}
8984
8985function hash256 (buffer) {
8986 return sha256(sha256(buffer))
8987}
8988
8989module.exports = {
8990 hash160: hash160,
8991 hash256: hash256,
8992 ripemd160: ripemd160,
8993 sha1: sha1,
8994 sha256: sha256
8995}
8996
b777ff55 8997},{"create-hash":85}],48:[function(require,module,exports){
a0091a40
IC
8998var Buffer = require('safe-buffer').Buffer
8999var createHmac = require('create-hmac')
9000var typeforce = require('typeforce')
9001var types = require('./types')
9002
9003var BigInteger = require('bigi')
9004var ECSignature = require('./ecsignature')
9005
9006var ZERO = Buffer.alloc(1, 0)
9007var ONE = Buffer.alloc(1, 1)
9008
9009var ecurve = require('ecurve')
9010var secp256k1 = ecurve.getCurveByName('secp256k1')
9011
9012// https://tools.ietf.org/html/rfc6979#section-3.2
9013function deterministicGenerateK (hash, x, checkSig) {
9014 typeforce(types.tuple(
9015 types.Hash256bit,
9016 types.Buffer256bit,
9017 types.Function
9018 ), arguments)
9019
9020 // Step A, ignored as hash already provided
9021 // Step B
9022 // Step C
9023 var k = Buffer.alloc(32, 0)
9024 var v = Buffer.alloc(32, 1)
9025
9026 // Step D
9027 k = createHmac('sha256', k)
9028 .update(v)
9029 .update(ZERO)
9030 .update(x)
9031 .update(hash)
9032 .digest()
9033
9034 // Step E
9035 v = createHmac('sha256', k).update(v).digest()
9036
9037 // Step F
9038 k = createHmac('sha256', k)
9039 .update(v)
9040 .update(ONE)
9041 .update(x)
9042 .update(hash)
9043 .digest()
9044
9045 // Step G
9046 v = createHmac('sha256', k).update(v).digest()
9047
9048 // Step H1/H2a, ignored as tlen === qlen (256 bit)
9049 // Step H2b
9050 v = createHmac('sha256', k).update(v).digest()
9051
9052 var T = BigInteger.fromBuffer(v)
9053
9054 // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA
9055 while (T.signum() <= 0 || T.compareTo(secp256k1.n) >= 0 || !checkSig(T)) {
9056 k = createHmac('sha256', k)
9057 .update(v)
9058 .update(ZERO)
9059 .digest()
9060
9061 v = createHmac('sha256', k).update(v).digest()
9062
9063 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
9064 // Step H2b again
9065 v = createHmac('sha256', k).update(v).digest()
9066 T = BigInteger.fromBuffer(v)
9067 }
9068
9069 return T
9070}
9071
9072var N_OVER_TWO = secp256k1.n.shiftRight(1)
9073
9074function sign (hash, d) {
9075 typeforce(types.tuple(types.Hash256bit, types.BigInt), arguments)
9076
9077 var x = d.toBuffer(32)
9078 var e = BigInteger.fromBuffer(hash)
9079 var n = secp256k1.n
9080 var G = secp256k1.G
9081
9082 var r, s
9083 deterministicGenerateK(hash, x, function (k) {
9084 var Q = G.multiply(k)
9085
9086 if (secp256k1.isInfinity(Q)) return false
9087
9088 r = Q.affineX.mod(n)
9089 if (r.signum() === 0) return false
9090
9091 s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n)
9092 if (s.signum() === 0) return false
9093
9094 return true
9095 })
9096
9097 // enforce low S values, see bip62: 'low s values in signatures'
9098 if (s.compareTo(N_OVER_TWO) > 0) {
9099 s = n.subtract(s)
9100 }
9101
9102 return new ECSignature(r, s)
9103}
9104
9105function verify (hash, signature, Q) {
9106 typeforce(types.tuple(
9107 types.Hash256bit,
9108 types.ECSignature,
9109 types.ECPoint
9110 ), arguments)
9111
9112 var n = secp256k1.n
9113 var G = secp256k1.G
9114
9115 var r = signature.r
9116 var s = signature.s
9117
9118 // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
9119 if (r.signum() <= 0 || r.compareTo(n) >= 0) return false
9120 if (s.signum() <= 0 || s.compareTo(n) >= 0) return false
9121
9122 // 1.4.2 H = Hash(M), already done by the user
9123 // 1.4.3 e = H
9124 var e = BigInteger.fromBuffer(hash)
9125
9126 // Compute s^-1
9127 var sInv = s.modInverse(n)
9128
9129 // 1.4.4 Compute u1 = es^−1 mod n
9130 // u2 = rs^−1 mod n
9131 var u1 = e.multiply(sInv).mod(n)
9132 var u2 = r.multiply(sInv).mod(n)
9133
9134 // 1.4.5 Compute R = (xR, yR)
9135 // R = u1G + u2Q
9136 var R = G.multiplyTwo(u1, Q, u2)
9137
9138 // 1.4.5 (cont.) Enforce R is not at infinity
9139 if (secp256k1.isInfinity(R)) return false
9140
9141 // 1.4.6 Convert the field element R.x to an integer
9142 var xR = R.affineX
9143
9144 // 1.4.7 Set v = xR mod n
9145 var v = xR.mod(n)
9146
9147 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
9148 return v.equals(r)
9149}
9150
9151module.exports = {
9152 deterministicGenerateK: deterministicGenerateK,
9153 sign: sign,
9154 verify: verify,
9155
9156 // TODO: remove
9157 __curve: secp256k1
9158}
9159
b777ff55 9160},{"./ecsignature":50,"./types":80,"bigi":39,"create-hmac":88,"ecurve":92,"safe-buffer":101,"typeforce":112}],49:[function(require,module,exports){
a0091a40
IC
9161var baddress = require('./address')
9162var bcrypto = require('./crypto')
9163var ecdsa = require('./ecdsa')
9164var randomBytes = require('randombytes')
9165var typeforce = require('typeforce')
9166var types = require('./types')
9167var wif = require('wif')
9168
9169var NETWORKS = require('./networks')
9170var BigInteger = require('bigi')
9171
9172var ecurve = require('ecurve')
9173var secp256k1 = ecdsa.__curve
9174
9175function ECPair (d, Q, options) {
9176 if (options) {
9177 typeforce({
9178 compressed: types.maybe(types.Boolean),
9179 network: types.maybe(types.Network)
9180 }, options)
9181 }
9182
9183 options = options || {}
9184
9185 if (d) {
9186 if (d.signum() <= 0) throw new Error('Private key must be greater than 0')
9187 if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order')
9188 if (Q) throw new TypeError('Unexpected publicKey parameter')
9189
9190 this.d = d
9191 } else {
9192 typeforce(types.ECPoint, Q)
9193
9194 this.__Q = Q
9195 }
9196
9197 this.compressed = options.compressed === undefined ? true : options.compressed
9198 this.network = options.network || NETWORKS.bitcoin
9199}
9200
9201Object.defineProperty(ECPair.prototype, 'Q', {
9202 get: function () {
9203 if (!this.__Q && this.d) {
9204 this.__Q = secp256k1.G.multiply(this.d)
9205 }
9206
9207 return this.__Q
9208 }
9209})
9210
9211ECPair.fromPublicKeyBuffer = function (buffer, network) {
9212 var Q = ecurve.Point.decodeFrom(secp256k1, buffer)
9213
9214 return new ECPair(null, Q, {
9215 compressed: Q.compressed,
9216 network: network
9217 })
9218}
9219
9220ECPair.fromWIF = function (string, network) {
9221 var decoded = wif.decode(string)
9222 var version = decoded.version
9223
9224 // list of networks?
9225 if (types.Array(network)) {
9226 network = network.filter(function (x) {
9227 return version === x.wif
9228 }).pop()
9229
9230 if (!network) throw new Error('Unknown network version')
9231
9232 // otherwise, assume a network object (or default to bitcoin)
9233 } else {
9234 network = network || NETWORKS.bitcoin
9235
9236 if (version !== network.wif) throw new Error('Invalid network version')
9237 }
9238
9239 var d = BigInteger.fromBuffer(decoded.privateKey)
9240
9241 return new ECPair(d, null, {
9242 compressed: decoded.compressed,
9243 network: network
9244 })
9245}
9246
9247ECPair.makeRandom = function (options) {
9248 options = options || {}
9249
9250 var rng = options.rng || randomBytes
9251
9252 var d
9253 do {
9254 var buffer = rng(32)
9255 typeforce(types.Buffer256bit, buffer)
9256
9257 d = BigInteger.fromBuffer(buffer)
9258 } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0)
9259
9260 return new ECPair(d, null, options)
9261}
9262
9263ECPair.prototype.getAddress = function () {
9264 return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash)
9265}
9266
9267ECPair.prototype.getNetwork = function () {
9268 return this.network
9269}
9270
9271ECPair.prototype.getPublicKeyBuffer = function () {
9272 return this.Q.getEncoded(this.compressed)
9273}
9274
9275ECPair.prototype.sign = function (hash) {
9276 if (!this.d) throw new Error('Missing private key')
9277
9278 return ecdsa.sign(hash, this.d)
9279}
9280
9281ECPair.prototype.toWIF = function () {
9282 if (!this.d) throw new Error('Missing private key')
9283
9284 return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed)
9285}
9286
9287ECPair.prototype.verify = function (hash, signature) {
9288 return ecdsa.verify(hash, signature, this.Q)
9289}
9290
9291module.exports = ECPair
9292
b777ff55 9293},{"./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){
a0091a40
IC
9294(function (Buffer){
9295var bip66 = require('bip66')
9296var typeforce = require('typeforce')
9297var types = require('./types')
9298
9299var BigInteger = require('bigi')
9300
9301function ECSignature (r, s) {
9302 typeforce(types.tuple(types.BigInt, types.BigInt), arguments)
9303
9304 this.r = r
9305 this.s = s
9306}
9307
9308ECSignature.parseCompact = function (buffer) {
9f59e99b 9309 typeforce(types.BufferN(65), buffer)
a0091a40
IC
9310
9311 var flagByte = buffer.readUInt8(0) - 27
9312 if (flagByte !== (flagByte & 7)) throw new Error('Invalid signature parameter')
9313
9314 var compressed = !!(flagByte & 4)
9315 var recoveryParam = flagByte & 3
9f59e99b 9316 var signature = ECSignature.fromRSBuffer(buffer.slice(1))
a0091a40
IC
9317
9318 return {
9319 compressed: compressed,
9320 i: recoveryParam,
9f59e99b 9321 signature: signature
a0091a40
IC
9322 }
9323}
9324
9f59e99b
IC
9325ECSignature.fromRSBuffer = function (buffer) {
9326 typeforce(types.BufferN(64), buffer)
9327
9328 var r = BigInteger.fromBuffer(buffer.slice(0, 32))
9329 var s = BigInteger.fromBuffer(buffer.slice(32, 64))
9330 return new ECSignature(r, s)
9331}
9332
a0091a40
IC
9333ECSignature.fromDER = function (buffer) {
9334 var decode = bip66.decode(buffer)
9335 var r = BigInteger.fromDERInteger(decode.r)
9336 var s = BigInteger.fromDERInteger(decode.s)
9337
9338 return new ECSignature(r, s)
9339}
9340
9341// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
9342ECSignature.parseScriptSignature = function (buffer) {
9343 var hashType = buffer.readUInt8(buffer.length - 1)
9344 var hashTypeMod = hashType & ~0x80
9345
9346 if (hashTypeMod <= 0x00 || hashTypeMod >= 0x04) throw new Error('Invalid hashType ' + hashType)
9347
9348 return {
9349 signature: ECSignature.fromDER(buffer.slice(0, -1)),
9350 hashType: hashType
9351 }
9352}
9353
9354ECSignature.prototype.toCompact = function (i, compressed) {
9355 if (compressed) {
9356 i += 4
9357 }
9358
9359 i += 27
9360
9361 var buffer = Buffer.alloc(65)
9362 buffer.writeUInt8(i, 0)
9f59e99b 9363 this.toRSBuffer(buffer, 1)
a0091a40
IC
9364 return buffer
9365}
9366
9367ECSignature.prototype.toDER = function () {
9368 var r = Buffer.from(this.r.toDERInteger())
9369 var s = Buffer.from(this.s.toDERInteger())
9370
9371 return bip66.encode(r, s)
9372}
9373
9f59e99b
IC
9374ECSignature.prototype.toRSBuffer = function (buffer, offset) {
9375 buffer = buffer || Buffer.alloc(64)
9376 this.r.toBuffer(32).copy(buffer, offset)
9377 this.s.toBuffer(32).copy(buffer, offset + 32)
9378 return buffer
9379}
9380
a0091a40
IC
9381ECSignature.prototype.toScriptSignature = function (hashType) {
9382 var hashTypeMod = hashType & ~0x80
9383 if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType)
9384
9385 var hashTypeBuffer = Buffer.alloc(1)
9386 hashTypeBuffer.writeUInt8(hashType, 0)
9387
9388 return Buffer.concat([this.toDER(), hashTypeBuffer])
9389}
9390
9391module.exports = ECSignature
9392
9393}).call(this,require("buffer").Buffer)
b777ff55 9394},{"./types":80,"bigi":39,"bip66":41,"buffer":5,"typeforce":112}],51:[function(require,module,exports){
a0091a40
IC
9395var Buffer = require('safe-buffer').Buffer
9396var base58check = require('bs58check')
9397var bcrypto = require('./crypto')
9398var createHmac = require('create-hmac')
9399var typeforce = require('typeforce')
9400var types = require('./types')
9401var NETWORKS = require('./networks')
9402
9403var BigInteger = require('bigi')
9404var ECPair = require('./ecpair')
9405
9406var ecurve = require('ecurve')
9407var curve = ecurve.getCurveByName('secp256k1')
9408
9409function HDNode (keyPair, chainCode) {
9410 typeforce(types.tuple('ECPair', types.Buffer256bit), arguments)
9411
9412 if (!keyPair.compressed) throw new TypeError('BIP32 only allows compressed keyPairs')
9413
9414 this.keyPair = keyPair
9415 this.chainCode = chainCode
9416 this.depth = 0
9417 this.index = 0
9418 this.parentFingerprint = 0x00000000
9419}
9420
9421HDNode.HIGHEST_BIT = 0x80000000
9422HDNode.LENGTH = 78
9423HDNode.MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8')
9424
9425HDNode.fromSeedBuffer = function (seed, network) {
9426 typeforce(types.tuple(types.Buffer, types.maybe(types.Network)), arguments)
9427
9428 if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits')
9429 if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits')
9430
9431 var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest()
9432 var IL = I.slice(0, 32)
9433 var IR = I.slice(32)
9434
9435 // In case IL is 0 or >= n, the master key is invalid
9436 // This is handled by the ECPair constructor
9437 var pIL = BigInteger.fromBuffer(IL)
9438 var keyPair = new ECPair(pIL, null, {
9439 network: network
9440 })
9441
9442 return new HDNode(keyPair, IR)
9443}
9444
9445HDNode.fromSeedHex = function (hex, network) {
9446 return HDNode.fromSeedBuffer(Buffer.from(hex, 'hex'), network)
9447}
9448
9449HDNode.fromBase58 = function (string, networks) {
9450 var buffer = base58check.decode(string)
9451 if (buffer.length !== 78) throw new Error('Invalid buffer length')
9452
9453 // 4 bytes: version bytes
9454 var version = buffer.readUInt32BE(0)
9455 var network
9456
9457 // list of networks?
9458 if (Array.isArray(networks)) {
9459 network = networks.filter(function (x) {
9460 return version === x.bip32.private ||
9461 version === x.bip32.public
9462 }).pop()
9463
9464 if (!network) throw new Error('Unknown network version')
9465
9466 // otherwise, assume a network object (or default to bitcoin)
9467 } else {
9468 network = networks || NETWORKS.bitcoin
9469 }
9470
9471 if (version !== network.bip32.private &&
9472 version !== network.bip32.public) throw new Error('Invalid network version')
9473
9474 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
9475 var depth = buffer[4]
9476
9477 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9478 var parentFingerprint = buffer.readUInt32BE(5)
9479 if (depth === 0) {
9480 if (parentFingerprint !== 0x00000000) throw new Error('Invalid parent fingerprint')
9481 }
9482
9483 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9484 // This is encoded in MSB order. (0x00000000 if master key)
9485 var index = buffer.readUInt32BE(9)
9486 if (depth === 0 && index !== 0) throw new Error('Invalid index')
9487
9488 // 32 bytes: the chain code
9489 var chainCode = buffer.slice(13, 45)
9490 var keyPair
9491
9492 // 33 bytes: private key data (0x00 + k)
9493 if (version === network.bip32.private) {
9494 if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key')
9495
9496 var d = BigInteger.fromBuffer(buffer.slice(46, 78))
9497 keyPair = new ECPair(d, null, { network: network })
9498
9499 // 33 bytes: public key data (0x02 + X or 0x03 + X)
9500 } else {
9501 var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78))
9502 // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw
9503
9504 // Verify that the X coordinate in the public point corresponds to a point on the curve.
9505 // If not, the extended public key is invalid.
9506 curve.validate(Q)
9507
9508 keyPair = new ECPair(null, Q, { network: network })
9509 }
9510
9511 var hd = new HDNode(keyPair, chainCode)
9512 hd.depth = depth
9513 hd.index = index
9514 hd.parentFingerprint = parentFingerprint
9515
9516 return hd
9517}
9518
9519HDNode.prototype.getAddress = function () {
9520 return this.keyPair.getAddress()
9521}
9522
9523HDNode.prototype.getIdentifier = function () {
9524 return bcrypto.hash160(this.keyPair.getPublicKeyBuffer())
9525}
9526
9527HDNode.prototype.getFingerprint = function () {
9528 return this.getIdentifier().slice(0, 4)
9529}
9530
9531HDNode.prototype.getNetwork = function () {
9532 return this.keyPair.getNetwork()
9533}
9534
9535HDNode.prototype.getPublicKeyBuffer = function () {
9536 return this.keyPair.getPublicKeyBuffer()
9537}
9538
9539HDNode.prototype.neutered = function () {
9540 var neuteredKeyPair = new ECPair(null, this.keyPair.Q, {
9541 network: this.keyPair.network
9542 })
9543
9544 var neutered = new HDNode(neuteredKeyPair, this.chainCode)
9545 neutered.depth = this.depth
9546 neutered.index = this.index
9547 neutered.parentFingerprint = this.parentFingerprint
9548
9549 return neutered
9550}
9551
9552HDNode.prototype.sign = function (hash) {
9553 return this.keyPair.sign(hash)
9554}
9555
9556HDNode.prototype.verify = function (hash, signature) {
9557 return this.keyPair.verify(hash, signature)
9558}
9559
9560HDNode.prototype.toBase58 = function (__isPrivate) {
9561 if (__isPrivate !== undefined) throw new TypeError('Unsupported argument in 2.0.0')
9562
9563 // Version
9564 var network = this.keyPair.network
9565 var version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public
9566 var buffer = Buffer.allocUnsafe(78)
9567
9568 // 4 bytes: version bytes
9569 buffer.writeUInt32BE(version, 0)
9570
9571 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
9572 buffer.writeUInt8(this.depth, 4)
9573
9574 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9575 buffer.writeUInt32BE(this.parentFingerprint, 5)
9576
9577 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9578 // This is encoded in big endian. (0x00000000 if master key)
9579 buffer.writeUInt32BE(this.index, 9)
9580
9581 // 32 bytes: the chain code
9582 this.chainCode.copy(buffer, 13)
9583
9584 // 33 bytes: the public key or private key data
9585 if (!this.isNeutered()) {
9586 // 0x00 + k for private keys
9587 buffer.writeUInt8(0, 45)
9588 this.keyPair.d.toBuffer(32).copy(buffer, 46)
9589
9590 // 33 bytes: the public key
9591 } else {
9592 // X9.62 encoding for public keys
9593 this.keyPair.getPublicKeyBuffer().copy(buffer, 45)
9594 }
9595
9596 return base58check.encode(buffer)
9597}
9598
9599// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
9600HDNode.prototype.derive = function (index) {
9601 typeforce(types.UInt32, index)
9602
9603 var isHardened = index >= HDNode.HIGHEST_BIT
9604 var data = Buffer.allocUnsafe(37)
9605
9606 // Hardened child
9607 if (isHardened) {
9608 if (this.isNeutered()) throw new TypeError('Could not derive hardened child key')
9609
9610 // data = 0x00 || ser256(kpar) || ser32(index)
9611 data[0] = 0x00
9612 this.keyPair.d.toBuffer(32).copy(data, 1)
9613 data.writeUInt32BE(index, 33)
9614
9615 // Normal child
9616 } else {
9617 // data = serP(point(kpar)) || ser32(index)
9618 // = serP(Kpar) || ser32(index)
9619 this.keyPair.getPublicKeyBuffer().copy(data, 0)
9620 data.writeUInt32BE(index, 33)
9621 }
9622
9623 var I = createHmac('sha512', this.chainCode).update(data).digest()
9624 var IL = I.slice(0, 32)
9625 var IR = I.slice(32)
9626
9627 var pIL = BigInteger.fromBuffer(IL)
9628
9629 // In case parse256(IL) >= n, proceed with the next value for i
9630 if (pIL.compareTo(curve.n) >= 0) {
9631 return this.derive(index + 1)
9632 }
9633
9634 // Private parent key -> private child key
9635 var derivedKeyPair
9636 if (!this.isNeutered()) {
9637 // ki = parse256(IL) + kpar (mod n)
9638 var ki = pIL.add(this.keyPair.d).mod(curve.n)
9639
9640 // In case ki == 0, proceed with the next value for i
9641 if (ki.signum() === 0) {
9642 return this.derive(index + 1)
9643 }
9644
9645 derivedKeyPair = new ECPair(ki, null, {
9646 network: this.keyPair.network
9647 })
9648
9649 // Public parent key -> public child key
9650 } else {
9651 // Ki = point(parse256(IL)) + Kpar
9652 // = G*IL + Kpar
9653 var Ki = curve.G.multiply(pIL).add(this.keyPair.Q)
9654
9655 // In case Ki is the point at infinity, proceed with the next value for i
9656 if (curve.isInfinity(Ki)) {
9657 return this.derive(index + 1)
9658 }
9659
9660 derivedKeyPair = new ECPair(null, Ki, {
9661 network: this.keyPair.network
9662 })
9663 }
9664
9665 var hd = new HDNode(derivedKeyPair, IR)
9666 hd.depth = this.depth + 1
9667 hd.index = index
9668 hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)
9669
9670 return hd
9671}
9672
9673HDNode.prototype.deriveHardened = function (index) {
9674 typeforce(types.UInt31, index)
9675
9676 // Only derives hardened private keys by default
9677 return this.derive(index + HDNode.HIGHEST_BIT)
9678}
9679
9680// Private === not neutered
9681// Public === neutered
9682HDNode.prototype.isNeutered = function () {
9683 return !(this.keyPair.d)
9684}
9685
9686HDNode.prototype.derivePath = function (path) {
9687 typeforce(types.BIP32Path, path)
9688
9689 var splitPath = path.split('/')
9690 if (splitPath[0] === 'm') {
9691 if (this.parentFingerprint) {
9692 throw new Error('Not a master node')
9693 }
9694
9695 splitPath = splitPath.slice(1)
9696 }
9697
9698 return splitPath.reduce(function (prevHd, indexStr) {
9699 var index
9700 if (indexStr.slice(-1) === "'") {
9701 index = parseInt(indexStr.slice(0, -1), 10)
9702 return prevHd.deriveHardened(index)
9703 } else {
9704 index = parseInt(indexStr, 10)
9705 return prevHd.derive(index)
9706 }
9707 }, this)
9708}
9709
9710module.exports = HDNode
9711
b777ff55 9712},{"./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){
9f59e99b
IC
9713var script = require('./script')
9714
9715var templates = require('./templates')
9716for (var key in templates) {
9717 script[key] = templates[key]
9718}
9719
a0091a40 9720module.exports = {
9f59e99b
IC
9721 bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0
9722
a0091a40
IC
9723 Block: require('./block'),
9724 ECPair: require('./ecpair'),
9725 ECSignature: require('./ecsignature'),
9726 HDNode: require('./hdnode'),
9727 Transaction: require('./transaction'),
9728 TransactionBuilder: require('./transaction_builder'),
9729
9730 address: require('./address'),
a0091a40
IC
9731 crypto: require('./crypto'),
9732 networks: require('./networks'),
9733 opcodes: require('bitcoin-ops'),
9f59e99b 9734 script: script
a0091a40
IC
9735}
9736
9f59e99b 9737},{"./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){
a0091a40
IC
9738// https://en.bitcoin.it/wiki/List_of_address_prefixes
9739// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
9740
9741module.exports = {
9742 bitcoin: {
9743 messagePrefix: '\x18Bitcoin Signed Message:\n',
9f59e99b 9744 bech32: 'bc',
a0091a40
IC
9745 bip32: {
9746 public: 0x0488b21e,
9747 private: 0x0488ade4
9748 },
9749 pubKeyHash: 0x00,
9750 scriptHash: 0x05,
9751 wif: 0x80
9752 },
9753 testnet: {
9754 messagePrefix: '\x18Bitcoin Signed Message:\n',
9f59e99b 9755 bech32: 'tb',
a0091a40
IC
9756 bip32: {
9757 public: 0x043587cf,
9758 private: 0x04358394
9759 },
9760 pubKeyHash: 0x6f,
9761 scriptHash: 0xc4,
9762 wif: 0xef
9763 },
9764 litecoin: {
9765 messagePrefix: '\x19Litecoin Signed Message:\n',
9766 bip32: {
9767 public: 0x019da462,
9768 private: 0x019d9cfe
9769 },
9770 pubKeyHash: 0x30,
9771 scriptHash: 0x32,
9772 wif: 0xb0
9773 }
9774}
9775
9f59e99b 9776},{}],54:[function(require,module,exports){
a0091a40
IC
9777var Buffer = require('safe-buffer').Buffer
9778var bip66 = require('bip66')
9779var pushdata = require('pushdata-bitcoin')
9780var typeforce = require('typeforce')
9781var types = require('./types')
9782var scriptNumber = require('./script_number')
9783
9784var OPS = require('bitcoin-ops')
9785var REVERSE_OPS = require('bitcoin-ops/map')
9786var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
9787
9788function isOPInt (value) {
9789 return types.Number(value) &&
9790 ((value === OPS.OP_0) ||
9791 (value >= OPS.OP_1 && value <= OPS.OP_16) ||
9792 (value === OPS.OP_1NEGATE))
9793}
9794
9795function isPushOnlyChunk (value) {
9796 return types.Buffer(value) || isOPInt(value)
9797}
9798
9799function isPushOnly (value) {
9800 return types.Array(value) && value.every(isPushOnlyChunk)
9801}
9802
9f59e99b
IC
9803function asMinimalOP (buffer) {
9804 if (buffer.length === 0) return OPS.OP_0
9805 if (buffer.length !== 1) return
9806 if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0]
9807 if (buffer[0] === 0x81) return OPS.OP_1NEGATE
9808}
9809
a0091a40
IC
9810function compile (chunks) {
9811 // TODO: remove me
9812 if (Buffer.isBuffer(chunks)) return chunks
9813
9814 typeforce(types.Array, chunks)
9815
9816 var bufferSize = chunks.reduce(function (accum, chunk) {
9817 // data chunk
9818 if (Buffer.isBuffer(chunk)) {
9819 // adhere to BIP62.3, minimal push policy
9f59e99b 9820 if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) {
a0091a40
IC
9821 return accum + 1
9822 }
9823
9824 return accum + pushdata.encodingLength(chunk.length) + chunk.length
9825 }
9826
9827 // opcode
9828 return accum + 1
9829 }, 0.0)
9830
9831 var buffer = Buffer.allocUnsafe(bufferSize)
9832 var offset = 0
9833
9834 chunks.forEach(function (chunk) {
9835 // data chunk
9836 if (Buffer.isBuffer(chunk)) {
9837 // adhere to BIP62.3, minimal push policy
9f59e99b
IC
9838 var opcode = asMinimalOP(chunk)
9839 if (opcode !== undefined) {
a0091a40
IC
9840 buffer.writeUInt8(opcode, offset)
9841 offset += 1
9842 return
9843 }
9844
a0091a40 9845 offset += pushdata.encode(buffer, chunk.length, offset)
a0091a40
IC
9846 chunk.copy(buffer, offset)
9847 offset += chunk.length
9848
9849 // opcode
9850 } else {
9851 buffer.writeUInt8(chunk, offset)
9852 offset += 1
9853 }
9854 })
9855
9856 if (offset !== buffer.length) throw new Error('Could not decode chunks')
9857 return buffer
9858}
9859
9860function decompile (buffer) {
9861 // TODO: remove me
9862 if (types.Array(buffer)) return buffer
9863
9864 typeforce(types.Buffer, buffer)
9865
9866 var chunks = []
9867 var i = 0
9868
9869 while (i < buffer.length) {
9870 var opcode = buffer[i]
9871
9872 // data chunk
9873 if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) {
9874 var d = pushdata.decode(buffer, i)
9875
9876 // did reading a pushDataInt fail? empty script
9877 if (d === null) return []
9878 i += d.size
9879
9880 // attempt to read too much data? empty script
9881 if (i + d.number > buffer.length) return []
9882
9883 var data = buffer.slice(i, i + d.number)
9884 i += d.number
9885
9f59e99b
IC
9886 // decompile minimally
9887 var op = asMinimalOP(data)
9888 if (op !== undefined) {
9889 chunks.push(op)
9890 } else {
9891 chunks.push(data)
9892 }
a0091a40
IC
9893
9894 // opcode
9895 } else {
9896 chunks.push(opcode)
9897
9898 i += 1
9899 }
9900 }
9901
9902 return chunks
9903}
9904
9905function toASM (chunks) {
9906 if (Buffer.isBuffer(chunks)) {
9907 chunks = decompile(chunks)
9908 }
9909
9910 return chunks.map(function (chunk) {
9911 // data?
9f59e99b
IC
9912 if (Buffer.isBuffer(chunk)) {
9913 var op = asMinimalOP(chunk)
9914 if (op === undefined) return chunk.toString('hex')
9915 chunk = op
9916 }
a0091a40
IC
9917
9918 // opcode!
9919 return REVERSE_OPS[chunk]
9920 }).join(' ')
9921}
9922
9923function fromASM (asm) {
9924 typeforce(types.String, asm)
9925
9926 return compile(asm.split(' ').map(function (chunkStr) {
9927 // opcode?
9928 if (OPS[chunkStr] !== undefined) return OPS[chunkStr]
9929 typeforce(types.Hex, chunkStr)
9930
9931 // data!
9932 return Buffer.from(chunkStr, 'hex')
9933 }))
9934}
9935
9936function toStack (chunks) {
9937 chunks = decompile(chunks)
9938 typeforce(isPushOnly, chunks)
9939
9940 return chunks.map(function (op) {
9941 if (Buffer.isBuffer(op)) return op
9942 if (op === OPS.OP_0) return Buffer.allocUnsafe(0)
9943
9944 return scriptNumber.encode(op - OP_INT_BASE)
9945 })
9946}
9947
9948function isCanonicalPubKey (buffer) {
9949 if (!Buffer.isBuffer(buffer)) return false
9950 if (buffer.length < 33) return false
9951
9952 switch (buffer[0]) {
9953 case 0x02:
9954 case 0x03:
9955 return buffer.length === 33
9956 case 0x04:
9957 return buffer.length === 65
9958 }
9959
9960 return false
9961}
9962
9963function isDefinedHashType (hashType) {
9964 var hashTypeMod = hashType & ~0x80
9965
9966// return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE
9967 return hashTypeMod > 0x00 && hashTypeMod < 0x04
9968}
9969
9970function isCanonicalSignature (buffer) {
9971 if (!Buffer.isBuffer(buffer)) return false
9972 if (!isDefinedHashType(buffer[buffer.length - 1])) return false
9973
9974 return bip66.check(buffer.slice(0, -1))
9975}
9976
9977module.exports = {
9978 compile: compile,
9979 decompile: decompile,
9980 fromASM: fromASM,
9981 toASM: toASM,
9982 toStack: toStack,
9983
9984 number: require('./script_number'),
9985
9986 isCanonicalPubKey: isCanonicalPubKey,
9987 isCanonicalSignature: isCanonicalSignature,
9988 isPushOnly: isPushOnly,
9989 isDefinedHashType: isDefinedHashType
9990}
9991
b777ff55 9992},{"./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){
a0091a40
IC
9993var Buffer = require('safe-buffer').Buffer
9994
9995function decode (buffer, maxLength, minimal) {
9996 maxLength = maxLength || 4
9997 minimal = minimal === undefined ? true : minimal
9998
9999 var length = buffer.length
10000 if (length === 0) return 0
10001 if (length > maxLength) throw new TypeError('Script number overflow')
10002 if (minimal) {
10003 if ((buffer[length - 1] & 0x7f) === 0) {
10004 if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number')
10005 }
10006 }
10007
10008 // 40-bit
10009 if (length === 5) {
10010 var a = buffer.readUInt32LE(0)
10011 var b = buffer.readUInt8(4)
10012
10013 if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a)
10014 return (b * 0x100000000) + a
10015 }
10016
10017 var result = 0
10018
10019 // 32-bit / 24-bit / 16-bit / 8-bit
10020 for (var i = 0; i < length; ++i) {
10021 result |= buffer[i] << (8 * i)
10022 }
10023
10024 if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1))))
10025 return result
10026}
10027
10028function scriptNumSize (i) {
10029 return i > 0x7fffffff ? 5
10030 : i > 0x7fffff ? 4
10031 : i > 0x7fff ? 3
10032 : i > 0x7f ? 2
10033 : i > 0x00 ? 1
10034 : 0
10035}
10036
10037function encode (number) {
10038 var value = Math.abs(number)
10039 var size = scriptNumSize(value)
10040 var buffer = Buffer.allocUnsafe(size)
10041 var negative = number < 0
10042
10043 for (var i = 0; i < size; ++i) {
10044 buffer.writeUInt8(value & 0xff, i)
10045 value >>= 8
10046 }
10047
10048 if (buffer[size - 1] & 0x80) {
10049 buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1)
10050 } else if (negative) {
10051 buffer[size - 1] |= 0x80
10052 }
10053
10054 return buffer
10055}
10056
10057module.exports = {
10058 decode: decode,
10059 encode: encode
10060}
10061
b777ff55 10062},{"safe-buffer":101}],56:[function(require,module,exports){
a0091a40
IC
10063var decompile = require('../script').decompile
10064var multisig = require('./multisig')
10065var nullData = require('./nulldata')
10066var pubKey = require('./pubkey')
10067var pubKeyHash = require('./pubkeyhash')
10068var scriptHash = require('./scripthash')
10069var witnessPubKeyHash = require('./witnesspubkeyhash')
10070var witnessScriptHash = require('./witnessscripthash')
10071var witnessCommitment = require('./witnesscommitment')
10072
10073var types = {
10074 MULTISIG: 'multisig',
10075 NONSTANDARD: 'nonstandard',
10076 NULLDATA: 'nulldata',
10077 P2PK: 'pubkey',
10078 P2PKH: 'pubkeyhash',
10079 P2SH: 'scripthash',
10080 P2WPKH: 'witnesspubkeyhash',
10081 P2WSH: 'witnessscripthash',
10082 WITNESS_COMMITMENT: 'witnesscommitment'
10083}
10084
10085function classifyOutput (script) {
10086 if (witnessPubKeyHash.output.check(script)) return types.P2WPKH
10087 if (witnessScriptHash.output.check(script)) return types.P2WSH
10088 if (pubKeyHash.output.check(script)) return types.P2PKH
10089 if (scriptHash.output.check(script)) return types.P2SH
10090
10091 // XXX: optimization, below functions .decompile before use
10092 var chunks = decompile(script)
10093 if (multisig.output.check(chunks)) return types.MULTISIG
10094 if (pubKey.output.check(chunks)) return types.P2PK
10095 if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT
10096 if (nullData.output.check(chunks)) return types.NULLDATA
10097
10098 return types.NONSTANDARD
10099}
10100
10101function classifyInput (script, allowIncomplete) {
10102 // XXX: optimization, below functions .decompile before use
10103 var chunks = decompile(script)
10104
10105 if (pubKeyHash.input.check(chunks)) return types.P2PKH
10106 if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH
10107 if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG
10108 if (pubKey.input.check(chunks)) return types.P2PK
10109
10110 return types.NONSTANDARD
10111}
10112
10113function classifyWitness (script, allowIncomplete) {
10114 // XXX: optimization, below functions .decompile before use
10115 var chunks = decompile(script)
10116
10117 if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH
10118 if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH
10119
10120 return types.NONSTANDARD
10121}
10122
10123module.exports = {
10124 classifyInput: classifyInput,
10125 classifyOutput: classifyOutput,
10126 classifyWitness: classifyWitness,
10127 multisig: multisig,
10128 nullData: nullData,
10129 pubKey: pubKey,
10130 pubKeyHash: pubKeyHash,
10131 scriptHash: scriptHash,
10132 witnessPubKeyHash: witnessPubKeyHash,
10133 witnessScriptHash: witnessScriptHash,
10134 witnessCommitment: witnessCommitment,
10135 types: types
10136}
10137
9f59e99b 10138},{"../script":54,"./multisig":57,"./nulldata":60,"./pubkey":61,"./pubkeyhash":64,"./scripthash":67,"./witnesscommitment":70,"./witnesspubkeyhash":72,"./witnessscripthash":75}],57:[function(require,module,exports){
a0091a40
IC
10139module.exports = {
10140 input: require('./input'),
10141 output: require('./output')
10142}
10143
9f59e99b 10144},{"./input":58,"./output":59}],58:[function(require,module,exports){
a0091a40
IC
10145// OP_0 [signatures ...]
10146
10147var Buffer = require('safe-buffer').Buffer
10148var bscript = require('../../script')
9f59e99b 10149var p2mso = require('./output')
a0091a40
IC
10150var typeforce = require('typeforce')
10151var OPS = require('bitcoin-ops')
10152
10153function partialSignature (value) {
10154 return value === OPS.OP_0 || bscript.isCanonicalSignature(value)
10155}
10156
10157function check (script, allowIncomplete) {
10158 var chunks = bscript.decompile(script)
10159 if (chunks.length < 2) return false
10160 if (chunks[0] !== OPS.OP_0) return false
10161
10162 if (allowIncomplete) {
10163 return chunks.slice(1).every(partialSignature)
10164 }
10165
10166 return chunks.slice(1).every(bscript.isCanonicalSignature)
10167}
10168check.toJSON = function () { return 'multisig input' }
10169
10170var EMPTY_BUFFER = Buffer.allocUnsafe(0)
10171
10172function encodeStack (signatures, scriptPubKey) {
10173 typeforce([partialSignature], signatures)
10174
10175 if (scriptPubKey) {
9f59e99b 10176 var scriptData = p2mso.decode(scriptPubKey)
a0091a40
IC
10177
10178 if (signatures.length < scriptData.m) {
10179 throw new TypeError('Not enough signatures provided')
10180 }
10181
10182 if (signatures.length > scriptData.pubKeys.length) {
10183 throw new TypeError('Too many signatures provided')
10184 }
10185 }
10186
9f59e99b
IC
10187 return [].concat(EMPTY_BUFFER, signatures.map(function (sig) {
10188 if (sig === OPS.OP_0) {
10189 return EMPTY_BUFFER
10190 }
10191 return sig
10192 }))
a0091a40
IC
10193}
10194
10195function encode (signatures, scriptPubKey) {
10196 return bscript.compile(encodeStack(signatures, scriptPubKey))
10197}
10198
10199function decodeStack (stack, allowIncomplete) {
b777ff55 10200 typeforce(typeforce.Array, stack)
a0091a40
IC
10201 typeforce(check, stack, allowIncomplete)
10202 return stack.slice(1)
10203}
10204
10205function decode (buffer, allowIncomplete) {
10206 var stack = bscript.decompile(buffer)
10207 return decodeStack(stack, allowIncomplete)
10208}
10209
10210module.exports = {
10211 check: check,
10212 decode: decode,
10213 decodeStack: decodeStack,
10214 encode: encode,
10215 encodeStack: encodeStack
10216}
10217
b777ff55 10218},{"../../script":54,"./output":59,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],59:[function(require,module,exports){
a0091a40
IC
10219// m [pubKeys ...] n OP_CHECKMULTISIG
10220
10221var bscript = require('../../script')
10222var types = require('../../types')
10223var typeforce = require('typeforce')
10224var OPS = require('bitcoin-ops')
10225var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
10226
10227function check (script, allowIncomplete) {
10228 var chunks = bscript.decompile(script)
10229
10230 if (chunks.length < 4) return false
10231 if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false
10232 if (!types.Number(chunks[0])) return false
10233 if (!types.Number(chunks[chunks.length - 2])) return false
10234 var m = chunks[0] - OP_INT_BASE
10235 var n = chunks[chunks.length - 2] - OP_INT_BASE
10236
10237 if (m <= 0) return false
10238 if (n > 16) return false
10239 if (m > n) return false
10240 if (n !== chunks.length - 3) return false
10241 if (allowIncomplete) return true
10242
10243 var keys = chunks.slice(1, -2)
10244 return keys.every(bscript.isCanonicalPubKey)
10245}
10246check.toJSON = function () { return 'multi-sig output' }
10247
10248function encode (m, pubKeys) {
10249 typeforce({
10250 m: types.Number,
10251 pubKeys: [bscript.isCanonicalPubKey]
10252 }, {
10253 m: m,
10254 pubKeys: pubKeys
10255 })
10256
10257 var n = pubKeys.length
10258 if (n < m) throw new TypeError('Not enough pubKeys provided')
10259
10260 return bscript.compile([].concat(
10261 OP_INT_BASE + m,
10262 pubKeys,
10263 OP_INT_BASE + n,
10264 OPS.OP_CHECKMULTISIG
10265 ))
10266}
10267
10268function decode (buffer, allowIncomplete) {
10269 var chunks = bscript.decompile(buffer)
10270 typeforce(check, chunks, allowIncomplete)
10271
10272 return {
10273 m: chunks[0] - OP_INT_BASE,
10274 pubKeys: chunks.slice(1, -2)
10275 }
10276}
10277
10278module.exports = {
10279 check: check,
10280 decode: decode,
10281 encode: encode
10282}
10283
b777ff55 10284},{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],60:[function(require,module,exports){
a0091a40
IC
10285// OP_RETURN {data}
10286
10287var bscript = require('../script')
10288var types = require('../types')
10289var typeforce = require('typeforce')
10290var OPS = require('bitcoin-ops')
10291
10292function check (script) {
10293 var buffer = bscript.compile(script)
10294
10295 return buffer.length > 1 &&
10296 buffer[0] === OPS.OP_RETURN
10297}
10298check.toJSON = function () { return 'null data output' }
10299
10300function encode (data) {
10301 typeforce(types.Buffer, data)
10302
10303 return bscript.compile([OPS.OP_RETURN, data])
10304}
10305
10306function decode (buffer) {
10307 typeforce(check, buffer)
10308
10309 return buffer.slice(2)
10310}
10311
10312module.exports = {
10313 output: {
10314 check: check,
10315 decode: decode,
10316 encode: encode
10317 }
10318}
10319
b777ff55 10320},{"../script":54,"../types":80,"bitcoin-ops":42,"typeforce":112}],61:[function(require,module,exports){
9f59e99b
IC
10321arguments[4][57][0].apply(exports,arguments)
10322},{"./input":62,"./output":63,"dup":57}],62:[function(require,module,exports){
a0091a40
IC
10323// {signature}
10324
10325var bscript = require('../../script')
a0091a40
IC
10326var typeforce = require('typeforce')
10327
10328function check (script) {
10329 var chunks = bscript.decompile(script)
10330
10331 return chunks.length === 1 &&
10332 bscript.isCanonicalSignature(chunks[0])
10333}
10334check.toJSON = function () { return 'pubKey input' }
10335
10336function encodeStack (signature) {
9f59e99b 10337 typeforce(bscript.isCanonicalSignature, signature)
a0091a40
IC
10338 return [signature]
10339}
10340
10341function encode (signature) {
10342 return bscript.compile(encodeStack(signature))
10343}
10344
10345function decodeStack (stack) {
b777ff55 10346 typeforce(typeforce.Array, stack)
a0091a40
IC
10347 typeforce(check, stack)
10348 return stack[0]
10349}
10350
10351function decode (buffer) {
10352 var stack = bscript.decompile(buffer)
10353 return decodeStack(stack)
10354}
10355
10356module.exports = {
10357 check: check,
10358 decode: decode,
10359 decodeStack: decodeStack,
10360 encode: encode,
10361 encodeStack: encodeStack
10362}
10363
b777ff55 10364},{"../../script":54,"typeforce":112}],63:[function(require,module,exports){
a0091a40
IC
10365// {pubKey} OP_CHECKSIG
10366
10367var bscript = require('../../script')
10368var typeforce = require('typeforce')
10369var OPS = require('bitcoin-ops')
10370
10371function check (script) {
10372 var chunks = bscript.decompile(script)
10373
10374 return chunks.length === 2 &&
10375 bscript.isCanonicalPubKey(chunks[0]) &&
10376 chunks[1] === OPS.OP_CHECKSIG
10377}
10378check.toJSON = function () { return 'pubKey output' }
10379
10380function encode (pubKey) {
10381 typeforce(bscript.isCanonicalPubKey, pubKey)
10382
10383 return bscript.compile([pubKey, OPS.OP_CHECKSIG])
10384}
10385
10386function decode (buffer) {
10387 var chunks = bscript.decompile(buffer)
10388 typeforce(check, chunks)
10389
10390 return chunks[0]
10391}
10392
10393module.exports = {
10394 check: check,
10395 decode: decode,
10396 encode: encode
10397}
10398
b777ff55 10399},{"../../script":54,"bitcoin-ops":42,"typeforce":112}],64:[function(require,module,exports){
9f59e99b
IC
10400arguments[4][57][0].apply(exports,arguments)
10401},{"./input":65,"./output":66,"dup":57}],65:[function(require,module,exports){
a0091a40
IC
10402// {signature} {pubKey}
10403
10404var bscript = require('../../script')
a0091a40
IC
10405var typeforce = require('typeforce')
10406
10407function check (script) {
10408 var chunks = bscript.decompile(script)
10409
10410 return chunks.length === 2 &&
10411 bscript.isCanonicalSignature(chunks[0]) &&
10412 bscript.isCanonicalPubKey(chunks[1])
10413}
10414check.toJSON = function () { return 'pubKeyHash input' }
10415
10416function encodeStack (signature, pubKey) {
10417 typeforce({
9f59e99b
IC
10418 signature: bscript.isCanonicalSignature,
10419 pubKey: bscript.isCanonicalPubKey
a0091a40 10420 }, {
9f59e99b
IC
10421 signature: signature,
10422 pubKey: pubKey
a0091a40
IC
10423 })
10424
10425 return [signature, pubKey]
10426}
10427
10428function encode (signature, pubKey) {
10429 return bscript.compile(encodeStack(signature, pubKey))
10430}
10431
10432function decodeStack (stack) {
b777ff55 10433 typeforce(typeforce.Array, stack)
a0091a40
IC
10434 typeforce(check, stack)
10435
10436 return {
10437 signature: stack[0],
10438 pubKey: stack[1]
10439 }
10440}
10441
10442function decode (buffer) {
10443 var stack = bscript.decompile(buffer)
10444 return decodeStack(stack)
10445}
10446
10447module.exports = {
10448 check: check,
10449 decode: decode,
10450 decodeStack: decodeStack,
10451 encode: encode,
10452 encodeStack: encodeStack
10453}
10454
b777ff55 10455},{"../../script":54,"typeforce":112}],66:[function(require,module,exports){
a0091a40
IC
10456// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
10457
10458var bscript = require('../../script')
10459var types = require('../../types')
10460var typeforce = require('typeforce')
10461var OPS = require('bitcoin-ops')
10462
10463function check (script) {
10464 var buffer = bscript.compile(script)
10465
10466 return buffer.length === 25 &&
10467 buffer[0] === OPS.OP_DUP &&
10468 buffer[1] === OPS.OP_HASH160 &&
10469 buffer[2] === 0x14 &&
10470 buffer[23] === OPS.OP_EQUALVERIFY &&
10471 buffer[24] === OPS.OP_CHECKSIG
10472}
10473check.toJSON = function () { return 'pubKeyHash output' }
10474
10475function encode (pubKeyHash) {
10476 typeforce(types.Hash160bit, pubKeyHash)
10477
10478 return bscript.compile([
10479 OPS.OP_DUP,
10480 OPS.OP_HASH160,
10481 pubKeyHash,
10482 OPS.OP_EQUALVERIFY,
10483 OPS.OP_CHECKSIG
10484 ])
10485}
10486
10487function decode (buffer) {
10488 typeforce(check, buffer)
10489
10490 return buffer.slice(3, 23)
10491}
10492
10493module.exports = {
10494 check: check,
10495 decode: decode,
10496 encode: encode
10497}
10498
b777ff55 10499},{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],67:[function(require,module,exports){
9f59e99b
IC
10500arguments[4][57][0].apply(exports,arguments)
10501},{"./input":68,"./output":69,"dup":57}],68:[function(require,module,exports){
a0091a40
IC
10502// <scriptSig> {serialized scriptPubKey script}
10503
10504var Buffer = require('safe-buffer').Buffer
10505var bscript = require('../../script')
10506var typeforce = require('typeforce')
10507
9f59e99b
IC
10508var p2ms = require('../multisig/')
10509var p2pk = require('../pubkey/')
10510var p2pkh = require('../pubkeyhash/')
10511var p2wpkho = require('../witnesspubkeyhash/output')
10512var p2wsho = require('../witnessscripthash/output')
10513
a0091a40
IC
10514function check (script, allowIncomplete) {
10515 var chunks = bscript.decompile(script)
10516 if (chunks.length < 1) return false
10517
10518 var lastChunk = chunks[chunks.length - 1]
10519 if (!Buffer.isBuffer(lastChunk)) return false
10520
10521 var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1)))
10522 var redeemScriptChunks = bscript.decompile(lastChunk)
10523
10524 // is redeemScript a valid script?
10525 if (redeemScriptChunks.length === 0) return false
10526
10527 // is redeemScriptSig push only?
10528 if (!bscript.isPushOnly(scriptSigChunks)) return false
10529
9f59e99b 10530 // is witness?
a0091a40 10531 if (chunks.length === 1) {
9f59e99b
IC
10532 return p2wsho.check(redeemScriptChunks) ||
10533 p2wpkho.check(redeemScriptChunks)
a0091a40 10534 }
9f59e99b
IC
10535
10536 // match types
10537 if (p2pkh.input.check(scriptSigChunks) &&
10538 p2pkh.output.check(redeemScriptChunks)) return true
10539
10540 if (p2ms.input.check(scriptSigChunks, allowIncomplete) &&
10541 p2ms.output.check(redeemScriptChunks)) return true
10542
10543 if (p2pk.input.check(scriptSigChunks) &&
10544 p2pk.output.check(redeemScriptChunks)) return true
10545
10546 return false
a0091a40
IC
10547}
10548check.toJSON = function () { return 'scriptHash input' }
10549
10550function encodeStack (redeemScriptStack, redeemScript) {
10551 var serializedScriptPubKey = bscript.compile(redeemScript)
10552
10553 return [].concat(redeemScriptStack, serializedScriptPubKey)
10554}
10555
10556function encode (redeemScriptSig, redeemScript) {
10557 var redeemScriptStack = bscript.decompile(redeemScriptSig)
10558
10559 return bscript.compile(encodeStack(redeemScriptStack, redeemScript))
10560}
10561
10562function decodeStack (stack) {
b777ff55 10563 typeforce(typeforce.Array, stack)
a0091a40
IC
10564 typeforce(check, stack)
10565
10566 return {
10567 redeemScriptStack: stack.slice(0, -1),
10568 redeemScript: stack[stack.length - 1]
10569 }
10570}
10571
10572function decode (buffer) {
10573 var stack = bscript.decompile(buffer)
10574 var result = decodeStack(stack)
10575 result.redeemScriptSig = bscript.compile(result.redeemScriptStack)
10576 delete result.redeemScriptStack
10577 return result
10578}
10579
10580module.exports = {
10581 check: check,
10582 decode: decode,
10583 decodeStack: decodeStack,
10584 encode: encode,
10585 encodeStack: encodeStack
10586}
10587
b777ff55 10588},{"../../script":54,"../multisig/":57,"../pubkey/":61,"../pubkeyhash/":64,"../witnesspubkeyhash/output":74,"../witnessscripthash/output":77,"safe-buffer":101,"typeforce":112}],69:[function(require,module,exports){
a0091a40
IC
10589// OP_HASH160 {scriptHash} OP_EQUAL
10590
10591var bscript = require('../../script')
10592var types = require('../../types')
10593var typeforce = require('typeforce')
10594var OPS = require('bitcoin-ops')
10595
10596function check (script) {
10597 var buffer = bscript.compile(script)
10598
10599 return buffer.length === 23 &&
10600 buffer[0] === OPS.OP_HASH160 &&
10601 buffer[1] === 0x14 &&
10602 buffer[22] === OPS.OP_EQUAL
10603}
10604check.toJSON = function () { return 'scriptHash output' }
10605
10606function encode (scriptHash) {
10607 typeforce(types.Hash160bit, scriptHash)
10608
10609 return bscript.compile([OPS.OP_HASH160, scriptHash, OPS.OP_EQUAL])
10610}
10611
10612function decode (buffer) {
10613 typeforce(check, buffer)
10614
10615 return buffer.slice(2, 22)
10616}
10617
10618module.exports = {
10619 check: check,
10620 decode: decode,
10621 encode: encode
10622}
10623
b777ff55 10624},{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],70:[function(require,module,exports){
a0091a40
IC
10625module.exports = {
10626 output: require('./output')
10627}
10628
9f59e99b 10629},{"./output":71}],71:[function(require,module,exports){
a0091a40
IC
10630// OP_RETURN {aa21a9ed} {commitment}
10631
10632var Buffer = require('safe-buffer').Buffer
10633var bscript = require('../../script')
10634var types = require('../../types')
10635var typeforce = require('typeforce')
10636var OPS = require('bitcoin-ops')
10637
10638var HEADER = Buffer.from('aa21a9ed', 'hex')
10639
10640function check (script) {
10641 var buffer = bscript.compile(script)
10642
10643 return buffer.length > 37 &&
10644 buffer[0] === OPS.OP_RETURN &&
10645 buffer[1] === 0x24 &&
10646 buffer.slice(2, 6).equals(HEADER)
10647}
10648
10649check.toJSON = function () { return 'Witness commitment output' }
10650
10651function encode (commitment) {
10652 typeforce(types.Hash256bit, commitment)
10653
10654 var buffer = Buffer.allocUnsafe(36)
10655 HEADER.copy(buffer, 0)
10656 commitment.copy(buffer, 4)
10657
10658 return bscript.compile([OPS.OP_RETURN, buffer])
10659}
10660
10661function decode (buffer) {
10662 typeforce(check, buffer)
10663
10664 return bscript.decompile(buffer)[1].slice(4, 36)
10665}
10666
10667module.exports = {
10668 check: check,
10669 decode: decode,
10670 encode: encode
10671}
10672
b777ff55 10673},{"../../script":54,"../../types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],72:[function(require,module,exports){
9f59e99b
IC
10674arguments[4][57][0].apply(exports,arguments)
10675},{"./input":73,"./output":74,"dup":57}],73:[function(require,module,exports){
a0091a40
IC
10676// {signature} {pubKey}
10677
9f59e99b
IC
10678var bscript = require('../../script')
10679var typeforce = require('typeforce')
10680
10681function isCompressedCanonicalPubKey (pubKey) {
10682 return bscript.isCanonicalPubKey(pubKey) && pubKey.length === 33
10683}
10684
10685function check (script) {
10686 var chunks = bscript.decompile(script)
10687
10688 return chunks.length === 2 &&
10689 bscript.isCanonicalSignature(chunks[0]) &&
10690 isCompressedCanonicalPubKey(chunks[1])
10691}
10692check.toJSON = function () { return 'witnessPubKeyHash input' }
10693
10694function encodeStack (signature, pubKey) {
10695 typeforce({
10696 signature: bscript.isCanonicalSignature,
10697 pubKey: isCompressedCanonicalPubKey
10698 }, {
10699 signature: signature,
10700 pubKey: pubKey
10701 })
10702
10703 return [signature, pubKey]
10704}
10705
10706function decodeStack (stack) {
b777ff55 10707 typeforce(typeforce.Array, stack)
9f59e99b
IC
10708 typeforce(check, stack)
10709
10710 return {
10711 signature: stack[0],
10712 pubKey: stack[1]
10713 }
10714}
a0091a40
IC
10715
10716module.exports = {
9f59e99b
IC
10717 check: check,
10718 decodeStack: decodeStack,
10719 encodeStack: encodeStack
a0091a40
IC
10720}
10721
b777ff55 10722},{"../../script":54,"typeforce":112}],74:[function(require,module,exports){
a0091a40
IC
10723// OP_0 {pubKeyHash}
10724
10725var bscript = require('../../script')
10726var types = require('../../types')
10727var typeforce = require('typeforce')
10728var OPS = require('bitcoin-ops')
10729
10730function check (script) {
10731 var buffer = bscript.compile(script)
10732
10733 return buffer.length === 22 &&
10734 buffer[0] === OPS.OP_0 &&
10735 buffer[1] === 0x14
10736}
10737check.toJSON = function () { return 'Witness pubKeyHash output' }
10738
10739function encode (pubKeyHash) {
10740 typeforce(types.Hash160bit, pubKeyHash)
10741
10742 return bscript.compile([OPS.OP_0, pubKeyHash])
10743}
10744
10745function decode (buffer) {
10746 typeforce(check, buffer)
10747
10748 return buffer.slice(2)
10749}
10750
10751module.exports = {
10752 check: check,
10753 decode: decode,
10754 encode: encode
10755}
10756
b777ff55 10757},{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],75:[function(require,module,exports){
9f59e99b
IC
10758arguments[4][57][0].apply(exports,arguments)
10759},{"./input":76,"./output":77,"dup":57}],76:[function(require,module,exports){
10760(function (Buffer){
10761// <scriptSig> {serialized scriptPubKey script}
10762
10763var bscript = require('../../script')
10764var types = require('../../types')
10765var typeforce = require('typeforce')
10766
10767var p2ms = require('../multisig/')
10768var p2pk = require('../pubkey/')
10769var p2pkh = require('../pubkeyhash/')
10770
10771function check (chunks, allowIncomplete) {
10772 typeforce(types.Array, chunks)
10773 if (chunks.length < 1) return false
10774
10775 var witnessScript = chunks[chunks.length - 1]
10776 if (!Buffer.isBuffer(witnessScript)) return false
10777
10778 var witnessScriptChunks = bscript.decompile(witnessScript)
10779
10780 // is witnessScript a valid script?
10781 if (witnessScriptChunks.length === 0) return false
10782
10783 var witnessRawScriptSig = bscript.compile(chunks.slice(0, -1))
10784
10785 // match types
10786 if (p2pkh.input.check(witnessRawScriptSig) &&
10787 p2pkh.output.check(witnessScriptChunks)) return true
10788
10789 if (p2ms.input.check(witnessRawScriptSig, allowIncomplete) &&
10790 p2ms.output.check(witnessScriptChunks)) return true
10791
10792 if (p2pk.input.check(witnessRawScriptSig) &&
10793 p2pk.output.check(witnessScriptChunks)) return true
10794
10795 return false
10796}
10797check.toJSON = function () { return 'witnessScriptHash input' }
10798
10799function encodeStack (witnessData, witnessScript) {
10800 typeforce({
10801 witnessData: [types.Buffer],
10802 witnessScript: types.Buffer
10803 }, {
10804 witnessData: witnessData,
10805 witnessScript: witnessScript
10806 })
10807
10808 return [].concat(witnessData, witnessScript)
10809}
a0091a40 10810
b777ff55
IC
10811function decodeStack (stack) {
10812 typeforce(typeforce.Array, stack)
10813 typeforce(check, stack)
9f59e99b 10814 return {
b777ff55
IC
10815 witnessData: stack.slice(0, -1),
10816 witnessScript: stack[stack.length - 1]
9f59e99b
IC
10817 }
10818}
a0091a40
IC
10819
10820module.exports = {
9f59e99b
IC
10821 check: check,
10822 decodeStack: decodeStack,
10823 encodeStack: encodeStack
a0091a40
IC
10824}
10825
9f59e99b 10826}).call(this,{"isBuffer":require("../../../../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
b777ff55 10827},{"../../../../../../../../.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){
a0091a40
IC
10828// OP_0 {scriptHash}
10829
10830var bscript = require('../../script')
10831var types = require('../../types')
10832var typeforce = require('typeforce')
10833var OPS = require('bitcoin-ops')
10834
10835function check (script) {
10836 var buffer = bscript.compile(script)
10837
10838 return buffer.length === 34 &&
10839 buffer[0] === OPS.OP_0 &&
10840 buffer[1] === 0x20
10841}
10842check.toJSON = function () { return 'Witness scriptHash output' }
10843
10844function encode (scriptHash) {
10845 typeforce(types.Hash256bit, scriptHash)
10846
10847 return bscript.compile([OPS.OP_0, scriptHash])
10848}
10849
10850function decode (buffer) {
10851 typeforce(check, buffer)
10852
10853 return buffer.slice(2)
10854}
10855
10856module.exports = {
10857 check: check,
10858 decode: decode,
10859 encode: encode
10860}
10861
b777ff55 10862},{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],78:[function(require,module,exports){
a0091a40
IC
10863var Buffer = require('safe-buffer').Buffer
10864var bcrypto = require('./crypto')
10865var bscript = require('./script')
10866var bufferutils = require('./bufferutils')
10867var opcodes = require('bitcoin-ops')
10868var typeforce = require('typeforce')
10869var types = require('./types')
10870var varuint = require('varuint-bitcoin')
10871
10872function varSliceSize (someScript) {
10873 var length = someScript.length
10874
10875 return varuint.encodingLength(length) + length
10876}
10877
10878function vectorSize (someVector) {
10879 var length = someVector.length
10880
10881 return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) {
10882 return sum + varSliceSize(witness)
10883 }, 0)
10884}
10885
10886function Transaction () {
10887 this.version = 1
10888 this.locktime = 0
10889 this.ins = []
10890 this.outs = []
10891}
10892
10893Transaction.DEFAULT_SEQUENCE = 0xffffffff
10894Transaction.SIGHASH_ALL = 0x01
10895Transaction.SIGHASH_NONE = 0x02
10896Transaction.SIGHASH_SINGLE = 0x03
10897Transaction.SIGHASH_ANYONECANPAY = 0x80
10898Transaction.ADVANCED_TRANSACTION_MARKER = 0x00
10899Transaction.ADVANCED_TRANSACTION_FLAG = 0x01
10900
10901var EMPTY_SCRIPT = Buffer.allocUnsafe(0)
10902var EMPTY_WITNESS = []
10903var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
10904var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
10905var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex')
10906var BLANK_OUTPUT = {
10907 script: EMPTY_SCRIPT,
10908 valueBuffer: VALUE_UINT64_MAX
10909}
10910
10911Transaction.fromBuffer = function (buffer, __noStrict) {
10912 var offset = 0
10913 function readSlice (n) {
10914 offset += n
10915 return buffer.slice(offset - n, offset)
10916 }
10917
10918 function readUInt32 () {
10919 var i = buffer.readUInt32LE(offset)
10920 offset += 4
10921 return i
10922 }
10923
10924 function readInt32 () {
10925 var i = buffer.readInt32LE(offset)
10926 offset += 4
10927 return i
10928 }
10929
10930 function readUInt64 () {
10931 var i = bufferutils.readUInt64LE(buffer, offset)
10932 offset += 8
10933 return i
10934 }
10935
10936 function readVarInt () {
10937 var vi = varuint.decode(buffer, offset)
10938 offset += varuint.decode.bytes
10939 return vi
10940 }
10941
10942 function readVarSlice () {
10943 return readSlice(readVarInt())
10944 }
10945
10946 function readVector () {
10947 var count = readVarInt()
10948 var vector = []
10949 for (var i = 0; i < count; i++) vector.push(readVarSlice())
10950 return vector
10951 }
10952
10953 var tx = new Transaction()
10954 tx.version = readInt32()
10955
10956 var marker = buffer.readUInt8(offset)
10957 var flag = buffer.readUInt8(offset + 1)
10958
10959 var hasWitnesses = false
10960 if (marker === Transaction.ADVANCED_TRANSACTION_MARKER &&
10961 flag === Transaction.ADVANCED_TRANSACTION_FLAG) {
10962 offset += 2
10963 hasWitnesses = true
10964 }
10965
10966 var vinLen = readVarInt()
10967 for (var i = 0; i < vinLen; ++i) {
10968 tx.ins.push({
10969 hash: readSlice(32),
10970 index: readUInt32(),
10971 script: readVarSlice(),
10972 sequence: readUInt32(),
10973 witness: EMPTY_WITNESS
10974 })
10975 }
10976
10977 var voutLen = readVarInt()
10978 for (i = 0; i < voutLen; ++i) {
10979 tx.outs.push({
10980 value: readUInt64(),
10981 script: readVarSlice()
10982 })
10983 }
10984
10985 if (hasWitnesses) {
10986 for (i = 0; i < vinLen; ++i) {
10987 tx.ins[i].witness = readVector()
10988 }
10989
10990 // was this pointless?
10991 if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
10992 }
10993
10994 tx.locktime = readUInt32()
10995
10996 if (__noStrict) return tx
10997 if (offset !== buffer.length) throw new Error('Transaction has unexpected data')
10998
10999 return tx
11000}
11001
11002Transaction.fromHex = function (hex) {
11003 return Transaction.fromBuffer(Buffer.from(hex, 'hex'))
11004}
11005
11006Transaction.isCoinbaseHash = function (buffer) {
11007 typeforce(types.Hash256bit, buffer)
11008 for (var i = 0; i < 32; ++i) {
11009 if (buffer[i] !== 0) return false
11010 }
11011 return true
11012}
11013
11014Transaction.prototype.isCoinbase = function () {
11015 return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash)
11016}
11017
11018Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) {
11019 typeforce(types.tuple(
11020 types.Hash256bit,
11021 types.UInt32,
11022 types.maybe(types.UInt32),
11023 types.maybe(types.Buffer)
11024 ), arguments)
11025
11026 if (types.Null(sequence)) {
11027 sequence = Transaction.DEFAULT_SEQUENCE
11028 }
11029
11030 // Add the input and return the input's index
11031 return (this.ins.push({
11032 hash: hash,
11033 index: index,
11034 script: scriptSig || EMPTY_SCRIPT,
11035 sequence: sequence,
11036 witness: EMPTY_WITNESS
11037 }) - 1)
11038}
11039
11040Transaction.prototype.addOutput = function (scriptPubKey, value) {
11041 typeforce(types.tuple(types.Buffer, types.Satoshi), arguments)
11042
11043 // Add the output and return the output's index
11044 return (this.outs.push({
11045 script: scriptPubKey,
11046 value: value
11047 }) - 1)
11048}
11049
11050Transaction.prototype.hasWitnesses = function () {
11051 return this.ins.some(function (x) {
11052 return x.witness.length !== 0
11053 })
11054}
11055
11056Transaction.prototype.weight = function () {
11057 var base = this.__byteLength(false)
11058 var total = this.__byteLength(true)
11059 return base * 3 + total
11060}
11061
11062Transaction.prototype.virtualSize = function () {
11063 return Math.ceil(this.weight() / 4)
11064}
11065
11066Transaction.prototype.byteLength = function () {
11067 return this.__byteLength(true)
11068}
11069
11070Transaction.prototype.__byteLength = function (__allowWitness) {
11071 var hasWitnesses = __allowWitness && this.hasWitnesses()
11072
11073 return (
11074 (hasWitnesses ? 10 : 8) +
11075 varuint.encodingLength(this.ins.length) +
11076 varuint.encodingLength(this.outs.length) +
11077 this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) +
11078 this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) +
11079 (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0)
11080 )
11081}
11082
11083Transaction.prototype.clone = function () {
11084 var newTx = new Transaction()
11085 newTx.version = this.version
11086 newTx.locktime = this.locktime
11087
11088 newTx.ins = this.ins.map(function (txIn) {
11089 return {
11090 hash: txIn.hash,
11091 index: txIn.index,
11092 script: txIn.script,
11093 sequence: txIn.sequence,
11094 witness: txIn.witness
11095 }
11096 })
11097
11098 newTx.outs = this.outs.map(function (txOut) {
11099 return {
11100 script: txOut.script,
11101 value: txOut.value
11102 }
11103 })
11104
11105 return newTx
11106}
11107
11108/**
11109 * Hash transaction for signing a specific input.
11110 *
11111 * Bitcoin uses a different hash for each signed transaction input.
11112 * This method copies the transaction, makes the necessary changes based on the
11113 * hashType, and then hashes the result.
11114 * This hash can then be used to sign the provided transaction input.
11115 */
11116Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) {
11117 typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments)
11118
11119 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
11120 if (inIndex >= this.ins.length) return ONE
11121
11122 // ignore OP_CODESEPARATOR
11123 var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) {
11124 return x !== opcodes.OP_CODESEPARATOR
11125 }))
11126
11127 var txTmp = this.clone()
11128
11129 // SIGHASH_NONE: ignore all outputs? (wildcard payee)
11130 if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) {
11131 txTmp.outs = []
11132
11133 // ignore sequence numbers (except at inIndex)
11134 txTmp.ins.forEach(function (input, i) {
11135 if (i === inIndex) return
11136
11137 input.sequence = 0
11138 })
11139
11140 // SIGHASH_SINGLE: ignore all outputs, except at the same index?
11141 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) {
11142 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
11143 if (inIndex >= this.outs.length) return ONE
11144
11145 // truncate outputs after
11146 txTmp.outs.length = inIndex + 1
11147
11148 // "blank" outputs before
11149 for (var i = 0; i < inIndex; i++) {
11150 txTmp.outs[i] = BLANK_OUTPUT
11151 }
11152
11153 // ignore sequence numbers (except at inIndex)
11154 txTmp.ins.forEach(function (input, y) {
11155 if (y === inIndex) return
11156
11157 input.sequence = 0
11158 })
11159 }
11160
11161 // SIGHASH_ANYONECANPAY: ignore inputs entirely?
11162 if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
11163 txTmp.ins = [txTmp.ins[inIndex]]
11164 txTmp.ins[0].script = ourScript
11165
11166 // SIGHASH_ALL: only ignore input scripts
11167 } else {
11168 // "blank" others input scripts
11169 txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT })
11170 txTmp.ins[inIndex].script = ourScript
11171 }
11172
11173 // serialize and hash
11174 var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4)
11175 buffer.writeInt32LE(hashType, buffer.length - 4)
11176 txTmp.__toBuffer(buffer, 0, false)
11177
11178 return bcrypto.hash256(buffer)
11179}
11180
11181Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) {
11182 typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments)
11183
11184 var tbuffer, toffset
11185 function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) }
11186 function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) }
11187 function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) }
11188 function writeVarInt (i) {
11189 varuint.encode(i, tbuffer, toffset)
11190 toffset += varuint.encode.bytes
11191 }
11192 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
11193
11194 var hashOutputs = ZERO
11195 var hashPrevouts = ZERO
11196 var hashSequence = ZERO
11197
11198 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) {
11199 tbuffer = Buffer.allocUnsafe(36 * this.ins.length)
11200 toffset = 0
11201
11202 this.ins.forEach(function (txIn) {
11203 writeSlice(txIn.hash)
11204 writeUInt32(txIn.index)
11205 })
11206
11207 hashPrevouts = bcrypto.hash256(tbuffer)
11208 }
11209
11210 if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) &&
11211 (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
11212 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
11213 tbuffer = Buffer.allocUnsafe(4 * this.ins.length)
11214 toffset = 0
11215
11216 this.ins.forEach(function (txIn) {
11217 writeUInt32(txIn.sequence)
11218 })
11219
11220 hashSequence = bcrypto.hash256(tbuffer)
11221 }
11222
11223 if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE &&
11224 (hashType & 0x1f) !== Transaction.SIGHASH_NONE) {
11225 var txOutsSize = this.outs.reduce(function (sum, output) {
11226 return sum + 8 + varSliceSize(output.script)
11227 }, 0)
11228
11229 tbuffer = Buffer.allocUnsafe(txOutsSize)
11230 toffset = 0
11231
11232 this.outs.forEach(function (out) {
11233 writeUInt64(out.value)
11234 writeVarSlice(out.script)
11235 })
11236
11237 hashOutputs = bcrypto.hash256(tbuffer)
11238 } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) {
11239 var output = this.outs[inIndex]
11240
11241 tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script))
11242 toffset = 0
11243 writeUInt64(output.value)
11244 writeVarSlice(output.script)
11245
11246 hashOutputs = bcrypto.hash256(tbuffer)
11247 }
11248
11249 tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript))
11250 toffset = 0
11251
11252 var input = this.ins[inIndex]
11253 writeUInt32(this.version)
11254 writeSlice(hashPrevouts)
11255 writeSlice(hashSequence)
11256 writeSlice(input.hash)
11257 writeUInt32(input.index)
11258 writeVarSlice(prevOutScript)
11259 writeUInt64(value)
11260 writeUInt32(input.sequence)
11261 writeSlice(hashOutputs)
11262 writeUInt32(this.locktime)
11263 writeUInt32(hashType)
11264 return bcrypto.hash256(tbuffer)
11265}
11266
11267Transaction.prototype.getHash = function () {
11268 return bcrypto.hash256(this.__toBuffer(undefined, undefined, false))
11269}
11270
11271Transaction.prototype.getId = function () {
11272 // transaction hash's are displayed in reverse order
11273 return this.getHash().reverse().toString('hex')
11274}
11275
11276Transaction.prototype.toBuffer = function (buffer, initialOffset) {
11277 return this.__toBuffer(buffer, initialOffset, true)
11278}
11279
11280Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) {
11281 if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness))
11282
11283 var offset = initialOffset || 0
11284 function writeSlice (slice) { offset += slice.copy(buffer, offset) }
11285 function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) }
11286 function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) }
11287 function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) }
11288 function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) }
11289 function writeVarInt (i) {
11290 varuint.encode(i, buffer, offset)
11291 offset += varuint.encode.bytes
11292 }
11293 function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) }
11294 function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) }
11295
11296 writeInt32(this.version)
11297
11298 var hasWitnesses = __allowWitness && this.hasWitnesses()
11299
11300 if (hasWitnesses) {
11301 writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER)
11302 writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG)
11303 }
11304
11305 writeVarInt(this.ins.length)
11306
11307 this.ins.forEach(function (txIn) {
11308 writeSlice(txIn.hash)
11309 writeUInt32(txIn.index)
11310 writeVarSlice(txIn.script)
11311 writeUInt32(txIn.sequence)
11312 })
11313
11314 writeVarInt(this.outs.length)
11315 this.outs.forEach(function (txOut) {
11316 if (!txOut.valueBuffer) {
11317 writeUInt64(txOut.value)
11318 } else {
11319 writeSlice(txOut.valueBuffer)
11320 }
11321
11322 writeVarSlice(txOut.script)
11323 })
11324
11325 if (hasWitnesses) {
11326 this.ins.forEach(function (input) {
11327 writeVector(input.witness)
11328 })
11329 }
11330
11331 writeUInt32(this.locktime)
11332
11333 // avoid slicing unless necessary
11334 if (initialOffset !== undefined) return buffer.slice(initialOffset, offset)
11335 return buffer
11336}
11337
11338Transaction.prototype.toHex = function () {
11339 return this.toBuffer().toString('hex')
11340}
11341
11342Transaction.prototype.setInputScript = function (index, scriptSig) {
11343 typeforce(types.tuple(types.Number, types.Buffer), arguments)
11344
11345 this.ins[index].script = scriptSig
11346}
11347
11348Transaction.prototype.setWitness = function (index, witness) {
11349 typeforce(types.tuple(types.Number, [types.Buffer]), arguments)
11350
11351 this.ins[index].witness = witness
11352}
11353
11354module.exports = Transaction
11355
b777ff55 11356},{"./bufferutils":46,"./crypto":47,"./script":54,"./types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112,"varuint-bitcoin":114}],79:[function(require,module,exports){
a0091a40
IC
11357var Buffer = require('safe-buffer').Buffer
11358var baddress = require('./address')
11359var bcrypto = require('./crypto')
11360var bscript = require('./script')
9f59e99b 11361var btemplates = require('./templates')
a0091a40
IC
11362var networks = require('./networks')
11363var ops = require('bitcoin-ops')
11364var typeforce = require('typeforce')
11365var types = require('./types')
9f59e99b
IC
11366var scriptTypes = btemplates.types
11367var SIGNABLE = [btemplates.types.P2PKH, btemplates.types.P2PK, btemplates.types.MULTISIG]
11368var P2SH = SIGNABLE.concat([btemplates.types.P2WPKH, btemplates.types.P2WSH])
a0091a40
IC
11369
11370var ECPair = require('./ecpair')
11371var ECSignature = require('./ecsignature')
11372var Transaction = require('./transaction')
11373
9f59e99b
IC
11374function supportedType (type) {
11375 return SIGNABLE.indexOf(type) !== -1
11376}
11377
11378function supportedP2SHType (type) {
11379 return P2SH.indexOf(type) !== -1
11380}
11381
a0091a40
IC
11382function extractChunks (type, chunks, script) {
11383 var pubKeys = []
11384 var signatures = []
11385 switch (type) {
11386 case scriptTypes.P2PKH:
11387 // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')
11388 pubKeys = chunks.slice(1)
11389 signatures = chunks.slice(0, 1)
11390 break
11391
11392 case scriptTypes.P2PK:
9f59e99b 11393 pubKeys[0] = script ? btemplates.pubKey.output.decode(script) : undefined
a0091a40
IC
11394 signatures = chunks.slice(0, 1)
11395 break
11396
11397 case scriptTypes.MULTISIG:
11398 if (script) {
9f59e99b 11399 var multisig = btemplates.multisig.output.decode(script)
a0091a40
IC
11400 pubKeys = multisig.pubKeys
11401 }
11402
11403 signatures = chunks.slice(1).map(function (chunk) {
11404 return chunk.length === 0 ? undefined : chunk
11405 })
11406 break
11407 }
11408
11409 return {
11410 pubKeys: pubKeys,
11411 signatures: signatures
11412 }
11413}
11414function expandInput (scriptSig, witnessStack) {
11415 if (scriptSig.length === 0 && witnessStack.length === 0) return {}
11416
11417 var prevOutScript
11418 var prevOutType
11419 var scriptType
11420 var script
11421 var redeemScript
11422 var witnessScript
11423 var witnessScriptType
11424 var redeemScriptType
11425 var witness = false
11426 var p2wsh = false
11427 var p2sh = false
11428 var witnessProgram
11429 var chunks
11430
11431 var scriptSigChunks = bscript.decompile(scriptSig)
9f59e99b 11432 var sigType = btemplates.classifyInput(scriptSigChunks, true)
a0091a40
IC
11433 if (sigType === scriptTypes.P2SH) {
11434 p2sh = true
11435 redeemScript = scriptSigChunks[scriptSigChunks.length - 1]
9f59e99b
IC
11436 redeemScriptType = btemplates.classifyOutput(redeemScript)
11437 prevOutScript = btemplates.scriptHash.output.encode(bcrypto.hash160(redeemScript))
a0091a40
IC
11438 prevOutType = scriptTypes.P2SH
11439 script = redeemScript
11440 }
11441
9f59e99b 11442 var classifyWitness = btemplates.classifyWitness(witnessStack, true)
a0091a40
IC
11443 if (classifyWitness === scriptTypes.P2WSH) {
11444 witnessScript = witnessStack[witnessStack.length - 1]
9f59e99b 11445 witnessScriptType = btemplates.classifyOutput(witnessScript)
a0091a40 11446 p2wsh = true
9f59e99b 11447 witness = true
a0091a40 11448 if (scriptSig.length === 0) {
9f59e99b 11449 prevOutScript = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
a0091a40 11450 prevOutType = scriptTypes.P2WSH
9f59e99b 11451 if (redeemScript !== undefined) {
a0091a40
IC
11452 throw new Error('Redeem script given when unnecessary')
11453 }
11454 // bare witness
11455 } else {
11456 if (!redeemScript) {
11457 throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty')
11458 }
9f59e99b 11459 witnessProgram = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript))
a0091a40
IC
11460 if (!redeemScript.equals(witnessProgram)) {
11461 throw new Error('Redeem script didn\'t match witnessScript')
11462 }
11463 }
11464
9f59e99b 11465 if (!supportedType(btemplates.classifyOutput(witnessScript))) {
a0091a40
IC
11466 throw new Error('unsupported witness script')
11467 }
9f59e99b 11468
a0091a40
IC
11469 script = witnessScript
11470 scriptType = witnessScriptType
11471 chunks = witnessStack.slice(0, -1)
11472 } else if (classifyWitness === scriptTypes.P2WPKH) {
9f59e99b 11473 witness = true
a0091a40
IC
11474 var key = witnessStack[witnessStack.length - 1]
11475 var keyHash = bcrypto.hash160(key)
11476 if (scriptSig.length === 0) {
9f59e99b 11477 prevOutScript = btemplates.witnessPubKeyHash.output.encode(keyHash)
a0091a40
IC
11478 prevOutType = scriptTypes.P2WPKH
11479 if (typeof redeemScript !== 'undefined') {
11480 throw new Error('Redeem script given when unnecessary')
11481 }
11482 } else {
11483 if (!redeemScript) {
11484 throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty')
11485 }
9f59e99b 11486 witnessProgram = btemplates.witnessPubKeyHash.output.encode(keyHash)
a0091a40
IC
11487 if (!redeemScript.equals(witnessProgram)) {
11488 throw new Error('Redeem script did not have the right witness program')
11489 }
11490 }
11491
11492 scriptType = scriptTypes.P2PKH
11493 chunks = witnessStack
11494 } else if (redeemScript) {
9f59e99b 11495 if (!supportedP2SHType(redeemScriptType)) {
a0091a40
IC
11496 throw new Error('Bad redeemscript!')
11497 }
11498
11499 script = redeemScript
11500 scriptType = redeemScriptType
11501 chunks = scriptSigChunks.slice(0, -1)
11502 } else {
9f59e99b 11503 prevOutType = scriptType = btemplates.classifyInput(scriptSig)
a0091a40
IC
11504 chunks = scriptSigChunks
11505 }
11506
11507 var expanded = extractChunks(scriptType, chunks, script)
11508
11509 var result = {
11510 pubKeys: expanded.pubKeys,
11511 signatures: expanded.signatures,
11512 prevOutScript: prevOutScript,
11513 prevOutType: prevOutType,
11514 signType: scriptType,
11515 signScript: script,
11516 witness: Boolean(witness)
11517 }
11518
11519 if (p2sh) {
11520 result.redeemScript = redeemScript
11521 result.redeemScriptType = redeemScriptType
11522 }
11523
11524 if (p2wsh) {
11525 result.witnessScript = witnessScript
11526 result.witnessScriptType = witnessScriptType
11527 }
11528
11529 return result
11530}
11531
11532// could be done in expandInput, but requires the original Transaction for hashForSignature
11533function fixMultisigOrder (input, transaction, vin) {
11534 if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return
11535 if (input.pubKeys.length === input.signatures.length) return
11536
11537 var unmatched = input.signatures.concat()
11538
11539 input.signatures = input.pubKeys.map(function (pubKey) {
11540 var keyPair = ECPair.fromPublicKeyBuffer(pubKey)
11541 var match
11542
11543 // check for a signature
11544 unmatched.some(function (signature, i) {
11545 // skip if undefined || OP_0
11546 if (!signature) return false
11547
11548 // TODO: avoid O(n) hashForSignature
11549 var parsed = ECSignature.parseScriptSignature(signature)
11550 var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType)
11551
11552 // skip if signature does not match pubKey
11553 if (!keyPair.verify(hash, parsed.signature)) return false
11554
11555 // remove matched signature from unmatched
11556 unmatched[i] = undefined
11557 match = signature
11558
11559 return true
11560 })
11561
11562 return match
11563 })
11564}
11565
11566function expandOutput (script, scriptType, ourPubKey) {
11567 typeforce(types.Buffer, script)
11568
11569 var scriptChunks = bscript.decompile(script)
11570 if (!scriptType) {
9f59e99b 11571 scriptType = btemplates.classifyOutput(script)
a0091a40
IC
11572 }
11573
11574 var pubKeys = []
11575
11576 switch (scriptType) {
11577 // does our hash160(pubKey) match the output scripts?
11578 case scriptTypes.P2PKH:
11579 if (!ourPubKey) break
11580
11581 var pkh1 = scriptChunks[2]
11582 var pkh2 = bcrypto.hash160(ourPubKey)
11583 if (pkh1.equals(pkh2)) pubKeys = [ourPubKey]
11584 break
11585
11586 // does our hash160(pubKey) match the output scripts?
11587 case scriptTypes.P2WPKH:
11588 if (!ourPubKey) break
11589
11590 var wpkh1 = scriptChunks[1]
11591 var wpkh2 = bcrypto.hash160(ourPubKey)
11592 if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey]
11593 break
11594
11595 case scriptTypes.P2PK:
11596 pubKeys = scriptChunks.slice(0, 1)
11597 break
11598
11599 case scriptTypes.MULTISIG:
11600 pubKeys = scriptChunks.slice(1, -2)
11601 break
11602
11603 default: return { scriptType: scriptType }
11604 }
11605
11606 return {
11607 pubKeys: pubKeys,
11608 scriptType: scriptType,
11609 signatures: pubKeys.map(function () { return undefined })
11610 }
11611}
11612
9f59e99b 11613function checkP2SHInput (input, redeemScriptHash) {
a0091a40
IC
11614 if (input.prevOutType) {
11615 if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH')
11616
11617 var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1]
11618 if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)')
11619 }
11620}
11621
11622function checkP2WSHInput (input, witnessScriptHash) {
11623 if (input.prevOutType) {
11624 if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH')
11625
11626 var scriptHash = bscript.decompile(input.prevOutScript)[1]
11627 if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)')
11628 }
11629}
11630
11631function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) {
11632 var expanded
11633 var prevOutType
11634 var prevOutScript
11635
11636 var p2sh = false
11637 var p2shType
11638 var redeemScriptHash
11639
11640 var witness = false
11641 var p2wsh = false
11642 var witnessType
11643 var witnessScriptHash
11644
11645 var signType
11646 var signScript
11647
11648 if (redeemScript && witnessScript) {
11649 redeemScriptHash = bcrypto.hash160(redeemScript)
11650 witnessScriptHash = bcrypto.sha256(witnessScript)
9f59e99b 11651 checkP2SHInput(input, redeemScriptHash)
a0091a40 11652
9f59e99b 11653 if (!redeemScript.equals(btemplates.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script')
a0091a40
IC
11654
11655 expanded = expandOutput(witnessScript, undefined, kpPubKey)
11656 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
9f59e99b
IC
11657
11658 prevOutType = btemplates.types.P2SH
11659 prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash)
a0091a40 11660 p2sh = witness = p2wsh = true
9f59e99b 11661 p2shType = btemplates.types.P2WSH
a0091a40
IC
11662 signType = witnessType = expanded.scriptType
11663 signScript = witnessScript
11664 } else if (redeemScript) {
11665 redeemScriptHash = bcrypto.hash160(redeemScript)
9f59e99b 11666 checkP2SHInput(input, redeemScriptHash)
a0091a40
IC
11667
11668 expanded = expandOutput(redeemScript, undefined, kpPubKey)
11669 if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"')
11670
9f59e99b
IC
11671 prevOutType = btemplates.types.P2SH
11672 prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash)
a0091a40
IC
11673 p2sh = true
11674 signType = p2shType = expanded.scriptType
11675 signScript = redeemScript
9f59e99b 11676 witness = signType === btemplates.types.P2WPKH
a0091a40
IC
11677 } else if (witnessScript) {
11678 witnessScriptHash = bcrypto.sha256(witnessScript)
11679 checkP2WSHInput(input, witnessScriptHash)
11680
11681 expanded = expandOutput(witnessScript, undefined, kpPubKey)
11682 if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"')
11683
9f59e99b
IC
11684 prevOutType = btemplates.types.P2WSH
11685 prevOutScript = btemplates.witnessScriptHash.output.encode(witnessScriptHash)
a0091a40
IC
11686 witness = p2wsh = true
11687 signType = witnessType = expanded.scriptType
11688 signScript = witnessScript
11689 } else if (input.prevOutType) {
11690 // embedded scripts are not possible without a redeemScript
11691 if (input.prevOutType === scriptTypes.P2SH ||
11692 input.prevOutType === scriptTypes.P2WSH) {
11693 throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript')
11694 }
11695
11696 prevOutType = input.prevOutType
11697 prevOutScript = input.prevOutScript
11698 expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey)
11699 if (!expanded.pubKeys) return
11700
11701 witness = (input.prevOutType === scriptTypes.P2WPKH)
11702 signType = prevOutType
11703 signScript = prevOutScript
11704 } else {
9f59e99b 11705 prevOutScript = btemplates.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey))
a0091a40 11706 expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey)
9f59e99b 11707
a0091a40
IC
11708 prevOutType = scriptTypes.P2PKH
11709 witness = false
11710 signType = prevOutType
11711 signScript = prevOutScript
11712 }
11713
a0091a40 11714 if (signType === scriptTypes.P2WPKH) {
9f59e99b 11715 signScript = btemplates.pubKeyHash.output.encode(btemplates.witnessPubKeyHash.output.decode(signScript))
a0091a40
IC
11716 }
11717
11718 if (p2sh) {
11719 input.redeemScript = redeemScript
11720 input.redeemScriptType = p2shType
11721 }
11722
11723 if (p2wsh) {
11724 input.witnessScript = witnessScript
11725 input.witnessScriptType = witnessType
11726 }
11727
11728 input.pubKeys = expanded.pubKeys
11729 input.signatures = expanded.signatures
11730 input.signScript = signScript
11731 input.signType = signType
11732 input.prevOutScript = prevOutScript
11733 input.prevOutType = prevOutType
11734 input.witness = witness
11735}
11736
11737function buildStack (type, signatures, pubKeys, allowIncomplete) {
11738 if (type === scriptTypes.P2PKH) {
9f59e99b 11739 if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return btemplates.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0])
a0091a40 11740 } else if (type === scriptTypes.P2PK) {
9f59e99b 11741 if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return btemplates.pubKey.input.encodeStack(signatures[0])
a0091a40
IC
11742 } else if (type === scriptTypes.MULTISIG) {
11743 if (signatures.length > 0) {
11744 signatures = signatures.map(function (signature) {
11745 return signature || ops.OP_0
11746 })
11747 if (!allowIncomplete) {
11748 // remove blank signatures
11749 signatures = signatures.filter(function (x) { return x !== ops.OP_0 })
11750 }
11751
9f59e99b 11752 return btemplates.multisig.input.encodeStack(signatures)
a0091a40
IC
11753 }
11754 } else {
11755 throw new Error('Not yet supported')
11756 }
11757
11758 if (!allowIncomplete) throw new Error('Not enough signatures provided')
a0091a40
IC
11759 return []
11760}
11761
11762function buildInput (input, allowIncomplete) {
11763 var scriptType = input.prevOutType
11764 var sig = []
11765 var witness = []
9f59e99b
IC
11766
11767 if (supportedType(scriptType)) {
a0091a40
IC
11768 sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete)
11769 }
11770
11771 var p2sh = false
9f59e99b 11772 if (scriptType === btemplates.types.P2SH) {
a0091a40
IC
11773 // We can remove this error later when we have a guarantee prepareInput
11774 // rejects unsignable scripts - it MUST be signable at this point.
9f59e99b 11775 if (!allowIncomplete && !supportedP2SHType(input.redeemScriptType)) {
a0091a40
IC
11776 throw new Error('Impossible to sign this type')
11777 }
9f59e99b
IC
11778
11779 if (supportedType(input.redeemScriptType)) {
a0091a40
IC
11780 sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete)
11781 }
9f59e99b 11782
a0091a40 11783 // If it wasn't SIGNABLE, it's witness, defer to that
9f59e99b
IC
11784 if (input.redeemScriptType) {
11785 p2sh = true
11786 scriptType = input.redeemScriptType
11787 }
a0091a40
IC
11788 }
11789
9f59e99b 11790 switch (scriptType) {
a0091a40 11791 // P2WPKH is a special case of P2PKH
9f59e99b
IC
11792 case btemplates.types.P2WPKH:
11793 witness = buildStack(btemplates.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete)
11794 break
a0091a40 11795
9f59e99b
IC
11796 case btemplates.types.P2WSH:
11797 // We can remove this check later
11798 if (!allowIncomplete && !supportedType(input.witnessScriptType)) {
11799 throw new Error('Impossible to sign this type')
11800 }
11801
11802 if (supportedType(input.witnessScriptType)) {
11803 witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete)
11804 witness.push(input.witnessScript)
11805 scriptType = input.witnessScriptType
11806 }
11807
11808 break
a0091a40
IC
11809 }
11810
11811 // append redeemScript if necessary
11812 if (p2sh) {
11813 sig.push(input.redeemScript)
11814 }
11815
11816 return {
11817 type: scriptType,
11818 script: bscript.compile(sig),
11819 witness: witness
11820 }
11821}
11822
11823function TransactionBuilder (network, maximumFeeRate) {
11824 this.prevTxMap = {}
11825 this.network = network || networks.bitcoin
11826
11827 // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
b777ff55 11828 this.maximumFeeRate = maximumFeeRate || 2500
a0091a40
IC
11829
11830 this.inputs = []
11831 this.tx = new Transaction()
11832}
11833
11834TransactionBuilder.prototype.setLockTime = function (locktime) {
11835 typeforce(types.UInt32, locktime)
11836
11837 // if any signatures exist, throw
11838 if (this.inputs.some(function (input) {
11839 if (!input.signatures) return false
11840
11841 return input.signatures.some(function (s) { return s })
11842 })) {
11843 throw new Error('No, this would invalidate signatures')
11844 }
11845
11846 this.tx.locktime = locktime
11847}
11848
11849TransactionBuilder.prototype.setVersion = function (version) {
11850 typeforce(types.UInt32, version)
11851
11852 // XXX: this might eventually become more complex depending on what the versions represent
11853 this.tx.version = version
11854}
11855
11856TransactionBuilder.fromTransaction = function (transaction, network) {
11857 var txb = new TransactionBuilder(network)
11858
11859 // Copy transaction fields
11860 txb.setVersion(transaction.version)
11861 txb.setLockTime(transaction.locktime)
11862
11863 // Copy outputs (done first to avoid signature invalidation)
11864 transaction.outs.forEach(function (txOut) {
11865 txb.addOutput(txOut.script, txOut.value)
11866 })
11867
11868 // Copy inputs
11869 transaction.ins.forEach(function (txIn) {
11870 txb.__addInputUnsafe(txIn.hash, txIn.index, {
11871 sequence: txIn.sequence,
11872 script: txIn.script,
11873 witness: txIn.witness
11874 })
11875 })
11876
11877 // fix some things not possible through the public API
11878 txb.inputs.forEach(function (input, i) {
11879 fixMultisigOrder(input, transaction, i)
11880 })
11881
11882 return txb
11883}
11884
11885TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) {
11886 if (!this.__canModifyInputs()) {
11887 throw new Error('No, this would invalidate signatures')
11888 }
11889
11890 var value
11891
11892 // is it a hex string?
11893 if (typeof txHash === 'string') {
11894 // transaction hashs's are displayed in reverse order, un-reverse it
11895 txHash = Buffer.from(txHash, 'hex').reverse()
11896
11897 // is it a Transaction object?
11898 } else if (txHash instanceof Transaction) {
11899 var txOut = txHash.outs[vout]
11900 prevOutScript = txOut.script
11901 value = txOut.value
11902
11903 txHash = txHash.getHash()
11904 }
11905
11906 return this.__addInputUnsafe(txHash, vout, {
11907 sequence: sequence,
11908 prevOutScript: prevOutScript,
11909 value: value
11910 })
11911}
11912
11913TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) {
11914 if (Transaction.isCoinbaseHash(txHash)) {
11915 throw new Error('coinbase inputs not supported')
11916 }
11917
11918 var prevTxOut = txHash.toString('hex') + ':' + vout
11919 if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut)
11920
11921 var input = {}
11922
11923 // derive what we can from the scriptSig
11924 if (options.script !== undefined) {
11925 input = expandInput(options.script, options.witness || [])
11926 }
11927
11928 // if an input value was given, retain it
11929 if (options.value !== undefined) {
11930 input.value = options.value
11931 }
11932
11933 // derive what we can from the previous transactions output script
11934 if (!input.prevOutScript && options.prevOutScript) {
11935 var prevOutType
11936
11937 if (!input.pubKeys && !input.signatures) {
11938 var expanded = expandOutput(options.prevOutScript)
11939
11940 if (expanded.pubKeys) {
11941 input.pubKeys = expanded.pubKeys
11942 input.signatures = expanded.signatures
11943 }
11944
11945 prevOutType = expanded.scriptType
11946 }
11947
11948 input.prevOutScript = options.prevOutScript
9f59e99b 11949 input.prevOutType = prevOutType || btemplates.classifyOutput(options.prevOutScript)
a0091a40
IC
11950 }
11951
11952 var vin = this.tx.addInput(txHash, vout, options.sequence, options.scriptSig)
11953 this.inputs[vin] = input
11954 this.prevTxMap[prevTxOut] = vin
a0091a40
IC
11955 return vin
11956}
11957
11958TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) {
11959 if (!this.__canModifyOutputs()) {
11960 throw new Error('No, this would invalidate signatures')
11961 }
11962
11963 // Attempt to get a script if it's a base58 address string
11964 if (typeof scriptPubKey === 'string') {
11965 scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network)
11966 }
11967
11968 return this.tx.addOutput(scriptPubKey, value)
11969}
11970
11971TransactionBuilder.prototype.build = function () {
11972 return this.__build(false)
11973}
11974TransactionBuilder.prototype.buildIncomplete = function () {
11975 return this.__build(true)
11976}
11977
11978TransactionBuilder.prototype.__build = function (allowIncomplete) {
11979 if (!allowIncomplete) {
11980 if (!this.tx.ins.length) throw new Error('Transaction has no inputs')
11981 if (!this.tx.outs.length) throw new Error('Transaction has no outputs')
11982 }
11983
11984 var tx = this.tx.clone()
11985 // Create script signatures from inputs
11986 this.inputs.forEach(function (input, i) {
11987 var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType
11988 if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete')
11989 var result = buildInput(input, allowIncomplete)
11990
11991 // skip if no result
11992 if (!allowIncomplete) {
9f59e99b 11993 if (!supportedType(result.type) && result.type !== btemplates.types.P2WPKH) {
a0091a40
IC
11994 throw new Error(result.type + ' not supported')
11995 }
11996 }
11997
11998 tx.setInputScript(i, result.script)
11999 tx.setWitness(i, result.witness)
12000 })
12001
12002 if (!allowIncomplete) {
12003 // do not rely on this, its merely a last resort
9f59e99b 12004 if (this.__overMaximumFees(tx.virtualSize())) {
a0091a40
IC
12005 throw new Error('Transaction has absurd fees')
12006 }
12007 }
12008
12009 return tx
12010}
12011
12012function canSign (input) {
12013 return input.prevOutScript !== undefined &&
12014 input.signScript !== undefined &&
12015 input.pubKeys !== undefined &&
12016 input.signatures !== undefined &&
12017 input.signatures.length === input.pubKeys.length &&
12018 input.pubKeys.length > 0 &&
9f59e99b
IC
12019 (
12020 input.witness === false ||
12021 (input.witness === true && input.value !== undefined)
12022 )
a0091a40
IC
12023}
12024
12025TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) {
9f59e99b
IC
12026 // TODO: remove keyPair.network matching in 4.0.0
12027 if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network')
a0091a40
IC
12028 if (!this.inputs[vin]) throw new Error('No input at index: ' + vin)
12029 hashType = hashType || Transaction.SIGHASH_ALL
12030
12031 var input = this.inputs[vin]
12032
12033 // if redeemScript was previously provided, enforce consistency
12034 if (input.redeemScript !== undefined &&
12035 redeemScript &&
12036 !input.redeemScript.equals(redeemScript)) {
12037 throw new Error('Inconsistent redeemScript')
12038 }
12039
9f59e99b 12040 var kpPubKey = keyPair.publicKey || keyPair.getPublicKeyBuffer()
a0091a40 12041 if (!canSign(input)) {
9f59e99b
IC
12042 if (witnessValue !== undefined) {
12043 if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input didn\'t match witnessValue')
12044 typeforce(types.Satoshi, witnessValue)
12045 input.value = witnessValue
12046 }
12047
12048 if (!canSign(input)) prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript)
a0091a40
IC
12049 if (!canSign(input)) throw Error(input.prevOutType + ' not supported')
12050 }
12051
12052 // ready to sign
12053 var signatureHash
12054 if (input.witness) {
9f59e99b 12055 signatureHash = this.tx.hashForWitnessV0(vin, input.signScript, input.value, hashType)
a0091a40
IC
12056 } else {
12057 signatureHash = this.tx.hashForSignature(vin, input.signScript, hashType)
12058 }
9f59e99b 12059
a0091a40
IC
12060 // enforce in order signing of public keys
12061 var signed = input.pubKeys.some(function (pubKey, i) {
12062 if (!kpPubKey.equals(pubKey)) return false
12063 if (input.signatures[i]) throw new Error('Signature already exists')
9f59e99b
IC
12064 if (kpPubKey.length !== 33 &&
12065 input.signType === scriptTypes.P2WPKH) throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH')
a0091a40 12066
9f59e99b
IC
12067 var signature = keyPair.sign(signatureHash)
12068 if (Buffer.isBuffer(signature)) signature = ECSignature.fromRSBuffer(signature)
12069
12070 input.signatures[i] = signature.toScriptSignature(hashType)
a0091a40
IC
12071 return true
12072 })
12073
12074 if (!signed) throw new Error('Key pair cannot sign for this input')
12075}
12076
12077function signatureHashType (buffer) {
12078 return buffer.readUInt8(buffer.length - 1)
12079}
12080
12081TransactionBuilder.prototype.__canModifyInputs = function () {
12082 return this.inputs.every(function (input) {
12083 // any signatures?
12084 if (input.signatures === undefined) return true
12085
12086 return input.signatures.every(function (signature) {
12087 if (!signature) return true
12088 var hashType = signatureHashType(signature)
12089
12090 // if SIGHASH_ANYONECANPAY is set, signatures would not
12091 // be invalidated by more inputs
12092 return hashType & Transaction.SIGHASH_ANYONECANPAY
12093 })
12094 })
12095}
12096
12097TransactionBuilder.prototype.__canModifyOutputs = function () {
12098 var nInputs = this.tx.ins.length
12099 var nOutputs = this.tx.outs.length
12100
12101 return this.inputs.every(function (input) {
12102 if (input.signatures === undefined) return true
12103
12104 return input.signatures.every(function (signature) {
12105 if (!signature) return true
12106 var hashType = signatureHashType(signature)
12107
12108 var hashTypeMod = hashType & 0x1f
12109 if (hashTypeMod === Transaction.SIGHASH_NONE) return true
12110 if (hashTypeMod === Transaction.SIGHASH_SINGLE) {
12111 // if SIGHASH_SINGLE is set, and nInputs > nOutputs
12112 // some signatures would be invalidated by the addition
12113 // of more outputs
12114 return nInputs <= nOutputs
12115 }
12116 })
12117 })
12118}
12119
12120TransactionBuilder.prototype.__overMaximumFees = function (bytes) {
12121 // not all inputs will have .value defined
12122 var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0)
12123
12124 // but all outputs do, and if we have any input value
12125 // we can immediately determine if the outputs are too small
12126 var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0)
12127 var fee = incoming - outgoing
12128 var feeRate = fee / bytes
12129
12130 return feeRate > this.maximumFeeRate
12131}
12132
12133module.exports = TransactionBuilder
12134
b777ff55 12135},{"./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){
a0091a40
IC
12136var typeforce = require('typeforce')
12137
12138var UINT31_MAX = Math.pow(2, 31) - 1
12139function UInt31 (value) {
12140 return typeforce.UInt32(value) && value <= UINT31_MAX
12141}
12142
12143function BIP32Path (value) {
12144 return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/)
12145}
12146BIP32Path.toJSON = function () { return 'BIP32 derivation path' }
12147
12148var SATOSHI_MAX = 21 * 1e14
12149function Satoshi (value) {
12150 return typeforce.UInt53(value) && value <= SATOSHI_MAX
12151}
12152
12153// external dependent types
12154var BigInt = typeforce.quacksLike('BigInteger')
12155var ECPoint = typeforce.quacksLike('Point')
12156
12157// exposed, external API
12158var ECSignature = typeforce.compile({ r: BigInt, s: BigInt })
12159var Network = typeforce.compile({
12160 messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String),
12161 bip32: {
12162 public: typeforce.UInt32,
12163 private: typeforce.UInt32
12164 },
12165 pubKeyHash: typeforce.UInt8,
12166 scriptHash: typeforce.UInt8,
12167 wif: typeforce.UInt8
12168})
12169
12170// extend typeforce types with ours
12171var types = {
12172 BigInt: BigInt,
12173 BIP32Path: BIP32Path,
12174 Buffer256bit: typeforce.BufferN(32),
12175 ECPoint: ECPoint,
12176 ECSignature: ECSignature,
12177 Hash160bit: typeforce.BufferN(20),
12178 Hash256bit: typeforce.BufferN(32),
12179 Network: Network,
12180 Satoshi: Satoshi,
12181 UInt31: UInt31
12182}
12183
12184for (var typeName in typeforce) {
12185 types[typeName] = typeforce[typeName]
12186}
12187
12188module.exports = types
12189
b777ff55
IC
12190},{"typeforce":112}],81:[function(require,module,exports){
12191var basex = require('base-x')
12192var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
a0091a40 12193
b777ff55 12194module.exports = basex(ALPHABET)
a0091a40 12195
b777ff55
IC
12196},{"base-x":35}],82:[function(require,module,exports){
12197'use strict'
a0091a40 12198
b777ff55
IC
12199var base58 = require('bs58')
12200var Buffer = require('safe-buffer').Buffer
a0091a40 12201
b777ff55
IC
12202module.exports = function (checksumFn) {
12203 // Encode a buffer as a base58-check encoded string
12204 function encode (payload) {
12205 var checksum = checksumFn(payload)
a0091a40 12206
b777ff55
IC
12207 return base58.encode(Buffer.concat([
12208 payload,
12209 checksum
12210 ], payload.length + 4))
12211 }
a0091a40 12212
b777ff55
IC
12213 function decodeRaw (buffer) {
12214 var payload = buffer.slice(0, -4)
12215 var checksum = buffer.slice(-4)
12216 var newChecksum = checksumFn(payload)
a0091a40 12217
b777ff55
IC
12218 if (checksum[0] ^ newChecksum[0] |
12219 checksum[1] ^ newChecksum[1] |
12220 checksum[2] ^ newChecksum[2] |
12221 checksum[3] ^ newChecksum[3]) return
a0091a40 12222
b777ff55 12223 return payload
a0091a40 12224 }
b777ff55
IC
12225
12226 // Decode a base58-check encoded string to a buffer, no result if checksum is wrong
12227 function decodeUnsafe (string) {
12228 var buffer = base58.decodeUnsafe(string)
12229 if (!buffer) return
12230
12231 return decodeRaw(buffer)
a0091a40 12232 }
a0091a40 12233
b777ff55
IC
12234 function decode (string) {
12235 var buffer = base58.decode(string)
12236 var payload = decodeRaw(buffer, checksumFn)
12237 if (!payload) throw new Error('Invalid checksum')
12238 return payload
12239 }
9f59e99b 12240
b777ff55
IC
12241 return {
12242 encode: encode,
12243 decode: decode,
12244 decodeUnsafe: decodeUnsafe
a0091a40 12245 }
b777ff55 12246}
a0091a40 12247
b777ff55
IC
12248},{"bs58":81,"safe-buffer":101}],83:[function(require,module,exports){
12249'use strict'
a0091a40 12250
b777ff55
IC
12251var createHash = require('create-hash')
12252var bs58checkBase = require('./base')
a0091a40 12253
b777ff55
IC
12254// SHA256(SHA256(buffer))
12255function sha256x2 (buffer) {
12256 var tmp = createHash('sha256').update(buffer).digest()
12257 return createHash('sha256').update(tmp).digest()
12258}
a0091a40 12259
b777ff55 12260module.exports = bs58checkBase(sha256x2)
a0091a40 12261
b777ff55
IC
12262},{"./base":82,"create-hash":85}],84:[function(require,module,exports){
12263var Buffer = require('safe-buffer').Buffer
12264var Transform = require('stream').Transform
12265var StringDecoder = require('string_decoder').StringDecoder
12266var inherits = require('inherits')
a0091a40 12267
b777ff55
IC
12268function CipherBase (hashMode) {
12269 Transform.call(this)
12270 this.hashMode = typeof hashMode === 'string'
12271 if (this.hashMode) {
12272 this[hashMode] = this._finalOrDigest
12273 } else {
12274 this.final = this._finalOrDigest
12275 }
12276 if (this._final) {
12277 this.__final = this._final
12278 this._final = null
12279 }
12280 this._decoder = null
12281 this._encoding = null
12282}
12283inherits(CipherBase, Transform)
a0091a40 12284
b777ff55
IC
12285CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
12286 if (typeof data === 'string') {
12287 data = Buffer.from(data, inputEnc)
12288 }
a0091a40 12289
b777ff55
IC
12290 var outData = this._update(data)
12291 if (this.hashMode) return this
a0091a40 12292
b777ff55
IC
12293 if (outputEnc) {
12294 outData = this._toString(outData, outputEnc)
12295 }
a0091a40 12296
b777ff55
IC
12297 return outData
12298}
a0091a40 12299
b777ff55
IC
12300CipherBase.prototype.setAutoPadding = function () {}
12301CipherBase.prototype.getAuthTag = function () {
12302 throw new Error('trying to get auth tag in unsupported state')
12303}
a0091a40 12304
b777ff55
IC
12305CipherBase.prototype.setAuthTag = function () {
12306 throw new Error('trying to set auth tag in unsupported state')
12307}
a0091a40 12308
b777ff55
IC
12309CipherBase.prototype.setAAD = function () {
12310 throw new Error('trying to set aad in unsupported state')
12311}
a0091a40 12312
b777ff55
IC
12313CipherBase.prototype._transform = function (data, _, next) {
12314 var err
12315 try {
12316 if (this.hashMode) {
12317 this._update(data)
9f59e99b 12318 } else {
b777ff55 12319 this.push(this._update(data))
9f59e99b 12320 }
b777ff55
IC
12321 } catch (e) {
12322 err = e
12323 } finally {
12324 next(err)
12325 }
12326}
12327CipherBase.prototype._flush = function (done) {
12328 var err
12329 try {
12330 this.push(this.__final())
12331 } catch (e) {
12332 err = e
12333 }
a0091a40 12334
b777ff55
IC
12335 done(err)
12336}
12337CipherBase.prototype._finalOrDigest = function (outputEnc) {
12338 var outData = this.__final() || Buffer.alloc(0)
12339 if (outputEnc) {
12340 outData = this._toString(outData, outputEnc, true)
12341 }
12342 return outData
12343}
a0091a40 12344
b777ff55
IC
12345CipherBase.prototype._toString = function (value, enc, fin) {
12346 if (!this._decoder) {
12347 this._decoder = new StringDecoder(enc)
12348 this._encoding = enc
12349 }
a0091a40 12350
b777ff55 12351 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
a0091a40 12352
b777ff55
IC
12353 var out = this._decoder.write(value)
12354 if (fin) {
12355 out += this._decoder.end()
12356 }
a0091a40 12357
b777ff55
IC
12358 return out
12359}
a0091a40 12360
b777ff55 12361module.exports = CipherBase
a0091a40 12362
b777ff55
IC
12363},{"inherits":96,"safe-buffer":101,"stream":28,"string_decoder":29}],85:[function(require,module,exports){
12364(function (Buffer){
12365'use strict'
12366var inherits = require('inherits')
12367var md5 = require('./md5')
12368var RIPEMD160 = require('ripemd160')
12369var sha = require('sha.js')
a0091a40 12370
b777ff55 12371var Base = require('cipher-base')
a0091a40 12372
b777ff55
IC
12373function HashNoConstructor (hash) {
12374 Base.call(this, 'digest')
a0091a40 12375
b777ff55
IC
12376 this._hash = hash
12377 this.buffers = []
12378}
a0091a40 12379
b777ff55 12380inherits(HashNoConstructor, Base)
a0091a40 12381
b777ff55
IC
12382HashNoConstructor.prototype._update = function (data) {
12383 this.buffers.push(data)
12384}
a0091a40 12385
b777ff55
IC
12386HashNoConstructor.prototype._final = function () {
12387 var buf = Buffer.concat(this.buffers)
12388 var r = this._hash(buf)
12389 this.buffers = null
a0091a40 12390
b777ff55
IC
12391 return r
12392}
a0091a40 12393
b777ff55
IC
12394function Hash (hash) {
12395 Base.call(this, 'digest')
a0091a40 12396
b777ff55
IC
12397 this._hash = hash
12398}
a0091a40 12399
b777ff55 12400inherits(Hash, Base)
a0091a40 12401
b777ff55
IC
12402Hash.prototype._update = function (data) {
12403 this._hash.update(data)
12404}
a0091a40 12405
b777ff55
IC
12406Hash.prototype._final = function () {
12407 return this._hash.digest()
12408}
a0091a40 12409
b777ff55
IC
12410module.exports = function createHash (alg) {
12411 alg = alg.toLowerCase()
12412 if (alg === 'md5') return new HashNoConstructor(md5)
12413 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
a0091a40 12414
b777ff55
IC
12415 return new Hash(sha(alg))
12416}
a0091a40 12417
b777ff55
IC
12418}).call(this,require("buffer").Buffer)
12419},{"./md5":87,"buffer":5,"cipher-base":84,"inherits":96,"ripemd160":100,"sha.js":103}],86:[function(require,module,exports){
12420(function (Buffer){
12421'use strict'
12422var intSize = 4
12423var zeroBuffer = new Buffer(intSize)
12424zeroBuffer.fill(0)
a0091a40 12425
b777ff55
IC
12426var charSize = 8
12427var hashSize = 16
a0091a40 12428
b777ff55
IC
12429function toArray (buf) {
12430 if ((buf.length % intSize) !== 0) {
12431 var len = buf.length + (intSize - (buf.length % intSize))
12432 buf = Buffer.concat([buf, zeroBuffer], len)
12433 }
a0091a40 12434
b777ff55
IC
12435 var arr = new Array(buf.length >>> 2)
12436 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
12437 arr[j] = buf.readInt32LE(i)
9f59e99b 12438 }
9f59e99b 12439
b777ff55 12440 return arr
9f59e99b
IC
12441}
12442
b777ff55
IC
12443module.exports = function hash (buf, fn) {
12444 var arr = fn(toArray(buf), buf.length * charSize)
12445 buf = new Buffer(hashSize)
12446 for (var i = 0; i < arr.length; i++) {
12447 buf.writeInt32LE(arr[i], i << 2, true)
9f59e99b 12448 }
b777ff55 12449 return buf
9f59e99b
IC
12450}
12451
b777ff55
IC
12452}).call(this,require("buffer").Buffer)
12453},{"buffer":5}],87:[function(require,module,exports){
12454'use strict'
12455/*
12456 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
12457 * Digest Algorithm, as defined in RFC 1321.
12458 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
12459 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
12460 * Distributed under the BSD License
12461 * See http://pajhome.org.uk/crypt/md5 for more info.
12462 */
9f59e99b 12463
b777ff55 12464var makeHash = require('./make-hash')
9f59e99b 12465
b777ff55
IC
12466/*
12467 * Calculate the MD5 of an array of little-endian words, and a bit length
12468 */
12469function core_md5 (x, len) {
12470 /* append padding */
12471 x[len >> 5] |= 0x80 << ((len) % 32)
12472 x[(((len + 64) >>> 9) << 4) + 14] = len
a0091a40 12473
b777ff55
IC
12474 var a = 1732584193
12475 var b = -271733879
12476 var c = -1732584194
12477 var d = 271733878
a0091a40 12478
b777ff55
IC
12479 for (var i = 0; i < x.length; i += 16) {
12480 var olda = a
12481 var oldb = b
12482 var oldc = c
12483 var oldd = d
a0091a40 12484
b777ff55
IC
12485 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
12486 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
12487 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
12488 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
12489 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
12490 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
12491 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
12492 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
12493 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
12494 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
12495 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
12496 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
12497 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
12498 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
12499 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
12500 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
a0091a40 12501
b777ff55
IC
12502 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
12503 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
12504 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
12505 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
12506 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
12507 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
12508 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
12509 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
12510 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
12511 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
12512 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
12513 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
12514 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
12515 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
12516 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
12517 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
a0091a40 12518
b777ff55
IC
12519 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
12520 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
12521 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
12522 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
12523 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
12524 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
12525 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
12526 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
12527 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
12528 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
12529 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
12530 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
12531 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
12532 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
12533 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
12534 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
a0091a40 12535
b777ff55
IC
12536 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
12537 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
12538 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
12539 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
12540 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
12541 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
12542 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
12543 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
12544 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
12545 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
12546 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
12547 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
12548 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
12549 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
12550 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
12551 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
a0091a40 12552
b777ff55
IC
12553 a = safe_add(a, olda)
12554 b = safe_add(b, oldb)
12555 c = safe_add(c, oldc)
12556 d = safe_add(d, oldd)
9f59e99b 12557 }
a0091a40 12558
b777ff55 12559 return [a, b, c, d]
a0091a40
IC
12560}
12561
b777ff55
IC
12562/*
12563 * These functions implement the four basic operations the algorithm uses.
12564 */
12565function md5_cmn (q, a, b, x, s, t) {
12566 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
12567}
9f59e99b 12568
b777ff55
IC
12569function md5_ff (a, b, c, d, x, s, t) {
12570 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
12571}
9f59e99b 12572
b777ff55
IC
12573function md5_gg (a, b, c, d, x, s, t) {
12574 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
a0091a40
IC
12575}
12576
b777ff55
IC
12577function md5_hh (a, b, c, d, x, s, t) {
12578 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
9f59e99b 12579}
a0091a40 12580
b777ff55
IC
12581function md5_ii (a, b, c, d, x, s, t) {
12582 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
a0091a40
IC
12583}
12584
b777ff55
IC
12585/*
12586 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
12587 * to work around bugs in some JS interpreters.
12588 */
12589function safe_add (x, y) {
12590 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
12591 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
12592 return (msw << 16) | (lsw & 0xFFFF)
a0091a40
IC
12593}
12594
b777ff55
IC
12595/*
12596 * Bitwise rotate a 32-bit number to the left.
12597 */
12598function bit_rol (num, cnt) {
12599 return (num << cnt) | (num >>> (32 - cnt))
12600}
9f59e99b 12601
b777ff55
IC
12602module.exports = function md5 (buf) {
12603 return makeHash(buf, core_md5)
a0091a40
IC
12604}
12605
b777ff55 12606},{"./make-hash":86}],88:[function(require,module,exports){
a0091a40
IC
12607'use strict'
12608var inherits = require('inherits')
b777ff55
IC
12609var Legacy = require('./legacy')
12610var Base = require('cipher-base')
12611var Buffer = require('safe-buffer').Buffer
12612var md5 = require('create-hash/md5')
12613var RIPEMD160 = require('ripemd160')
a0091a40 12614
b777ff55 12615var sha = require('sha.js')
a0091a40 12616
b777ff55 12617var ZEROS = Buffer.alloc(128)
a0091a40 12618
b777ff55
IC
12619function Hmac (alg, key) {
12620 Base.call(this, 'digest')
12621 if (typeof key === 'string') {
12622 key = Buffer.from(key)
12623 }
9f59e99b 12624
b777ff55 12625 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
9f59e99b 12626
b777ff55
IC
12627 this._alg = alg
12628 this._key = key
12629 if (key.length > blocksize) {
12630 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12631 key = hash.update(key).digest()
12632 } else if (key.length < blocksize) {
12633 key = Buffer.concat([key, ZEROS], blocksize)
a0091a40
IC
12634 }
12635
b777ff55
IC
12636 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12637 var opad = this._opad = Buffer.allocUnsafe(blocksize)
a0091a40 12638
b777ff55
IC
12639 for (var i = 0; i < blocksize; i++) {
12640 ipad[i] = key[i] ^ 0x36
12641 opad[i] = key[i] ^ 0x5C
a0091a40 12642 }
b777ff55
IC
12643 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
12644 this._hash.update(ipad)
9f59e99b 12645}
a0091a40 12646
b777ff55 12647inherits(Hmac, Base)
a0091a40 12648
b777ff55
IC
12649Hmac.prototype._update = function (data) {
12650 this._hash.update(data)
12651}
9f59e99b 12652
b777ff55
IC
12653Hmac.prototype._final = function () {
12654 var h = this._hash.digest()
12655 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
12656 return hash.update(this._opad).update(h).digest()
9f59e99b
IC
12657}
12658
b777ff55
IC
12659module.exports = function createHmac (alg, key) {
12660 alg = alg.toLowerCase()
12661 if (alg === 'rmd160' || alg === 'ripemd160') {
12662 return new Hmac('rmd160', key)
12663 }
12664 if (alg === 'md5') {
12665 return new Legacy(md5, key)
12666 }
12667 return new Hmac(alg, key)
a0091a40
IC
12668}
12669
b777ff55
IC
12670},{"./legacy":89,"cipher-base":84,"create-hash/md5":87,"inherits":96,"ripemd160":100,"safe-buffer":101,"sha.js":103}],89:[function(require,module,exports){
12671'use strict'
12672var inherits = require('inherits')
12673var Buffer = require('safe-buffer').Buffer
a0091a40 12674
b777ff55 12675var Base = require('cipher-base')
a0091a40 12676
b777ff55
IC
12677var ZEROS = Buffer.alloc(128)
12678var blocksize = 64
a0091a40 12679
b777ff55
IC
12680function Hmac (alg, key) {
12681 Base.call(this, 'digest')
12682 if (typeof key === 'string') {
12683 key = Buffer.from(key)
12684 }
a0091a40 12685
b777ff55
IC
12686 this._alg = alg
12687 this._key = key
a0091a40 12688
b777ff55
IC
12689 if (key.length > blocksize) {
12690 key = alg(key)
12691 } else if (key.length < blocksize) {
12692 key = Buffer.concat([key, ZEROS], blocksize)
12693 }
a0091a40 12694
b777ff55
IC
12695 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
12696 var opad = this._opad = Buffer.allocUnsafe(blocksize)
a0091a40 12697
b777ff55
IC
12698 for (var i = 0; i < blocksize; i++) {
12699 ipad[i] = key[i] ^ 0x36
12700 opad[i] = key[i] ^ 0x5C
9f59e99b 12701 }
a0091a40 12702
b777ff55
IC
12703 this._hash = [ipad]
12704}
a0091a40 12705
b777ff55 12706inherits(Hmac, Base)
a0091a40 12707
b777ff55
IC
12708Hmac.prototype._update = function (data) {
12709 this._hash.push(data)
12710}
9f59e99b 12711
b777ff55
IC
12712Hmac.prototype._final = function () {
12713 var h = this._alg(Buffer.concat(this._hash))
12714 return this._alg(Buffer.concat([this._opad, h]))
12715}
12716module.exports = Hmac
9f59e99b 12717
b777ff55
IC
12718},{"cipher-base":84,"inherits":96,"safe-buffer":101}],90:[function(require,module,exports){
12719var assert = require('assert')
12720var BigInteger = require('bigi')
a0091a40 12721
b777ff55 12722var Point = require('./point')
a0091a40 12723
b777ff55
IC
12724function Curve (p, a, b, Gx, Gy, n, h) {
12725 this.p = p
12726 this.a = a
12727 this.b = b
12728 this.G = Point.fromAffine(this, Gx, Gy)
12729 this.n = n
12730 this.h = h
a0091a40 12731
b777ff55 12732 this.infinity = new Point(this, null, null, BigInteger.ZERO)
9f59e99b 12733
b777ff55
IC
12734 // result caching
12735 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
9f59e99b 12736
b777ff55
IC
12737 // determine size of p in bytes
12738 this.pLength = Math.floor((this.p.bitLength() + 7) / 8)
a0091a40
IC
12739}
12740
b777ff55
IC
12741Curve.prototype.pointFromX = function (isOdd, x) {
12742 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
12743 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
a0091a40 12744
b777ff55
IC
12745 var y = beta
12746 if (beta.isEven() ^ !isOdd) {
12747 y = this.p.subtract(y) // -y % p
12748 }
a0091a40 12749
b777ff55
IC
12750 return Point.fromAffine(this, x, y)
12751}
a0091a40 12752
b777ff55
IC
12753Curve.prototype.isInfinity = function (Q) {
12754 if (Q === this.infinity) return true
a0091a40 12755
b777ff55
IC
12756 return Q.z.signum() === 0 && Q.y.signum() !== 0
12757}
a0091a40 12758
b777ff55
IC
12759Curve.prototype.isOnCurve = function (Q) {
12760 if (this.isInfinity(Q)) return true
12761
12762 var x = Q.affineX
12763 var y = Q.affineY
12764 var a = this.a
12765 var b = this.b
12766 var p = this.p
12767
12768 // Check that xQ and yQ are integers in the interval [0, p - 1]
12769 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
12770 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
a0091a40 12771
b777ff55
IC
12772 // and check that y^2 = x^3 + ax + b (mod p)
12773 var lhs = y.square().mod(p)
12774 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
12775 return lhs.equals(rhs)
12776}
a0091a40 12777
b777ff55
IC
12778/**
12779 * Validate an elliptic curve point.
12780 *
12781 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
12782 */
12783Curve.prototype.validate = function (Q) {
12784 // Check Q != O
12785 assert(!this.isInfinity(Q), 'Point is at infinity')
12786 assert(this.isOnCurve(Q), 'Point is not on the curve')
a0091a40 12787
b777ff55
IC
12788 // Check nQ = O (where Q is a scalar multiple of G)
12789 var nQ = Q.multiply(this.n)
12790 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
a0091a40 12791
b777ff55
IC
12792 return true
12793}
a0091a40 12794
b777ff55 12795module.exports = Curve
a0091a40 12796
b777ff55
IC
12797},{"./point":94,"assert":1,"bigi":39}],91:[function(require,module,exports){
12798module.exports={
12799 "secp128r1": {
12800 "p": "fffffffdffffffffffffffffffffffff",
12801 "a": "fffffffdfffffffffffffffffffffffc",
12802 "b": "e87579c11079f43dd824993c2cee5ed3",
12803 "n": "fffffffe0000000075a30d1b9038a115",
12804 "h": "01",
12805 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
12806 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
12807 },
12808 "secp160k1": {
12809 "p": "fffffffffffffffffffffffffffffffeffffac73",
12810 "a": "00",
12811 "b": "07",
12812 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
12813 "h": "01",
12814 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
12815 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
12816 },
12817 "secp160r1": {
12818 "p": "ffffffffffffffffffffffffffffffff7fffffff",
12819 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
12820 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
12821 "n": "0100000000000000000001f4c8f927aed3ca752257",
12822 "h": "01",
12823 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
12824 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
12825 },
12826 "secp192k1": {
12827 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
12828 "a": "00",
12829 "b": "03",
12830 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
12831 "h": "01",
12832 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
12833 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
12834 },
12835 "secp192r1": {
12836 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
12837 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
12838 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
12839 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
12840 "h": "01",
12841 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
12842 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
12843 },
12844 "secp256k1": {
12845 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
12846 "a": "00",
12847 "b": "07",
12848 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
12849 "h": "01",
12850 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
12851 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
12852 },
12853 "secp256r1": {
12854 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
12855 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
12856 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
12857 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
12858 "h": "01",
12859 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
12860 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
12861 }
a0091a40
IC
12862}
12863
b777ff55
IC
12864},{}],92:[function(require,module,exports){
12865var Point = require('./point')
12866var Curve = require('./curve')
a0091a40 12867
b777ff55 12868var getCurveByName = require('./names')
a0091a40 12869
b777ff55
IC
12870module.exports = {
12871 Curve: Curve,
12872 Point: Point,
12873 getCurveByName: getCurveByName
12874}
a0091a40 12875
b777ff55
IC
12876},{"./curve":90,"./names":93,"./point":94}],93:[function(require,module,exports){
12877var BigInteger = require('bigi')
a0091a40 12878
b777ff55
IC
12879var curves = require('./curves.json')
12880var Curve = require('./curve')
a0091a40 12881
b777ff55
IC
12882function getCurveByName (name) {
12883 var curve = curves[name]
12884 if (!curve) return null
a0091a40 12885
b777ff55
IC
12886 var p = new BigInteger(curve.p, 16)
12887 var a = new BigInteger(curve.a, 16)
12888 var b = new BigInteger(curve.b, 16)
12889 var n = new BigInteger(curve.n, 16)
12890 var h = new BigInteger(curve.h, 16)
12891 var Gx = new BigInteger(curve.Gx, 16)
12892 var Gy = new BigInteger(curve.Gy, 16)
a0091a40 12893
b777ff55 12894 return new Curve(p, a, b, Gx, Gy, n, h)
9f59e99b 12895}
a0091a40 12896
b777ff55
IC
12897module.exports = getCurveByName
12898
12899},{"./curve":90,"./curves.json":91,"bigi":39}],94:[function(require,module,exports){
12900var assert = require('assert')
12901var Buffer = require('safe-buffer').Buffer
12902var BigInteger = require('bigi')
a0091a40 12903
b777ff55 12904var THREE = BigInteger.valueOf(3)
a0091a40 12905
b777ff55
IC
12906function Point (curve, x, y, z) {
12907 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
a0091a40 12908
b777ff55
IC
12909 this.curve = curve
12910 this.x = x
12911 this.y = y
12912 this.z = z
12913 this._zInv = null
a0091a40 12914
b777ff55
IC
12915 this.compressed = true
12916}
a0091a40 12917
b777ff55
IC
12918Object.defineProperty(Point.prototype, 'zInv', {
12919 get: function () {
12920 if (this._zInv === null) {
12921 this._zInv = this.z.modInverse(this.curve.p)
12922 }
a0091a40 12923
b777ff55 12924 return this._zInv
a0091a40 12925 }
b777ff55 12926})
a0091a40 12927
b777ff55
IC
12928Object.defineProperty(Point.prototype, 'affineX', {
12929 get: function () {
12930 return this.x.multiply(this.zInv).mod(this.curve.p)
12931 }
12932})
9f59e99b 12933
b777ff55
IC
12934Object.defineProperty(Point.prototype, 'affineY', {
12935 get: function () {
12936 return this.y.multiply(this.zInv).mod(this.curve.p)
12937 }
12938})
9f59e99b 12939
b777ff55
IC
12940Point.fromAffine = function (curve, x, y) {
12941 return new Point(curve, x, y, BigInteger.ONE)
a0091a40
IC
12942}
12943
b777ff55
IC
12944Point.prototype.equals = function (other) {
12945 if (other === this) return true
12946 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
12947 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
a0091a40 12948
b777ff55
IC
12949 // u = Y2 * Z1 - Y1 * Z2
12950 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
a0091a40 12951
b777ff55 12952 if (u.signum() !== 0) return false
a0091a40 12953
b777ff55
IC
12954 // v = X2 * Z1 - X1 * Z2
12955 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
a0091a40 12956
b777ff55 12957 return v.signum() === 0
a0091a40
IC
12958}
12959
b777ff55
IC
12960Point.prototype.negate = function () {
12961 var y = this.curve.p.subtract(this.y)
a0091a40 12962
b777ff55 12963 return new Point(this.curve, this.x, y, this.z)
a0091a40
IC
12964}
12965
b777ff55
IC
12966Point.prototype.add = function (b) {
12967 if (this.curve.isInfinity(this)) return b
12968 if (this.curve.isInfinity(b)) return this
a0091a40 12969
b777ff55
IC
12970 var x1 = this.x
12971 var y1 = this.y
12972 var x2 = b.x
12973 var y2 = b.y
a0091a40 12974
b777ff55
IC
12975 // u = Y2 * Z1 - Y1 * Z2
12976 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
12977 // v = X2 * Z1 - X1 * Z2
12978 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
a0091a40 12979
b777ff55
IC
12980 if (v.signum() === 0) {
12981 if (u.signum() === 0) {
12982 return this.twice() // this == b, so double
12983 }
a0091a40 12984
b777ff55
IC
12985 return this.curve.infinity // this = -b, so infinity
12986 }
a0091a40 12987
b777ff55
IC
12988 var v2 = v.square()
12989 var v3 = v2.multiply(v)
12990 var x1v2 = x1.multiply(v2)
12991 var zu2 = u.square().multiply(this.z)
a0091a40 12992
b777ff55
IC
12993 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
12994 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
12995 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
12996 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)
12997 // z3 = v^3 * z1 * z2
12998 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
a0091a40 12999
b777ff55 13000 return new Point(this.curve, x3, y3, z3)
a0091a40
IC
13001}
13002
b777ff55
IC
13003Point.prototype.twice = function () {
13004 if (this.curve.isInfinity(this)) return this
13005 if (this.y.signum() === 0) return this.curve.infinity
a0091a40 13006
b777ff55
IC
13007 var x1 = this.x
13008 var y1 = this.y
a0091a40 13009
b777ff55
IC
13010 var y1z1 = y1.multiply(this.z).mod(this.curve.p)
13011 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
13012 var a = this.curve.a
a0091a40 13013
b777ff55
IC
13014 // w = 3 * x1^2 + a * z1^2
13015 var w = x1.square().multiply(THREE)
a0091a40 13016
b777ff55
IC
13017 if (a.signum() !== 0) {
13018 w = w.add(this.z.square().multiply(a))
13019 }
a0091a40 13020
b777ff55
IC
13021 w = w.mod(this.curve.p)
13022 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
13023 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
13024 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
13025 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
13026 // z3 = 8 * (y1 * z1)^3
13027 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
9f59e99b 13028
b777ff55 13029 return new Point(this.curve, x3, y3, z3)
a0091a40
IC
13030}
13031
b777ff55
IC
13032// Simple NAF (Non-Adjacent Form) multiplication algorithm
13033// TODO: modularize the multiplication algorithm
13034Point.prototype.multiply = function (k) {
13035 if (this.curve.isInfinity(this)) return this
13036 if (k.signum() === 0) return this.curve.infinity
a0091a40 13037
b777ff55
IC
13038 var e = k
13039 var h = e.multiply(THREE)
a0091a40 13040
b777ff55
IC
13041 var neg = this.negate()
13042 var R = this
a0091a40 13043
b777ff55
IC
13044 for (var i = h.bitLength() - 2; i > 0; --i) {
13045 var hBit = h.testBit(i)
13046 var eBit = e.testBit(i)
a0091a40 13047
b777ff55 13048 R = R.twice()
a0091a40 13049
b777ff55
IC
13050 if (hBit !== eBit) {
13051 R = R.add(hBit ? this : neg)
a0091a40
IC
13052 }
13053 }
a0091a40 13054
b777ff55 13055 return R
9f59e99b 13056}
a0091a40 13057
b777ff55
IC
13058// Compute this*j + x*k (simultaneous multiplication)
13059Point.prototype.multiplyTwo = function (j, x, k) {
13060 var i = Math.max(j.bitLength(), k.bitLength()) - 1
13061 var R = this.curve.infinity
13062 var both = this.add(x)
a0091a40 13063
b777ff55
IC
13064 while (i >= 0) {
13065 var jBit = j.testBit(i)
13066 var kBit = k.testBit(i)
a0091a40 13067
b777ff55
IC
13068 R = R.twice()
13069
13070 if (jBit) {
13071 if (kBit) {
13072 R = R.add(both)
13073 } else {
13074 R = R.add(this)
13075 }
13076 } else if (kBit) {
13077 R = R.add(x)
a0091a40 13078 }
b777ff55 13079 --i
a0091a40 13080 }
a0091a40 13081
b777ff55 13082 return R
9f59e99b 13083}
a0091a40 13084
b777ff55
IC
13085Point.prototype.getEncoded = function (compressed) {
13086 if (compressed == null) compressed = this.compressed
13087 if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00'
a0091a40 13088
b777ff55
IC
13089 var x = this.affineX
13090 var y = this.affineY
13091 var byteLength = this.curve.pLength
13092 var buffer
a0091a40 13093
b777ff55
IC
13094 // 0x02/0x03 | X
13095 if (compressed) {
13096 buffer = Buffer.allocUnsafe(1 + byteLength)
13097 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
a0091a40 13098
b777ff55
IC
13099 // 0x04 | X | Y
13100 } else {
13101 buffer = Buffer.allocUnsafe(1 + byteLength + byteLength)
13102 buffer.writeUInt8(0x04, 0)
a0091a40 13103
b777ff55
IC
13104 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
13105 }
a0091a40 13106
b777ff55 13107 x.toBuffer(byteLength).copy(buffer, 1)
a0091a40 13108
b777ff55 13109 return buffer
9f59e99b 13110}
a0091a40 13111
b777ff55
IC
13112Point.decodeFrom = function (curve, buffer) {
13113 var type = buffer.readUInt8(0)
13114 var compressed = (type !== 4)
a0091a40 13115
b777ff55
IC
13116 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
13117 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
a0091a40 13118
b777ff55
IC
13119 var Q
13120 if (compressed) {
13121 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
13122 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
a0091a40 13123
b777ff55
IC
13124 var isOdd = (type === 0x03)
13125 Q = curve.pointFromX(isOdd, x)
13126 } else {
13127 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
a0091a40 13128
b777ff55
IC
13129 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
13130 Q = Point.fromAffine(curve, x, y)
13131 }
a0091a40 13132
b777ff55
IC
13133 Q.compressed = compressed
13134 return Q
13135}
a0091a40 13136
b777ff55
IC
13137Point.prototype.toString = function () {
13138 if (this.curve.isInfinity(this)) return '(INFINITY)'
a0091a40 13139
b777ff55
IC
13140 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
13141}
a0091a40 13142
b777ff55 13143module.exports = Point
a0091a40 13144
b777ff55
IC
13145},{"assert":1,"bigi":39,"safe-buffer":101}],95:[function(require,module,exports){
13146(function (Buffer){
13147'use strict'
13148var Transform = require('stream').Transform
13149var inherits = require('inherits')
a0091a40 13150
b777ff55
IC
13151function HashBase (blockSize) {
13152 Transform.call(this)
a0091a40 13153
b777ff55
IC
13154 this._block = new Buffer(blockSize)
13155 this._blockSize = blockSize
13156 this._blockOffset = 0
13157 this._length = [0, 0, 0, 0]
a0091a40 13158
b777ff55 13159 this._finalized = false
a0091a40
IC
13160}
13161
b777ff55 13162inherits(HashBase, Transform)
a0091a40 13163
b777ff55
IC
13164HashBase.prototype._transform = function (chunk, encoding, callback) {
13165 var error = null
13166 try {
13167 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
13168 this.update(chunk)
13169 } catch (err) {
13170 error = err
a0091a40 13171 }
a0091a40 13172
b777ff55
IC
13173 callback(error)
13174}
9f59e99b 13175
b777ff55
IC
13176HashBase.prototype._flush = function (callback) {
13177 var error = null
13178 try {
13179 this.push(this._digest())
13180 } catch (err) {
13181 error = err
13182 }
9f59e99b 13183
b777ff55
IC
13184 callback(error)
13185}
9f59e99b 13186
b777ff55
IC
13187HashBase.prototype.update = function (data, encoding) {
13188 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
13189 if (this._finalized) throw new Error('Digest already called')
13190 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
9f59e99b 13191
b777ff55
IC
13192 // consume data
13193 var block = this._block
13194 var offset = 0
13195 while (this._blockOffset + data.length - offset >= this._blockSize) {
13196 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
13197 this._update()
13198 this._blockOffset = 0
a0091a40 13199 }
b777ff55 13200 while (offset < data.length) block[this._blockOffset++] = data[offset++]
a0091a40 13201
b777ff55
IC
13202 // update length
13203 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
13204 this._length[j] += carry
13205 carry = (this._length[j] / 0x0100000000) | 0
13206 if (carry > 0) this._length[j] -= 0x0100000000 * carry
13207 }
a0091a40 13208
b777ff55
IC
13209 return this
13210}
a0091a40 13211
b777ff55
IC
13212HashBase.prototype._update = function (data) {
13213 throw new Error('_update is not implemented')
13214}
a0091a40 13215
b777ff55
IC
13216HashBase.prototype.digest = function (encoding) {
13217 if (this._finalized) throw new Error('Digest already called')
13218 this._finalized = true
a0091a40 13219
b777ff55
IC
13220 var digest = this._digest()
13221 if (encoding !== undefined) digest = digest.toString(encoding)
13222 return digest
13223}
a0091a40 13224
b777ff55
IC
13225HashBase.prototype._digest = function () {
13226 throw new Error('_digest is not implemented')
13227}
9f59e99b 13228
b777ff55 13229module.exports = HashBase
9f59e99b 13230
b777ff55
IC
13231}).call(this,require("buffer").Buffer)
13232},{"buffer":5,"inherits":96,"stream":28}],96:[function(require,module,exports){
9f59e99b 13233arguments[4][9][0].apply(exports,arguments)
b777ff55 13234},{"dup":9}],97:[function(require,module,exports){
a0091a40
IC
13235(function (Buffer){
13236// constant-space merkle root calculation algorithm
13237module.exports = function fastRoot (values, digestFn) {
13238 if (!Array.isArray(values)) throw TypeError('Expected values Array')
13239 if (typeof digestFn !== 'function') throw TypeError('Expected digest Function')
13240
13241 var length = values.length
13242 var results = values.concat()
13243
13244 while (length > 1) {
13245 var j = 0
13246
13247 for (var i = 0; i < length; i += 2, ++j) {
13248 var left = results[i]
13249 var right = i + 1 === length ? left : results[i + 1]
13250 var data = Buffer.concat([left, right])
13251
13252 results[j] = digestFn(data)
13253 }
13254
13255 length = j
13256 }
13257
13258 return results[0]
13259}
13260
13261}).call(this,require("buffer").Buffer)
b777ff55 13262},{"buffer":5}],98:[function(require,module,exports){
a0091a40
IC
13263var OPS = require('bitcoin-ops')
13264
13265function encodingLength (i) {
13266 return i < OPS.OP_PUSHDATA1 ? 1
13267 : i <= 0xff ? 2
13268 : i <= 0xffff ? 3
13269 : 5
13270}
13271
13272function encode (buffer, number, offset) {
13273 var size = encodingLength(number)
13274
13275 // ~6 bit
13276 if (size === 1) {
13277 buffer.writeUInt8(number, offset)
13278
13279 // 8 bit
13280 } else if (size === 2) {
13281 buffer.writeUInt8(OPS.OP_PUSHDATA1, offset)
13282 buffer.writeUInt8(number, offset + 1)
13283
13284 // 16 bit
13285 } else if (size === 3) {
13286 buffer.writeUInt8(OPS.OP_PUSHDATA2, offset)
13287 buffer.writeUInt16LE(number, offset + 1)
13288
13289 // 32 bit
13290 } else {
13291 buffer.writeUInt8(OPS.OP_PUSHDATA4, offset)
13292 buffer.writeUInt32LE(number, offset + 1)
13293 }
13294
13295 return size
13296}
13297
13298function decode (buffer, offset) {
13299 var opcode = buffer.readUInt8(offset)
13300 var number, size
13301
13302 // ~6 bit
13303 if (opcode < OPS.OP_PUSHDATA1) {
13304 number = opcode
13305 size = 1
13306
13307 // 8 bit
13308 } else if (opcode === OPS.OP_PUSHDATA1) {
13309 if (offset + 2 > buffer.length) return null
13310 number = buffer.readUInt8(offset + 1)
13311 size = 2
13312
13313 // 16 bit
13314 } else if (opcode === OPS.OP_PUSHDATA2) {
13315 if (offset + 3 > buffer.length) return null
13316 number = buffer.readUInt16LE(offset + 1)
13317 size = 3
13318
13319 // 32 bit
13320 } else {
13321 if (offset + 5 > buffer.length) return null
13322 if (opcode !== OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode')
13323
13324 number = buffer.readUInt32LE(offset + 1)
13325 size = 5
13326 }
13327
13328 return {
13329 opcode: opcode,
13330 number: number,
13331 size: size
13332 }
13333}
13334
13335module.exports = {
13336 encodingLength: encodingLength,
13337 encode: encode,
13338 decode: decode
13339}
13340
b777ff55 13341},{"bitcoin-ops":42}],99:[function(require,module,exports){
a0091a40
IC
13342(function (process,global){
13343'use strict'
13344
13345function oldBrowser () {
b777ff55 13346 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
a0091a40
IC
13347}
13348
13349var Buffer = require('safe-buffer').Buffer
13350var crypto = global.crypto || global.msCrypto
13351
13352if (crypto && crypto.getRandomValues) {
13353 module.exports = randomBytes
13354} else {
13355 module.exports = oldBrowser
13356}
13357
13358function randomBytes (size, cb) {
13359 // phantomjs needs to throw
13360 if (size > 65536) throw new Error('requested too many random bytes')
13361 // in case browserify isn't using the Uint8Array version
13362 var rawBytes = new global.Uint8Array(size)
13363
13364 // This will not work in older browsers.
13365 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
13366 if (size > 0) { // getRandomValues fails on IE if size == 0
13367 crypto.getRandomValues(rawBytes)
13368 }
13369
13370 // XXX: phantomjs doesn't like a buffer being passed here
13371 var bytes = Buffer.from(rawBytes.buffer)
13372
13373 if (typeof cb === 'function') {
13374 return process.nextTick(function () {
13375 cb(null, bytes)
13376 })
13377 }
13378
13379 return bytes
13380}
13381
13382}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
b777ff55 13383},{"_process":13,"safe-buffer":101}],100:[function(require,module,exports){
a0091a40
IC
13384(function (Buffer){
13385'use strict'
13386var inherits = require('inherits')
13387var HashBase = require('hash-base')
13388
13389function RIPEMD160 () {
13390 HashBase.call(this, 64)
13391
13392 // state
13393 this._a = 0x67452301
13394 this._b = 0xefcdab89
13395 this._c = 0x98badcfe
13396 this._d = 0x10325476
13397 this._e = 0xc3d2e1f0
13398}
13399
13400inherits(RIPEMD160, HashBase)
13401
13402RIPEMD160.prototype._update = function () {
13403 var m = new Array(16)
13404 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
13405
13406 var al = this._a
13407 var bl = this._b
13408 var cl = this._c
13409 var dl = this._d
13410 var el = this._e
13411
13412 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
13413 // K = 0x00000000
13414 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
13415 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
13416 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
13417 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
13418 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
13419 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
13420 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
13421 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
13422 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
13423 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
13424 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
13425 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
13426 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
13427 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
13428 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
13429 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
13430 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
13431
13432 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
13433 // K = 0x5a827999
13434 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
13435 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
13436 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
13437 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
13438 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
13439 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
13440 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
13441 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
13442 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
13443 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
13444 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
13445 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
13446 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
13447 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
13448 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
13449 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
13450 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
13451
13452 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
13453 // K = 0x6ed9eba1
13454 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
13455 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
13456 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
13457 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
13458 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
13459 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
13460 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
13461 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
13462 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
13463 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
13464 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
13465 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
13466 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
13467 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
13468 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
13469 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
13470 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
13471
13472 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
13473 // K = 0x8f1bbcdc
13474 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
13475 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
13476 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
13477 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
13478 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
13479 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
13480 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
13481 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
13482 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
13483 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
13484 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
13485 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
13486 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
13487 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
13488 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
13489 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
13490 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
13491
13492 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
13493 // K = 0xa953fd4e
13494 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
13495 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
13496 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
13497 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
13498 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
13499 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
13500 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
13501 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
13502 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
13503 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
13504 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
13505 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
13506 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
13507 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
13508 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
13509 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
13510 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
13511
13512 var ar = this._a
13513 var br = this._b
13514 var cr = this._c
13515 var dr = this._d
13516 var er = this._e
13517
13518 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
13519 // K' = 0x50a28be6
13520 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
13521 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
13522 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
13523 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
13524 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
13525 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
13526 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
13527 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
13528 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
13529 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
13530 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
13531 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
13532 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
13533 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
13534 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
13535 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
13536 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
13537
13538 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
13539 // K' = 0x5c4dd124
13540 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
13541 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
13542 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
13543 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
13544 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
13545 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
13546 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
13547 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
13548 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
13549 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
13550 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
13551 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
13552 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
13553 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
13554 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
13555 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
13556 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
13557
13558 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
13559 // K' = 0x6d703ef3
13560 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
13561 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
13562 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
13563 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
13564 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
13565 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
13566 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
13567 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
13568 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
13569 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
13570 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
13571 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
13572 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
13573 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
13574 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
13575 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
13576 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
13577
13578 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
13579 // K' = 0x7a6d76e9
13580 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
13581 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
13582 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
13583 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
13584 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
13585 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
13586 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
13587 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
13588 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
13589 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
13590 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
13591 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
13592 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
13593 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
13594 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
13595 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
13596 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
13597
13598 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
13599 // K' = 0x00000000
13600 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
13601 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
13602 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
13603 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
13604 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
13605 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
13606 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
13607 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
13608 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
13609 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
13610 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
13611 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
13612 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
13613 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
13614 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
13615 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
13616 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
13617
13618 // change state
13619 var t = (this._b + cl + dr) | 0
13620 this._b = (this._c + dl + er) | 0
13621 this._c = (this._d + el + ar) | 0
13622 this._d = (this._e + al + br) | 0
13623 this._e = (this._a + bl + cr) | 0
13624 this._a = t
13625}
13626
13627RIPEMD160.prototype._digest = function () {
13628 // create padding and handle blocks
13629 this._block[this._blockOffset++] = 0x80
13630 if (this._blockOffset > 56) {
13631 this._block.fill(0, this._blockOffset, 64)
13632 this._update()
13633 this._blockOffset = 0
13634 }
13635
13636 this._block.fill(0, this._blockOffset, 56)
13637 this._block.writeUInt32LE(this._length[0], 56)
13638 this._block.writeUInt32LE(this._length[1], 60)
13639 this._update()
13640
13641 // produce result
13642 var buffer = new Buffer(20)
13643 buffer.writeInt32LE(this._a, 0)
13644 buffer.writeInt32LE(this._b, 4)
13645 buffer.writeInt32LE(this._c, 8)
13646 buffer.writeInt32LE(this._d, 12)
13647 buffer.writeInt32LE(this._e, 16)
13648 return buffer
13649}
13650
13651function rotl (x, n) {
13652 return (x << n) | (x >>> (32 - n))
13653}
13654
13655function fn1 (a, b, c, d, e, m, k, s) {
13656 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
13657}
13658
13659function fn2 (a, b, c, d, e, m, k, s) {
13660 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
13661}
13662
13663function fn3 (a, b, c, d, e, m, k, s) {
13664 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
13665}
13666
13667function fn4 (a, b, c, d, e, m, k, s) {
13668 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
13669}
13670
13671function fn5 (a, b, c, d, e, m, k, s) {
13672 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
13673}
13674
13675module.exports = RIPEMD160
13676
13677}).call(this,require("buffer").Buffer)
b777ff55 13678},{"buffer":5,"hash-base":95,"inherits":96}],101:[function(require,module,exports){
9f59e99b
IC
13679/* eslint-disable node/no-deprecated-api */
13680var buffer = require('buffer')
13681var Buffer = buffer.Buffer
13682
13683// alternative to using Object.keys for old browsers
13684function copyProps (src, dst) {
13685 for (var key in src) {
13686 dst[key] = src[key]
13687 }
13688}
13689if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13690 module.exports = buffer
13691} else {
13692 // Copy properties from require('buffer')
13693 copyProps(buffer, exports)
13694 exports.Buffer = SafeBuffer
13695}
13696
13697function SafeBuffer (arg, encodingOrOffset, length) {
13698 return Buffer(arg, encodingOrOffset, length)
13699}
13700
13701// Copy static methods from Buffer
13702copyProps(Buffer, SafeBuffer)
13703
13704SafeBuffer.from = function (arg, encodingOrOffset, length) {
13705 if (typeof arg === 'number') {
13706 throw new TypeError('Argument must not be a number')
13707 }
13708 return Buffer(arg, encodingOrOffset, length)
13709}
13710
13711SafeBuffer.alloc = function (size, fill, encoding) {
13712 if (typeof size !== 'number') {
13713 throw new TypeError('Argument must be a number')
13714 }
13715 var buf = Buffer(size)
13716 if (fill !== undefined) {
13717 if (typeof encoding === 'string') {
13718 buf.fill(fill, encoding)
13719 } else {
13720 buf.fill(fill)
13721 }
13722 } else {
13723 buf.fill(0)
13724 }
13725 return buf
13726}
13727
13728SafeBuffer.allocUnsafe = function (size) {
13729 if (typeof size !== 'number') {
13730 throw new TypeError('Argument must be a number')
13731 }
13732 return Buffer(size)
13733}
13734
13735SafeBuffer.allocUnsafeSlow = function (size) {
13736 if (typeof size !== 'number') {
13737 throw new TypeError('Argument must be a number')
13738 }
13739 return buffer.SlowBuffer(size)
13740}
13741
b777ff55 13742},{"buffer":5}],102:[function(require,module,exports){
9f59e99b
IC
13743var Buffer = require('safe-buffer').Buffer
13744
a0091a40
IC
13745// prototype class for hash functions
13746function Hash (blockSize, finalSize) {
9f59e99b 13747 this._block = Buffer.alloc(blockSize)
a0091a40
IC
13748 this._finalSize = finalSize
13749 this._blockSize = blockSize
13750 this._len = 0
a0091a40
IC
13751}
13752
13753Hash.prototype.update = function (data, enc) {
13754 if (typeof data === 'string') {
13755 enc = enc || 'utf8'
9f59e99b 13756 data = Buffer.from(data, enc)
a0091a40
IC
13757 }
13758
9f59e99b
IC
13759 var block = this._block
13760 var blockSize = this._blockSize
13761 var length = data.length
13762 var accum = this._len
a0091a40 13763
9f59e99b
IC
13764 for (var offset = 0; offset < length;) {
13765 var assigned = accum % blockSize
13766 var remainder = Math.min(length - offset, blockSize - assigned)
a0091a40 13767
9f59e99b
IC
13768 for (var i = 0; i < remainder; i++) {
13769 block[assigned + i] = data[offset + i]
a0091a40
IC
13770 }
13771
9f59e99b
IC
13772 accum += remainder
13773 offset += remainder
a0091a40 13774
9f59e99b
IC
13775 if ((accum % blockSize) === 0) {
13776 this._update(block)
a0091a40
IC
13777 }
13778 }
a0091a40 13779
9f59e99b 13780 this._len += length
a0091a40
IC
13781 return this
13782}
13783
13784Hash.prototype.digest = function (enc) {
9f59e99b 13785 var rem = this._len % this._blockSize
a0091a40 13786
9f59e99b 13787 this._block[rem] = 0x80
a0091a40 13788
9f59e99b
IC
13789 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
13790 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
13791 this._block.fill(0, rem + 1)
a0091a40 13792
9f59e99b 13793 if (rem >= this._finalSize) {
a0091a40
IC
13794 this._update(this._block)
13795 this._block.fill(0)
13796 }
13797
9f59e99b
IC
13798 var bits = this._len * 8
13799
13800 // uint32
13801 if (bits <= 0xffffffff) {
13802 this._block.writeUInt32BE(bits, this._blockSize - 4)
13803
13804 // uint64
13805 } else {
b777ff55 13806 var lowBits = (bits & 0xffffffff) >>> 0
9f59e99b
IC
13807 var highBits = (bits - lowBits) / 0x100000000
13808
13809 this._block.writeUInt32BE(highBits, this._blockSize - 8)
13810 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
13811 }
a0091a40 13812
9f59e99b
IC
13813 this._update(this._block)
13814 var hash = this._hash()
a0091a40
IC
13815
13816 return enc ? hash.toString(enc) : hash
13817}
13818
13819Hash.prototype._update = function () {
13820 throw new Error('_update must be implemented by subclass')
13821}
13822
13823module.exports = Hash
13824
b777ff55 13825},{"safe-buffer":101}],103:[function(require,module,exports){
a0091a40
IC
13826var exports = module.exports = function SHA (algorithm) {
13827 algorithm = algorithm.toLowerCase()
13828
13829 var Algorithm = exports[algorithm]
13830 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
13831
13832 return new Algorithm()
13833}
13834
13835exports.sha = require('./sha')
13836exports.sha1 = require('./sha1')
13837exports.sha224 = require('./sha224')
13838exports.sha256 = require('./sha256')
13839exports.sha384 = require('./sha384')
13840exports.sha512 = require('./sha512')
13841
b777ff55 13842},{"./sha":104,"./sha1":105,"./sha224":106,"./sha256":107,"./sha384":108,"./sha512":109}],104:[function(require,module,exports){
a0091a40
IC
13843/*
13844 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
13845 * in FIPS PUB 180-1
13846 * This source code is derived from sha1.js of the same repository.
13847 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
13848 * operation was added.
13849 */
13850
13851var inherits = require('inherits')
13852var Hash = require('./hash')
9f59e99b 13853var Buffer = require('safe-buffer').Buffer
a0091a40
IC
13854
13855var K = [
13856 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13857]
13858
13859var W = new Array(80)
13860
13861function Sha () {
13862 this.init()
13863 this._w = W
13864
13865 Hash.call(this, 64, 56)
13866}
13867
13868inherits(Sha, Hash)
13869
13870Sha.prototype.init = function () {
13871 this._a = 0x67452301
13872 this._b = 0xefcdab89
13873 this._c = 0x98badcfe
13874 this._d = 0x10325476
13875 this._e = 0xc3d2e1f0
13876
13877 return this
13878}
13879
13880function rotl5 (num) {
13881 return (num << 5) | (num >>> 27)
13882}
13883
13884function rotl30 (num) {
13885 return (num << 30) | (num >>> 2)
13886}
13887
13888function ft (s, b, c, d) {
13889 if (s === 0) return (b & c) | ((~b) & d)
13890 if (s === 2) return (b & c) | (b & d) | (c & d)
13891 return b ^ c ^ d
13892}
13893
13894Sha.prototype._update = function (M) {
13895 var W = this._w
13896
13897 var a = this._a | 0
13898 var b = this._b | 0
13899 var c = this._c | 0
13900 var d = this._d | 0
13901 var e = this._e | 0
13902
13903 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
13904 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
13905
13906 for (var j = 0; j < 80; ++j) {
13907 var s = ~~(j / 20)
13908 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
13909
13910 e = d
13911 d = c
13912 c = rotl30(b)
13913 b = a
13914 a = t
13915 }
13916
13917 this._a = (a + this._a) | 0
13918 this._b = (b + this._b) | 0
13919 this._c = (c + this._c) | 0
13920 this._d = (d + this._d) | 0
13921 this._e = (e + this._e) | 0
13922}
13923
13924Sha.prototype._hash = function () {
9f59e99b 13925 var H = Buffer.allocUnsafe(20)
a0091a40
IC
13926
13927 H.writeInt32BE(this._a | 0, 0)
13928 H.writeInt32BE(this._b | 0, 4)
13929 H.writeInt32BE(this._c | 0, 8)
13930 H.writeInt32BE(this._d | 0, 12)
13931 H.writeInt32BE(this._e | 0, 16)
13932
13933 return H
13934}
13935
13936module.exports = Sha
13937
b777ff55 13938},{"./hash":102,"inherits":96,"safe-buffer":101}],105:[function(require,module,exports){
a0091a40
IC
13939/*
13940 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
13941 * in FIPS PUB 180-1
13942 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
13943 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
13944 * Distributed under the BSD License
13945 * See http://pajhome.org.uk/crypt/md5 for details.
13946 */
13947
13948var inherits = require('inherits')
13949var Hash = require('./hash')
9f59e99b 13950var Buffer = require('safe-buffer').Buffer
a0091a40
IC
13951
13952var K = [
13953 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13954]
13955
13956var W = new Array(80)
13957
13958function Sha1 () {
13959 this.init()
13960 this._w = W
13961
13962 Hash.call(this, 64, 56)
13963}
13964
13965inherits(Sha1, Hash)
13966
13967Sha1.prototype.init = function () {
13968 this._a = 0x67452301
13969 this._b = 0xefcdab89
13970 this._c = 0x98badcfe
13971 this._d = 0x10325476
13972 this._e = 0xc3d2e1f0
13973
13974 return this
13975}
13976
13977function rotl1 (num) {
13978 return (num << 1) | (num >>> 31)
13979}
13980
13981function rotl5 (num) {
13982 return (num << 5) | (num >>> 27)
13983}
13984
13985function rotl30 (num) {
13986 return (num << 30) | (num >>> 2)
13987}
13988
13989function ft (s, b, c, d) {
13990 if (s === 0) return (b & c) | ((~b) & d)
13991 if (s === 2) return (b & c) | (b & d) | (c & d)
13992 return b ^ c ^ d
13993}
13994
13995Sha1.prototype._update = function (M) {
13996 var W = this._w
13997
13998 var a = this._a | 0
13999 var b = this._b | 0
14000 var c = this._c | 0
14001 var d = this._d | 0
14002 var e = this._e | 0
14003
14004 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
14005 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
14006
14007 for (var j = 0; j < 80; ++j) {
14008 var s = ~~(j / 20)
14009 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
14010
14011 e = d
14012 d = c
14013 c = rotl30(b)
14014 b = a
14015 a = t
14016 }
14017
14018 this._a = (a + this._a) | 0
14019 this._b = (b + this._b) | 0
14020 this._c = (c + this._c) | 0
14021 this._d = (d + this._d) | 0
14022 this._e = (e + this._e) | 0
14023}
14024
14025Sha1.prototype._hash = function () {
9f59e99b 14026 var H = Buffer.allocUnsafe(20)
a0091a40
IC
14027
14028 H.writeInt32BE(this._a | 0, 0)
14029 H.writeInt32BE(this._b | 0, 4)
14030 H.writeInt32BE(this._c | 0, 8)
14031 H.writeInt32BE(this._d | 0, 12)
14032 H.writeInt32BE(this._e | 0, 16)
14033
14034 return H
14035}
14036
14037module.exports = Sha1
14038
b777ff55 14039},{"./hash":102,"inherits":96,"safe-buffer":101}],106:[function(require,module,exports){
a0091a40
IC
14040/**
14041 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14042 * in FIPS 180-2
14043 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14044 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14045 *
14046 */
14047
14048var inherits = require('inherits')
14049var Sha256 = require('./sha256')
14050var Hash = require('./hash')
9f59e99b 14051var Buffer = require('safe-buffer').Buffer
a0091a40
IC
14052
14053var W = new Array(64)
14054
14055function Sha224 () {
14056 this.init()
14057
14058 this._w = W // new Array(64)
14059
14060 Hash.call(this, 64, 56)
14061}
14062
14063inherits(Sha224, Sha256)
14064
14065Sha224.prototype.init = function () {
14066 this._a = 0xc1059ed8
14067 this._b = 0x367cd507
14068 this._c = 0x3070dd17
14069 this._d = 0xf70e5939
14070 this._e = 0xffc00b31
14071 this._f = 0x68581511
14072 this._g = 0x64f98fa7
14073 this._h = 0xbefa4fa4
14074
14075 return this
14076}
14077
14078Sha224.prototype._hash = function () {
9f59e99b 14079 var H = Buffer.allocUnsafe(28)
a0091a40
IC
14080
14081 H.writeInt32BE(this._a, 0)
14082 H.writeInt32BE(this._b, 4)
14083 H.writeInt32BE(this._c, 8)
14084 H.writeInt32BE(this._d, 12)
14085 H.writeInt32BE(this._e, 16)
14086 H.writeInt32BE(this._f, 20)
14087 H.writeInt32BE(this._g, 24)
14088
14089 return H
14090}
14091
14092module.exports = Sha224
14093
b777ff55 14094},{"./hash":102,"./sha256":107,"inherits":96,"safe-buffer":101}],107:[function(require,module,exports){
a0091a40
IC
14095/**
14096 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14097 * in FIPS 180-2
14098 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14099 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14100 *
14101 */
14102
14103var inherits = require('inherits')
14104var Hash = require('./hash')
9f59e99b 14105var Buffer = require('safe-buffer').Buffer
a0091a40
IC
14106
14107var K = [
14108 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
14109 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
14110 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
14111 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
14112 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
14113 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
14114 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
14115 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
14116 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
14117 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
14118 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
14119 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
14120 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
14121 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
14122 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
14123 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
14124]
14125
14126var W = new Array(64)
14127
14128function Sha256 () {
14129 this.init()
14130
14131 this._w = W // new Array(64)
14132
14133 Hash.call(this, 64, 56)
14134}
14135
14136inherits(Sha256, Hash)
14137
14138Sha256.prototype.init = function () {
14139 this._a = 0x6a09e667
14140 this._b = 0xbb67ae85
14141 this._c = 0x3c6ef372
14142 this._d = 0xa54ff53a
14143 this._e = 0x510e527f
14144 this._f = 0x9b05688c
14145 this._g = 0x1f83d9ab
14146 this._h = 0x5be0cd19
14147
14148 return this
14149}
14150
14151function ch (x, y, z) {
14152 return z ^ (x & (y ^ z))
14153}
14154
14155function maj (x, y, z) {
14156 return (x & y) | (z & (x | y))
14157}
14158
14159function sigma0 (x) {
14160 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
14161}
14162
14163function sigma1 (x) {
14164 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
14165}
14166
14167function gamma0 (x) {
14168 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
14169}
14170
14171function gamma1 (x) {
14172 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
14173}
14174
14175Sha256.prototype._update = function (M) {
14176 var W = this._w
14177
14178 var a = this._a | 0
14179 var b = this._b | 0
14180 var c = this._c | 0
14181 var d = this._d | 0
14182 var e = this._e | 0
14183 var f = this._f | 0
14184 var g = this._g | 0
14185 var h = this._h | 0
14186
14187 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
14188 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
14189
14190 for (var j = 0; j < 64; ++j) {
14191 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
14192 var T2 = (sigma0(a) + maj(a, b, c)) | 0
14193
14194 h = g
14195 g = f
14196 f = e
14197 e = (d + T1) | 0
14198 d = c
14199 c = b
14200 b = a
14201 a = (T1 + T2) | 0
14202 }
14203
14204 this._a = (a + this._a) | 0
14205 this._b = (b + this._b) | 0
14206 this._c = (c + this._c) | 0
14207 this._d = (d + this._d) | 0
14208 this._e = (e + this._e) | 0
14209 this._f = (f + this._f) | 0
14210 this._g = (g + this._g) | 0
14211 this._h = (h + this._h) | 0
14212}
14213
14214Sha256.prototype._hash = function () {
9f59e99b 14215 var H = Buffer.allocUnsafe(32)
a0091a40
IC
14216
14217 H.writeInt32BE(this._a, 0)
14218 H.writeInt32BE(this._b, 4)
14219 H.writeInt32BE(this._c, 8)
14220 H.writeInt32BE(this._d, 12)
14221 H.writeInt32BE(this._e, 16)
14222 H.writeInt32BE(this._f, 20)
14223 H.writeInt32BE(this._g, 24)
14224 H.writeInt32BE(this._h, 28)
14225
14226 return H
14227}
14228
14229module.exports = Sha256
14230
b777ff55 14231},{"./hash":102,"inherits":96,"safe-buffer":101}],108:[function(require,module,exports){
a0091a40
IC
14232var inherits = require('inherits')
14233var SHA512 = require('./sha512')
14234var Hash = require('./hash')
9f59e99b 14235var Buffer = require('safe-buffer').Buffer
a0091a40
IC
14236
14237var W = new Array(160)
14238
14239function Sha384 () {
14240 this.init()
14241 this._w = W
14242
14243 Hash.call(this, 128, 112)
14244}
14245
14246inherits(Sha384, SHA512)
14247
14248Sha384.prototype.init = function () {
14249 this._ah = 0xcbbb9d5d
14250 this._bh = 0x629a292a
14251 this._ch = 0x9159015a
14252 this._dh = 0x152fecd8
14253 this._eh = 0x67332667
14254 this._fh = 0x8eb44a87
14255 this._gh = 0xdb0c2e0d
14256 this._hh = 0x47b5481d
14257
14258 this._al = 0xc1059ed8
14259 this._bl = 0x367cd507
14260 this._cl = 0x3070dd17
14261 this._dl = 0xf70e5939
14262 this._el = 0xffc00b31
14263 this._fl = 0x68581511
14264 this._gl = 0x64f98fa7
14265 this._hl = 0xbefa4fa4
14266
14267 return this
14268}
14269
14270Sha384.prototype._hash = function () {
9f59e99b 14271 var H = Buffer.allocUnsafe(48)
a0091a40
IC
14272
14273 function writeInt64BE (h, l, offset) {
14274 H.writeInt32BE(h, offset)
14275 H.writeInt32BE(l, offset + 4)
14276 }
14277
14278 writeInt64BE(this._ah, this._al, 0)
14279 writeInt64BE(this._bh, this._bl, 8)
14280 writeInt64BE(this._ch, this._cl, 16)
14281 writeInt64BE(this._dh, this._dl, 24)
14282 writeInt64BE(this._eh, this._el, 32)
14283 writeInt64BE(this._fh, this._fl, 40)
14284
14285 return H
14286}
14287
14288module.exports = Sha384
14289
b777ff55 14290},{"./hash":102,"./sha512":109,"inherits":96,"safe-buffer":101}],109:[function(require,module,exports){
a0091a40
IC
14291var inherits = require('inherits')
14292var Hash = require('./hash')
9f59e99b 14293var Buffer = require('safe-buffer').Buffer
a0091a40
IC
14294
14295var K = [
14296 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
14297 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
14298 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
14299 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
14300 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
14301 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
14302 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
14303 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
14304 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
14305 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
14306 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
14307 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
14308 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
14309 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
14310 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
14311 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
14312 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
14313 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
14314 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
14315 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
14316 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
14317 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
14318 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
14319 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
14320 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
14321 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
14322 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
14323 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
14324 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
14325 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
14326 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
14327 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
14328 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
14329 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
14330 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
14331 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
14332 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
14333 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
14334 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
14335 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
14336]
14337
14338var W = new Array(160)
14339
14340function Sha512 () {
14341 this.init()
14342 this._w = W
14343
14344 Hash.call(this, 128, 112)
14345}
14346
14347inherits(Sha512, Hash)
14348
14349Sha512.prototype.init = function () {
14350 this._ah = 0x6a09e667
14351 this._bh = 0xbb67ae85
14352 this._ch = 0x3c6ef372
14353 this._dh = 0xa54ff53a
14354 this._eh = 0x510e527f
14355 this._fh = 0x9b05688c
14356 this._gh = 0x1f83d9ab
14357 this._hh = 0x5be0cd19
14358
14359 this._al = 0xf3bcc908
14360 this._bl = 0x84caa73b
14361 this._cl = 0xfe94f82b
14362 this._dl = 0x5f1d36f1
14363 this._el = 0xade682d1
14364 this._fl = 0x2b3e6c1f
14365 this._gl = 0xfb41bd6b
14366 this._hl = 0x137e2179
14367
14368 return this
14369}
14370
14371function Ch (x, y, z) {
14372 return z ^ (x & (y ^ z))
14373}
14374
14375function maj (x, y, z) {
14376 return (x & y) | (z & (x | y))
14377}
14378
14379function sigma0 (x, xl) {
14380 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
14381}
14382
14383function sigma1 (x, xl) {
14384 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
14385}
14386
14387function Gamma0 (x, xl) {
14388 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
14389}
14390
14391function Gamma0l (x, xl) {
14392 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
14393}
14394
14395function Gamma1 (x, xl) {
14396 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
14397}
14398
14399function Gamma1l (x, xl) {
14400 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
14401}
14402
14403function getCarry (a, b) {
14404 return (a >>> 0) < (b >>> 0) ? 1 : 0
14405}
14406
14407Sha512.prototype._update = function (M) {
14408 var W = this._w
14409
14410 var ah = this._ah | 0
14411 var bh = this._bh | 0
14412 var ch = this._ch | 0
14413 var dh = this._dh | 0
14414 var eh = this._eh | 0
14415 var fh = this._fh | 0
14416 var gh = this._gh | 0
14417 var hh = this._hh | 0
14418
14419 var al = this._al | 0
14420 var bl = this._bl | 0
14421 var cl = this._cl | 0
14422 var dl = this._dl | 0
14423 var el = this._el | 0
14424 var fl = this._fl | 0
14425 var gl = this._gl | 0
14426 var hl = this._hl | 0
14427
14428 for (var i = 0; i < 32; i += 2) {
14429 W[i] = M.readInt32BE(i * 4)
14430 W[i + 1] = M.readInt32BE(i * 4 + 4)
14431 }
14432 for (; i < 160; i += 2) {
14433 var xh = W[i - 15 * 2]
14434 var xl = W[i - 15 * 2 + 1]
14435 var gamma0 = Gamma0(xh, xl)
14436 var gamma0l = Gamma0l(xl, xh)
14437
14438 xh = W[i - 2 * 2]
14439 xl = W[i - 2 * 2 + 1]
14440 var gamma1 = Gamma1(xh, xl)
14441 var gamma1l = Gamma1l(xl, xh)
14442
14443 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
14444 var Wi7h = W[i - 7 * 2]
14445 var Wi7l = W[i - 7 * 2 + 1]
14446
14447 var Wi16h = W[i - 16 * 2]
14448 var Wi16l = W[i - 16 * 2 + 1]
14449
14450 var Wil = (gamma0l + Wi7l) | 0
14451 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
14452 Wil = (Wil + gamma1l) | 0
14453 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
14454 Wil = (Wil + Wi16l) | 0
14455 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
14456
14457 W[i] = Wih
14458 W[i + 1] = Wil
14459 }
14460
14461 for (var j = 0; j < 160; j += 2) {
14462 Wih = W[j]
14463 Wil = W[j + 1]
14464
14465 var majh = maj(ah, bh, ch)
14466 var majl = maj(al, bl, cl)
14467
14468 var sigma0h = sigma0(ah, al)
14469 var sigma0l = sigma0(al, ah)
14470 var sigma1h = sigma1(eh, el)
14471 var sigma1l = sigma1(el, eh)
14472
14473 // t1 = h + sigma1 + ch + K[j] + W[j]
14474 var Kih = K[j]
14475 var Kil = K[j + 1]
14476
14477 var chh = Ch(eh, fh, gh)
14478 var chl = Ch(el, fl, gl)
14479
14480 var t1l = (hl + sigma1l) | 0
14481 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
14482 t1l = (t1l + chl) | 0
14483 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
14484 t1l = (t1l + Kil) | 0
14485 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
14486 t1l = (t1l + Wil) | 0
14487 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
14488
14489 // t2 = sigma0 + maj
14490 var t2l = (sigma0l + majl) | 0
14491 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
14492
14493 hh = gh
14494 hl = gl
14495 gh = fh
14496 gl = fl
14497 fh = eh
14498 fl = el
14499 el = (dl + t1l) | 0
14500 eh = (dh + t1h + getCarry(el, dl)) | 0
14501 dh = ch
14502 dl = cl
14503 ch = bh
14504 cl = bl
14505 bh = ah
14506 bl = al
14507 al = (t1l + t2l) | 0
14508 ah = (t1h + t2h + getCarry(al, t1l)) | 0
14509 }
14510
14511 this._al = (this._al + al) | 0
14512 this._bl = (this._bl + bl) | 0
14513 this._cl = (this._cl + cl) | 0
14514 this._dl = (this._dl + dl) | 0
14515 this._el = (this._el + el) | 0
14516 this._fl = (this._fl + fl) | 0
14517 this._gl = (this._gl + gl) | 0
14518 this._hl = (this._hl + hl) | 0
14519
14520 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
14521 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
14522 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
14523 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
14524 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
14525 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
14526 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
14527 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
14528}
14529
14530Sha512.prototype._hash = function () {
9f59e99b 14531 var H = Buffer.allocUnsafe(64)
a0091a40
IC
14532
14533 function writeInt64BE (h, l, offset) {
14534 H.writeInt32BE(h, offset)
14535 H.writeInt32BE(l, offset + 4)
14536 }
14537
14538 writeInt64BE(this._ah, this._al, 0)
14539 writeInt64BE(this._bh, this._bl, 8)
14540 writeInt64BE(this._ch, this._cl, 16)
14541 writeInt64BE(this._dh, this._dl, 24)
14542 writeInt64BE(this._eh, this._el, 32)
14543 writeInt64BE(this._fh, this._fl, 40)
14544 writeInt64BE(this._gh, this._gl, 48)
14545 writeInt64BE(this._hh, this._hl, 56)
14546
14547 return H
14548}
14549
14550module.exports = Sha512
14551
b777ff55 14552},{"./hash":102,"inherits":96,"safe-buffer":101}],110:[function(require,module,exports){
a0091a40
IC
14553var native = require('./native')
14554
a0091a40
IC
14555function getTypeName (fn) {
14556 return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1]
14557}
14558
14559function getValueTypeName (value) {
14560 return native.Nil(value) ? '' : getTypeName(value.constructor)
14561}
14562
14563function getValue (value) {
14564 if (native.Function(value)) return ''
14565 if (native.String(value)) return JSON.stringify(value)
14566 if (value && native.Object(value)) return ''
14567 return value
14568}
14569
14570function tfJSON (type) {
14571 if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type)
14572 if (native.Array(type)) return 'Array'
14573 if (type && native.Object(type)) return 'Object'
14574
14575 return type !== undefined ? type : ''
14576}
14577
14578function tfErrorString (type, value, valueTypeName) {
14579 var valueJson = getValue(value)
14580
14581 return 'Expected ' + tfJSON(type) + ', got' +
14582 (valueTypeName !== '' ? ' ' + valueTypeName : '') +
14583 (valueJson !== '' ? ' ' + valueJson : '')
14584}
14585
9f59e99b
IC
14586function TfTypeError (type, value, valueTypeName) {
14587 valueTypeName = valueTypeName || getValueTypeName(value)
14588 this.message = tfErrorString(type, value, valueTypeName)
14589
14590 Error.captureStackTrace(this, TfTypeError)
14591 this.__type = type
14592 this.__value = value
14593 this.__valueTypeName = valueTypeName
14594}
14595
14596TfTypeError.prototype = Object.create(Error.prototype)
14597TfTypeError.prototype.constructor = TfTypeError
14598
a0091a40
IC
14599function tfPropertyErrorString (type, label, name, value, valueTypeName) {
14600 var description = '" of type '
14601 if (label === 'key') description = '" with key type '
14602
14603 return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName)
14604}
14605
9f59e99b
IC
14606function TfPropertyTypeError (type, property, label, value, valueTypeName) {
14607 if (type) {
14608 valueTypeName = valueTypeName || getValueTypeName(value)
14609 this.message = tfPropertyErrorString(type, label, property, value, valueTypeName)
14610 } else {
14611 this.message = 'Unexpected property "' + property + '"'
14612 }
14613
14614 Error.captureStackTrace(this, TfTypeError)
14615 this.__label = label
14616 this.__property = property
14617 this.__type = type
14618 this.__value = value
14619 this.__valueTypeName = valueTypeName
14620}
14621
14622TfPropertyTypeError.prototype = Object.create(Error.prototype)
14623TfPropertyTypeError.prototype.constructor = TfTypeError
14624
14625function tfCustomError (expected, actual) {
14626 return new TfTypeError(expected, {}, actual)
14627}
14628
14629function tfSubError (e, property, label) {
14630 // sub child?
14631 if (e instanceof TfPropertyTypeError) {
14632 property = property + '.' + e.__property
14633
14634 e = new TfPropertyTypeError(
14635 e.__type, property, e.__label, e.__value, e.__valueTypeName
14636 )
14637
14638 // child?
14639 } else if (e instanceof TfTypeError) {
14640 e = new TfPropertyTypeError(
14641 e.__type, property, label, e.__value, e.__valueTypeName
14642 )
14643 }
14644
14645 Error.captureStackTrace(e)
14646 return e
14647}
14648
a0091a40
IC
14649module.exports = {
14650 TfTypeError: TfTypeError,
14651 TfPropertyTypeError: TfPropertyTypeError,
14652 tfCustomError: tfCustomError,
14653 tfSubError: tfSubError,
14654 tfJSON: tfJSON,
14655 getValueTypeName: getValueTypeName
14656}
14657
b777ff55 14658},{"./native":113}],111:[function(require,module,exports){
a0091a40
IC
14659(function (Buffer){
14660var NATIVE = require('./native')
14661var ERRORS = require('./errors')
14662
14663function _Buffer (value) {
14664 return Buffer.isBuffer(value)
14665}
14666
14667function Hex (value) {
14668 return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value)
14669}
14670
14671function _LengthN (type, length) {
14672 var name = type.toJSON()
14673
14674 function Length (value) {
14675 if (!type(value)) return false
14676 if (value.length === length) return true
14677
14678 throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')')
14679 }
14680 Length.toJSON = function () { return name }
14681
14682 return Length
14683}
14684
14685var _ArrayN = _LengthN.bind(null, NATIVE.Array)
14686var _BufferN = _LengthN.bind(null, _Buffer)
14687var _HexN = _LengthN.bind(null, Hex)
9f59e99b 14688var _StringN = _LengthN.bind(null, NATIVE.String)
a0091a40
IC
14689
14690var UINT53_MAX = Math.pow(2, 53) - 1
14691
14692function Finite (value) {
14693 return typeof value === 'number' && isFinite(value)
14694}
14695function Int8 (value) { return ((value << 24) >> 24) === value }
14696function Int16 (value) { return ((value << 16) >> 16) === value }
14697function Int32 (value) { return (value | 0) === value }
14698function UInt8 (value) { return (value & 0xff) === value }
14699function UInt16 (value) { return (value & 0xffff) === value }
14700function UInt32 (value) { return (value >>> 0) === value }
14701function UInt53 (value) {
14702 return typeof value === 'number' &&
14703 value >= 0 &&
14704 value <= UINT53_MAX &&
14705 Math.floor(value) === value
14706}
14707
14708var types = {
14709 ArrayN: _ArrayN,
14710 Buffer: _Buffer,
14711 BufferN: _BufferN,
14712 Finite: Finite,
14713 Hex: Hex,
14714 HexN: _HexN,
14715 Int8: Int8,
14716 Int16: Int16,
14717 Int32: Int32,
9f59e99b 14718 StringN: _StringN,
a0091a40
IC
14719 UInt8: UInt8,
14720 UInt16: UInt16,
14721 UInt32: UInt32,
14722 UInt53: UInt53
14723}
14724
14725for (var typeName in types) {
14726 types[typeName].toJSON = function (t) {
14727 return t
14728 }.bind(null, typeName)
14729}
14730
14731module.exports = types
14732
14733}).call(this,{"isBuffer":require("../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
b777ff55 14734},{"../../../../../.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){
a0091a40
IC
14735var ERRORS = require('./errors')
14736var NATIVE = require('./native')
14737
14738// short-hand
14739var tfJSON = ERRORS.tfJSON
14740var TfTypeError = ERRORS.TfTypeError
14741var TfPropertyTypeError = ERRORS.TfPropertyTypeError
14742var tfSubError = ERRORS.tfSubError
14743var getValueTypeName = ERRORS.getValueTypeName
14744
14745var TYPES = {
14746 arrayOf: function arrayOf (type) {
14747 type = compile(type)
14748
14749 function _arrayOf (array, strict) {
14750 if (!NATIVE.Array(array)) return false
9f59e99b 14751 if (NATIVE.Nil(array)) return false
a0091a40
IC
14752
14753 return array.every(function (value, i) {
14754 try {
14755 return typeforce(type, value, strict)
14756 } catch (e) {
14757 throw tfSubError(e, i)
14758 }
14759 })
14760 }
14761 _arrayOf.toJSON = function () { return '[' + tfJSON(type) + ']' }
14762
14763 return _arrayOf
14764 },
14765
14766 maybe: function maybe (type) {
14767 type = compile(type)
14768
14769 function _maybe (value, strict) {
14770 return NATIVE.Nil(value) || type(value, strict, maybe)
14771 }
14772 _maybe.toJSON = function () { return '?' + tfJSON(type) }
14773
14774 return _maybe
14775 },
14776
14777 map: function map (propertyType, propertyKeyType) {
14778 propertyType = compile(propertyType)
14779 if (propertyKeyType) propertyKeyType = compile(propertyKeyType)
14780
14781 function _map (value, strict) {
9f59e99b
IC
14782 if (!NATIVE.Object(value)) return false
14783 if (NATIVE.Nil(value)) return false
a0091a40
IC
14784
14785 for (var propertyName in value) {
14786 try {
14787 if (propertyKeyType) {
14788 typeforce(propertyKeyType, propertyName, strict)
14789 }
14790 } catch (e) {
14791 throw tfSubError(e, propertyName, 'key')
14792 }
14793
14794 try {
14795 var propertyValue = value[propertyName]
14796 typeforce(propertyType, propertyValue, strict)
14797 } catch (e) {
14798 throw tfSubError(e, propertyName)
14799 }
14800 }
14801
14802 return true
14803 }
14804
14805 if (propertyKeyType) {
14806 _map.toJSON = function () {
14807 return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}'
14808 }
14809 } else {
14810 _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' }
14811 }
14812
14813 return _map
14814 },
14815
14816 object: function object (uncompiled) {
14817 var type = {}
14818
14819 for (var typePropertyName in uncompiled) {
14820 type[typePropertyName] = compile(uncompiled[typePropertyName])
14821 }
14822
14823 function _object (value, strict) {
14824 if (!NATIVE.Object(value)) return false
14825 if (NATIVE.Nil(value)) return false
14826
14827 var propertyName
14828
14829 try {
14830 for (propertyName in type) {
14831 var propertyType = type[propertyName]
14832 var propertyValue = value[propertyName]
14833
14834 typeforce(propertyType, propertyValue, strict)
14835 }
14836 } catch (e) {
14837 throw tfSubError(e, propertyName)
14838 }
14839
14840 if (strict) {
14841 for (propertyName in value) {
14842 if (type[propertyName]) continue
14843
14844 throw new TfPropertyTypeError(undefined, propertyName)
14845 }
14846 }
14847
14848 return true
14849 }
14850 _object.toJSON = function () { return tfJSON(type) }
14851
14852 return _object
14853 },
14854
14855 oneOf: function oneOf () {
14856 var types = [].slice.call(arguments).map(compile)
14857
14858 function _oneOf (value, strict) {
14859 return types.some(function (type) {
14860 try {
14861 return typeforce(type, value, strict)
14862 } catch (e) {
14863 return false
14864 }
14865 })
14866 }
14867 _oneOf.toJSON = function () { return types.map(tfJSON).join('|') }
14868
14869 return _oneOf
14870 },
14871
14872 quacksLike: function quacksLike (type) {
14873 function _quacksLike (value) {
14874 return type === getValueTypeName(value)
14875 }
14876 _quacksLike.toJSON = function () { return type }
14877
14878 return _quacksLike
14879 },
14880
14881 tuple: function tuple () {
14882 var types = [].slice.call(arguments).map(compile)
14883
14884 function _tuple (values, strict) {
9f59e99b
IC
14885 if (NATIVE.Nil(values)) return false
14886 if (NATIVE.Nil(values.length)) return false
14887 if (strict && (values.length !== types.length)) return false
14888
a0091a40
IC
14889 return types.every(function (type, i) {
14890 try {
14891 return typeforce(type, values[i], strict)
14892 } catch (e) {
14893 throw tfSubError(e, i)
14894 }
9f59e99b 14895 })
a0091a40
IC
14896 }
14897 _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' }
14898
14899 return _tuple
14900 },
14901
14902 value: function value (expected) {
14903 function _value (actual) {
14904 return actual === expected
14905 }
14906 _value.toJSON = function () { return expected }
14907
14908 return _value
14909 }
14910}
14911
14912function compile (type) {
14913 if (NATIVE.String(type)) {
9f59e99b 14914 if (type[0] === '?') return TYPES.maybe(type.slice(1))
a0091a40
IC
14915
14916 return NATIVE[type] || TYPES.quacksLike(type)
14917 } else if (type && NATIVE.Object(type)) {
9f59e99b 14918 if (NATIVE.Array(type)) return TYPES.arrayOf(type[0])
a0091a40
IC
14919
14920 return TYPES.object(type)
14921 } else if (NATIVE.Function(type)) {
14922 return type
14923 }
14924
14925 return TYPES.value(type)
14926}
14927
14928function typeforce (type, value, strict, surrogate) {
14929 if (NATIVE.Function(type)) {
14930 if (type(value, strict)) return true
14931
14932 throw new TfTypeError(surrogate || type, value)
14933 }
14934
14935 // JIT
14936 return typeforce(compile(type), value, strict)
14937}
14938
14939// assign types to typeforce function
14940for (var typeName in NATIVE) {
14941 typeforce[typeName] = NATIVE[typeName]
14942}
14943
14944for (typeName in TYPES) {
14945 typeforce[typeName] = TYPES[typeName]
14946}
14947
14948var EXTRA = require('./extra')
14949for (typeName in EXTRA) {
14950 typeforce[typeName] = EXTRA[typeName]
14951}
14952
14953// async wrapper
14954function __async (type, value, strict, callback) {
14955 // default to falsy strict if using shorthand overload
14956 if (typeof strict === 'function') return __async(type, value, false, strict)
14957
14958 try {
14959 typeforce(type, value, strict)
14960 } catch (e) {
14961 return callback(e)
14962 }
14963
14964 callback()
14965}
14966
14967typeforce.async = __async
14968typeforce.compile = compile
14969typeforce.TfTypeError = TfTypeError
14970typeforce.TfPropertyTypeError = TfPropertyTypeError
14971
14972module.exports = typeforce
14973
b777ff55 14974},{"./errors":110,"./extra":111,"./native":113}],113:[function(require,module,exports){
a0091a40
IC
14975var types = {
14976 Array: function (value) { return value !== null && value !== undefined && value.constructor === Array },
14977 Boolean: function (value) { return typeof value === 'boolean' },
14978 Function: function (value) { return typeof value === 'function' },
14979 Nil: function (value) { return value === undefined || value === null },
14980 Number: function (value) { return typeof value === 'number' },
14981 Object: function (value) { return typeof value === 'object' },
14982 String: function (value) { return typeof value === 'string' },
14983 '': function () { return true }
14984}
14985
14986// TODO: deprecate
14987types.Null = types.Nil
14988
14989for (var typeName in types) {
14990 types[typeName].toJSON = function (t) {
14991 return t
14992 }.bind(null, typeName)
14993}
14994
14995module.exports = types
14996
b777ff55 14997},{}],114:[function(require,module,exports){
a0091a40 14998'use strict'
b777ff55 14999var Buffer = require('safe-buffer').Buffer
a0091a40
IC
15000
15001// Number.MAX_SAFE_INTEGER
15002var MAX_SAFE_INTEGER = 9007199254740991
15003
15004function checkUInt53 (n) {
15005 if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range')
15006}
15007
15008function encode (number, buffer, offset) {
15009 checkUInt53(number)
15010
b777ff55 15011 if (!buffer) buffer = Buffer.allocUnsafe(encodingLength(number))
a0091a40
IC
15012 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
15013 if (!offset) offset = 0
15014
15015 // 8 bit
15016 if (number < 0xfd) {
15017 buffer.writeUInt8(number, offset)
15018 encode.bytes = 1
15019
15020 // 16 bit
15021 } else if (number <= 0xffff) {
15022 buffer.writeUInt8(0xfd, offset)
15023 buffer.writeUInt16LE(number, offset + 1)
15024 encode.bytes = 3
15025
15026 // 32 bit
15027 } else if (number <= 0xffffffff) {
15028 buffer.writeUInt8(0xfe, offset)
15029 buffer.writeUInt32LE(number, offset + 1)
15030 encode.bytes = 5
15031
15032 // 64 bit
15033 } else {
15034 buffer.writeUInt8(0xff, offset)
15035 buffer.writeUInt32LE(number >>> 0, offset + 1)
15036 buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5)
15037 encode.bytes = 9
15038 }
15039
15040 return buffer
15041}
15042
15043function decode (buffer, offset) {
15044 if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance')
15045 if (!offset) offset = 0
15046
15047 var first = buffer.readUInt8(offset)
15048
15049 // 8 bit
15050 if (first < 0xfd) {
15051 decode.bytes = 1
15052 return first
15053
15054 // 16 bit
15055 } else if (first === 0xfd) {
15056 decode.bytes = 3
15057 return buffer.readUInt16LE(offset + 1)
15058
15059 // 32 bit
15060 } else if (first === 0xfe) {
15061 decode.bytes = 5
15062 return buffer.readUInt32LE(offset + 1)
15063
15064 // 64 bit
15065 } else {
15066 decode.bytes = 9
15067 var lo = buffer.readUInt32LE(offset + 1)
15068 var hi = buffer.readUInt32LE(offset + 5)
15069 var number = hi * 0x0100000000 + lo
15070 checkUInt53(number)
15071
15072 return number
15073 }
15074}
15075
15076function encodingLength (number) {
15077 checkUInt53(number)
15078
15079 return (
15080 number < 0xfd ? 1
15081 : number <= 0xffff ? 3
15082 : number <= 0xffffffff ? 5
15083 : 9
15084 )
15085}
15086
15087module.exports = { encode: encode, decode: decode, encodingLength: encodingLength }
15088
b777ff55 15089},{"safe-buffer":101}],115:[function(require,module,exports){
a0091a40
IC
15090(function (Buffer){
15091var bs58check = require('bs58check')
15092
15093function decodeRaw (buffer, version) {
15094 // check version only if defined
15095 if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version')
15096
15097 // uncompressed
15098 if (buffer.length === 33) {
15099 return {
15100 version: buffer[0],
15101 privateKey: buffer.slice(1, 33),
15102 compressed: false
15103 }
15104 }
15105
15106 // invalid length
15107 if (buffer.length !== 34) throw new Error('Invalid WIF length')
15108
15109 // invalid compression flag
15110 if (buffer[33] !== 0x01) throw new Error('Invalid compression flag')
15111
15112 return {
15113 version: buffer[0],
15114 privateKey: buffer.slice(1, 33),
15115 compressed: true
15116 }
15117}
15118
15119function encodeRaw (version, privateKey, compressed) {
15120 var result = new Buffer(compressed ? 34 : 33)
15121
15122 result.writeUInt8(version, 0)
15123 privateKey.copy(result, 1)
15124
15125 if (compressed) {
15126 result[33] = 0x01
15127 }
15128
15129 return result
15130}
15131
15132function decode (string, version) {
15133 return decodeRaw(bs58check.decode(string), version)
15134}
15135
15136function encode (version, privateKey, compressed) {
15137 if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed))
15138
15139 return bs58check.encode(
15140 encodeRaw(
15141 version.version,
15142 version.privateKey,
15143 version.compressed
15144 )
15145 )
15146}
15147
15148module.exports = {
15149 decode: decode,
15150 decodeRaw: decodeRaw,
15151 encode: encode,
15152 encodeRaw: encodeRaw
15153}
15154
15155}).call(this,require("buffer").Buffer)
b777ff55 15156},{"bs58check":83,"buffer":5}]},{},[34])(34)
9f59e99b 15157});