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
){
5 // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
9 * The buffer module from node.js, for the browser.
11 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
14 function compare(a
, b
) {
22 for (var i
= 0, len
= Math
.min(x
, y
); i
< len
; ++i
) {
38 function isBuffer(b
) {
39 if (global
.Buffer
&& typeof global
.Buffer
.isBuffer
=== 'function') {
40 return global
.Buffer
.isBuffer(b
);
42 return !!(b
!= null && b
._isBuffer
);
45 // based on node assert, original notice:
47 // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
49 // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
51 // Originally from narwhal.js (http://narwhaljs.org)
52 // Copyright (c) 2009 Thomas Robinson <280north.com>
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:
61 // The above copyright notice and this permission notice shall be included in
62 // all copies or substantial portions of the Software.
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.
71 var util
= require('util/');
72 var hasOwn
= Object
.prototype.hasOwnProperty
;
73 var pSlice
= Array
.prototype.slice
;
74 var functionsHaveNames
= (function () {
75 return function foo() {}.name
=== 'foo';
77 function pToString (obj
) {
78 return Object
.prototype.toString
.call(obj
);
80 function isView(arrbuf
) {
81 if (isBuffer(arrbuf
)) {
84 if (typeof global
.ArrayBuffer
!== 'function') {
87 if (typeof ArrayBuffer
.isView
=== 'function') {
88 return ArrayBuffer
.isView(arrbuf
);
93 if (arrbuf
instanceof DataView
) {
96 if (arrbuf
.buffer
&& arrbuf
.buffer
instanceof ArrayBuffer
) {
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.
105 var assert
= module
.exports
= ok
;
107 // 2. The AssertionError is defined in assert.
108 // new assert.AssertionError({ message: message,
110 // expected: expected })
112 var regex
= /\s*function\s+([^\(\s]*)\s*/;
113 // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
114 function getName(func
) {
115 if (!util
.isFunction(func
)) {
118 if (functionsHaveNames
) {
121 var str
= func
.toString();
122 var match
= str
.match(regex
);
123 return match
&& match
[1];
125 assert
.AssertionError
= function AssertionError(options
) {
126 this.name
= 'AssertionError';
127 this.actual
= options
.actual
;
128 this.expected
= options
.expected
;
129 this.operator
= options
.operator
;
130 if (options
.message
) {
131 this.message
= options
.message
;
132 this.generatedMessage
= false;
134 this.message
= getMessage(this);
135 this.generatedMessage
= true;
137 var stackStartFunction
= options
.stackStartFunction
|| fail
;
138 if (Error
.captureStackTrace
) {
139 Error
.captureStackTrace(this, stackStartFunction
);
141 // non v8 browsers so we can have a stacktrace
142 var err
= new Error();
146 // try to strip useless frames
147 var fn_name
= getName(stackStartFunction
);
148 var idx
= out
.indexOf('\n' + fn_name
);
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);
161 // assert.AssertionError instanceof Error
162 util
.inherits(assert
.AssertionError
, Error
);
164 function truncate(s
, n
) {
165 if (typeof s
=== 'string') {
166 return s
.length
< n
? s : s
.slice(0, n
);
171 function inspect(something
) {
172 if (functionsHaveNames
|| !util
.isFunction(something
)) {
173 return util
.inspect(something
);
175 var rawname
= getName(something
);
176 var name
= rawname
? ': ' + rawname : '';
177 return '[Function' + name
+ ']';
179 function getMessage(self
) {
180 return truncate(inspect(self
.actual
), 128) + ' ' +
181 self
.operator
+ ' ' +
182 truncate(inspect(self
.expected
), 128);
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
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
196 function fail(actual
, expected
, message
, operator
, stackStartFunction
) {
197 throw new assert
.AssertionError({
202 stackStartFunction: stackStartFunction
206 // EXTENSION! allows for well behaved errors defined elsewhere.
209 // 4. Pure assertion tests whether a value is truthy, as determined
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);.
216 function ok(value
, message
) {
217 if (!value
) fail(value
, true, message
, '==', assert
.ok
);
221 // 5. The equality assertion tests shallow, coercive equality with
223 // assert.equal(actual, expected, message_opt);
225 assert
.equal
= function equal(actual
, expected
, message
) {
226 if (actual
!= expected
) fail(actual
, expected
, message
, '==', assert
.equal
);
229 // 6. The non-equality assertion tests for whether two objects are not equal
230 // with != assert.notEqual(actual, expected, message_opt);
232 assert
.notEqual
= function notEqual(actual
, expected
, message
) {
233 if (actual
== expected
) {
234 fail(actual
, expected
, message
, '!=', assert
.notEqual
);
238 // 7. The equivalence assertion tests a deep equality relation.
239 // assert.deepEqual(actual, expected, message_opt);
241 assert
.deepEqual
= function deepEqual(actual
, expected
, message
) {
242 if (!_deepEqual(actual
, expected
, false)) {
243 fail(actual
, expected
, message
, 'deepEqual', assert
.deepEqual
);
247 assert
.deepStrictEqual
= function deepStrictEqual(actual
, expected
, message
) {
248 if (!_deepEqual(actual
, expected
, true)) {
249 fail(actual
, expected
, message
, 'deepStrictEqual', assert
.deepStrictEqual
);
253 function _deepEqual(actual
, expected
, strict
, memos
) {
254 // 7.1. All identical values are equivalent, as determined by ===.
255 if (actual
=== expected
) {
257 } else if (isBuffer(actual
) && isBuffer(expected
)) {
258 return compare(actual
, expected
) === 0;
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();
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
;
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
;
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;
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
)) {
303 memos
= memos
|| {actual: [], expected: []};
305 var actualIndex
= memos
.actual
.indexOf(actual
);
306 if (actualIndex
!== -1) {
307 if (actualIndex
=== memos
.expected
.indexOf(expected
)) {
312 memos
.actual
.push(actual
);
313 memos
.expected
.push(expected
);
315 return objEquiv(actual
, expected
, strict
, memos
);
319 function isArguments(object
) {
320 return Object
.prototype.toString
.call(object
) == '[object Arguments]';
323 function objEquiv(a
, b
, strict
, actualVisitedObjects
) {
324 if (a
=== null || a
=== undefined || b
=== null || b
=== undefined)
326 // if one is a primitive, the other must be same
327 if (util
.isPrimitive(a
) || util
.isPrimitive(b
))
329 if (strict
&& Object
.getPrototypeOf(a
) !== Object
.getPrototypeOf(b
))
331 var aIsArgs
= isArguments(a
);
332 var bIsArgs
= isArguments(b
);
333 if ((aIsArgs
&& !bIsArgs
) || (!aIsArgs
&& bIsArgs
))
338 return _deepEqual(a
, b
, strict
);
340 var ka
= objectKeys(a
);
341 var kb
= objectKeys(b
);
343 // having the same number of owned properties (keys incorporates
345 if (ka
.length
!== kb
.length
)
347 //the same set of keys (although not necessarily the same order),
351 for (i
= ka
.length
- 1; i
>= 0; i
--) {
355 //equivalent values for every corresponding key, and
356 //~~~possibly expensive deep test
357 for (i
= ka
.length
- 1; i
>= 0; i
--) {
359 if (!_deepEqual(a
[key
], b
[key
], strict
, actualVisitedObjects
))
365 // 8. The non-equivalence assertion tests for any deep inequality.
366 // assert.notDeepEqual(actual, expected, message_opt);
368 assert
.notDeepEqual
= function notDeepEqual(actual
, expected
, message
) {
369 if (_deepEqual(actual
, expected
, false)) {
370 fail(actual
, expected
, message
, 'notDeepEqual', assert
.notDeepEqual
);
374 assert
.notDeepStrictEqual
= notDeepStrictEqual
;
375 function notDeepStrictEqual(actual
, expected
, message
) {
376 if (_deepEqual(actual
, expected
, true)) {
377 fail(actual
, expected
, message
, 'notDeepStrictEqual', notDeepStrictEqual
);
382 // 9. The strict equality assertion tests strict equality, as determined by ===.
383 // assert.strictEqual(actual, expected, message_opt);
385 assert
.strictEqual
= function strictEqual(actual
, expected
, message
) {
386 if (actual
!== expected
) {
387 fail(actual
, expected
, message
, '===', assert
.strictEqual
);
391 // 10. The strict non-equality assertion tests for strict inequality, as
392 // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
394 assert
.notStrictEqual
= function notStrictEqual(actual
, expected
, message
) {
395 if (actual
=== expected
) {
396 fail(actual
, expected
, message
, '!==', assert
.notStrictEqual
);
400 function expectedException(actual
, expected
) {
401 if (!actual
|| !expected
) {
405 if (Object
.prototype.toString
.call(expected
) == '[object RegExp]') {
406 return expected
.test(actual
);
410 if (actual
instanceof expected
) {
414 // Ignore. The instanceof check doesn't work for arrow functions.
417 if (Error
.isPrototypeOf(expected
)) {
421 return expected
.call({}, actual
) === true;
424 function _tryBlock(block
) {
434 function _throws(shouldThrow
, block
, expected
, message
) {
437 if (typeof block
!== 'function') {
438 throw new TypeError('"block" argument must be a function');
441 if (typeof expected
=== 'string') {
446 actual
= _tryBlock(block
);
448 message
= (expected
&& expected
.name
? ' (' + expected
.name
+ ').' : '.') +
449 (message
? ' ' + message : '.');
451 if (shouldThrow
&& !actual
) {
452 fail(actual
, expected
, 'Missing expected exception' + message
);
455 var userProvidedMessage
= typeof message
=== 'string';
456 var isUnwantedException
= !shouldThrow
&& util
.isError(actual
);
457 var isUnexpectedException
= !shouldThrow
&& actual
&& !expected
;
459 if ((isUnwantedException
&&
460 userProvidedMessage
&&
461 expectedException(actual
, expected
)) ||
462 isUnexpectedException
) {
463 fail(actual
, expected
, 'Got unwanted exception' + message
);
466 if ((shouldThrow
&& actual
&& expected
&&
467 !expectedException(actual
, expected
)) || (!shouldThrow
&& actual
)) {
472 // 11. Expected to throw an error:
473 // assert.throws(block, Error_opt, message_opt);
475 assert
.throws = function(block
, /*optional*/error
, /*optional*/message
) {
476 _throws(true, block
, error
, message
);
479 // EXTENSION! This is annoying to write outside this module.
480 assert
.doesNotThrow = function(block
, /*optional*/error
, /*optional*/message
) {
481 _throws(false, block
, error
, message
);
484 assert
.ifError = function(err
) { if (err
) throw err
; };
486 var objectKeys
= Object
.keys
|| function (obj
) {
488 for (var key
in obj
) {
489 if (hasOwn
.call(obj
, key
)) keys
.push(key
);
494 }).call(this,typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
495 },{"util/":33}],2:[function(require
,module
,exports
){
498 exports
.byteLength
= byteLength
499 exports
.toByteArray
= toByteArray
500 exports
.fromByteArray
= fromByteArray
504 var Arr
= typeof Uint8Array
!== 'undefined' ? Uint8Array : Array
506 var code
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
507 for (var i
= 0, len
= code
.length
; i
< len
; ++i
) {
509 revLookup
[code
.charCodeAt(i
)] = i
512 revLookup
['-'.charCodeAt(0)] = 62
513 revLookup
['_'.charCodeAt(0)] = 63
515 function placeHoldersCount (b64
) {
518 throw new Error('Invalid string. Length must be a multiple of 4')
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
529 function byteLength (b64
) {
530 // base64 is 4/3 + up to two characters of the original data
531 return b64
.length
* 3 / 4 - placeHoldersCount(b64
)
534 function toByteArray (b64
) {
535 var i
, j
, l
, tmp
, placeHolders
, arr
537 placeHolders
= placeHoldersCount(b64
)
539 arr
= new Arr(len
* 3 / 4 - placeHolders
)
541 // if there are placeholders, only get up to the last complete 4 chars
542 l
= placeHolders
> 0 ? len
- 4 : len
546 for (i
= 0, j
= 0; i
< l
; i
+= 4, j
+= 3) {
547 tmp
= (revLookup
[b64
.charCodeAt(i
)] << 18) | (revLookup
[b64
.charCodeAt(i
+ 1)] << 12) | (revLookup
[b64
.charCodeAt(i
+ 2)] << 6) | revLookup
[b64
.charCodeAt(i
+ 3)]
548 arr
[L
++] = (tmp
>> 16) & 0xFF
549 arr
[L
++] = (tmp
>> 8) & 0xFF
550 arr
[L
++] = tmp
& 0xFF
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
565 function tripletToBase64 (num
) {
566 return lookup
[num
>> 18 & 0x3F] + lookup
[num
>> 12 & 0x3F] + lookup
[num
>> 6 & 0x3F] + lookup
[num
& 0x3F]
569 function encodeChunk (uint8
, start
, end
) {
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
))
576 return output
.join('')
579 function fromByteArray (uint8
) {
581 var len
= uint8
.length
582 var extraBytes
= len
% 3 // if we have 1 byte left, pad 2 bytes
585 var maxChunkLength
= 16383 // must be multiple of 3
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
)))
592 // pad the end with zeros, but make sure to not forget the extra bytes
593 if (extraBytes
=== 1) {
595 output
+= lookup
[tmp
>> 2]
596 output
+= lookup
[(tmp
<< 4) & 0x3F]
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]
608 return parts
.join('')
611 },{}],3:[function(require
,module
,exports
){
613 },{}],4:[function(require
,module
,exports
){
617 var buffer
= require('buffer');
618 var Buffer
= buffer
.Buffer
;
619 var SlowBuffer
= buffer
.SlowBuffer
;
620 var MAX_LEN
= buffer
.kMaxLength
|| 2147483647;
621 exports
.alloc
= function alloc(size
, fill
, encoding
) {
622 if (typeof Buffer
.alloc
=== 'function') {
623 return Buffer
.alloc(size
, fill
, encoding
);
625 if (typeof encoding
=== 'number') {
626 throw new TypeError('encoding must not be number');
628 if (typeof size
!== 'number') {
629 throw new TypeError('size must be a number');
631 if (size
> MAX_LEN
) {
632 throw new RangeError('size is too large');
636 if (_fill
=== undefined) {
640 var buf
= new Buffer(size
);
641 if (typeof _fill
=== 'string') {
642 var fillBuf
= new Buffer(_fill
, enc
);
643 var flen
= fillBuf
.length
;
646 buf
[i
] = fillBuf
[i
% flen
];
653 exports
.allocUnsafe
= function allocUnsafe(size
) {
654 if (typeof Buffer
.allocUnsafe
=== 'function') {
655 return Buffer
.allocUnsafe(size
);
657 if (typeof size
!== 'number') {
658 throw new TypeError('size must be a number');
660 if (size
> MAX_LEN
) {
661 throw new RangeError('size is too large');
663 return new Buffer(size
);
665 exports
.from = function from(value
, encodingOrOffset
, length
) {
666 if (typeof Buffer
.from === 'function' && (!global
.Uint8Array
|| Uint8Array
.from !== Buffer
.from)) {
667 return Buffer
.from(value
, encodingOrOffset
, length
);
669 if (typeof value
=== 'number') {
670 throw new TypeError('"value" argument must not be a number');
672 if (typeof value
=== 'string') {
673 return new Buffer(value
, encodingOrOffset
);
675 if (typeof ArrayBuffer
!== 'undefined' && value
instanceof ArrayBuffer
) {
676 var offset
= encodingOrOffset
;
677 if (arguments
.length
=== 1) {
678 return new Buffer(value
);
680 if (typeof offset
=== 'undefined') {
684 if (typeof len
=== 'undefined') {
685 len
= value
.byteLength
- offset
;
687 if (offset
>= value
.byteLength
) {
688 throw new RangeError('\'offset\' is out of bounds');
690 if (len
> value
.byteLength
- offset
) {
691 throw new RangeError('\'length\' is out of bounds');
693 return new Buffer(value
.slice(offset
, offset
+ len
));
695 if (Buffer
.isBuffer(value
)) {
696 var out
= new Buffer(value
.length
);
697 value
.copy(out
, 0, 0, value
.length
);
701 if (Array
.isArray(value
) || (typeof ArrayBuffer
!== 'undefined' && value
.buffer
instanceof ArrayBuffer
) || 'length' in value
) {
702 return new Buffer(value
);
704 if (value
.type
=== 'Buffer' && Array
.isArray(value
.data
)) {
705 return new Buffer(value
.data
);
709 throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
711 exports
.allocUnsafeSlow
= function allocUnsafeSlow(size
) {
712 if (typeof Buffer
.allocUnsafeSlow
=== 'function') {
713 return Buffer
.allocUnsafeSlow(size
);
715 if (typeof size
!== 'number') {
716 throw new TypeError('size must be a number');
718 if (size
>= MAX_LEN
) {
719 throw new RangeError('size is too large');
721 return new SlowBuffer(size
);
724 }).call(this,typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
725 },{"buffer":5}],5:[function(require
,module
,exports
){
727 * The buffer module from node.js, for the browser.
729 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
732 /* eslint-disable no-proto */
736 var base64
= require('base64-js')
737 var ieee754
= require('ieee754')
739 exports
.Buffer
= Buffer
740 exports
.SlowBuffer
= SlowBuffer
741 exports
.INSPECT_MAX_BYTES
= 50
743 var K_MAX_LENGTH
= 0x7fffffff
744 exports
.kMaxLength
= K_MAX_LENGTH
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)
752 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
753 * Opera 11.6+, iOS 4.2+.
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.
760 Buffer
.TYPED_ARRAY_SUPPORT
= typedArraySupport()
762 if (!Buffer
.TYPED_ARRAY_SUPPORT
&& typeof console
!== 'undefined' &&
763 typeof console
.error
=== 'function') {
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.'
770 function typedArraySupport () {
771 // Can typed array instances can be augmented?
773 var arr
= new Uint8Array(1)
774 arr
.__proto__
= {__proto__: Uint8Array
.prototype, foo: function () { return 42 }}
775 return arr
.foo() === 42
781 function createBuffer (length
) {
782 if (length
> K_MAX_LENGTH
) {
783 throw new RangeError('Invalid typed array length')
785 // Return an augmented `Uint8Array` instance
786 var buf
= new Uint8Array(length
)
787 buf
.__proto__
= Buffer
.prototype
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.
798 * The `Uint8Array` prototype remains unmodified.
801 function Buffer (arg
, encodingOrOffset
, length
) {
803 if (typeof arg
=== 'number') {
804 if (typeof encodingOrOffset
=== 'string') {
806 'If encoding is specified then the first argument must be a string'
809 return allocUnsafe(arg
)
811 return from(arg
, encodingOrOffset
, length
)
814 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
815 if (typeof Symbol
!== 'undefined' && Symbol
.species
&&
816 Buffer
[Symbol
.species
] === Buffer
) {
817 Object
.defineProperty(Buffer
, Symbol
.species
, {
825 Buffer
.poolSize
= 8192 // not used by this implementation
827 function from (value
, encodingOrOffset
, length
) {
828 if (typeof value
=== 'number') {
829 throw new TypeError('"value" argument must not be a number')
832 if (value
instanceof ArrayBuffer
) {
833 return fromArrayBuffer(value
, encodingOrOffset
, length
)
836 if (typeof value
=== 'string') {
837 return fromString(value
, encodingOrOffset
)
840 return fromObject(value
)
844 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
845 * if value is a number.
846 * Buffer.from(str[, encoding])
848 * Buffer.from(buffer)
849 * Buffer.from(arrayBuffer[, byteOffset[, length]])
851 Buffer
.from = function (value
, encodingOrOffset
, length
) {
852 return from(value
, encodingOrOffset
, length
)
855 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
856 // https://github.com/feross/buffer/pull/148
857 Buffer
.prototype.__proto__
= Uint8Array
.prototype
858 Buffer
.__proto__
= Uint8Array
860 function assertSize (size
) {
861 if (typeof size
!== 'number') {
862 throw new TypeError('"size" argument must be a number')
863 } else if (size
< 0) {
864 throw new RangeError('"size" argument must not be negative')
868 function alloc (size
, fill
, encoding
) {
871 return createBuffer(size
)
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
)
881 return createBuffer(size
)
885 * Creates a new filled Buffer instance.
886 * alloc(size[, fill[, encoding]])
888 Buffer
.alloc = function (size
, fill
, encoding
) {
889 return alloc(size
, fill
, encoding
)
892 function allocUnsafe (size
) {
894 return createBuffer(size
< 0 ? 0 : checked(size
) | 0)
898 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
900 Buffer
.allocUnsafe = function (size
) {
901 return allocUnsafe(size
)
904 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
906 Buffer
.allocUnsafeSlow = function (size
) {
907 return allocUnsafe(size
)
910 function fromString (string
, encoding
) {
911 if (typeof encoding
!== 'string' || encoding
=== '') {
915 if (!Buffer
.isEncoding(encoding
)) {
916 throw new TypeError('"encoding" must be a valid string encoding')
919 var length
= byteLength(string
, encoding
) | 0
920 var buf
= createBuffer(length
)
922 var actual
= buf
.write(string
, encoding
)
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
)
934 function fromArrayLike (array
) {
935 var length
= array
.length
< 0 ? 0 : checked(array
.length
) | 0
936 var buf
= createBuffer(length
)
937 for (var i
= 0; i
< length
; i
+= 1) {
938 buf
[i
] = array
[i
] & 255
943 function fromArrayBuffer (array
, byteOffset
, length
) {
944 if (byteOffset
< 0 || array
.byteLength
< byteOffset
) {
945 throw new RangeError('\'offset\' is out of bounds')
948 if (array
.byteLength
< byteOffset
+ (length
|| 0)) {
949 throw new RangeError('\'length\' is out of bounds')
953 if (byteOffset
=== undefined && length
=== undefined) {
954 buf
= new Uint8Array(array
)
955 } else if (length
=== undefined) {
956 buf
= new Uint8Array(array
, byteOffset
)
958 buf
= new Uint8Array(array
, byteOffset
, length
)
961 // Return an augmented `Uint8Array` instance
962 buf
.__proto__
= Buffer
.prototype
966 function fromObject (obj
) {
967 if (Buffer
.isBuffer(obj
)) {
968 var len
= checked(obj
.length
) | 0
969 var buf
= createBuffer(len
)
971 if (buf
.length
=== 0) {
975 obj
.copy(buf
, 0, 0, len
)
980 if (isArrayBufferView(obj
) || 'length' in obj
) {
981 if (typeof obj
.length
!== 'number' || numberIsNaN(obj
.length
)) {
982 return createBuffer(0)
984 return fromArrayLike(obj
)
987 if (obj
.type
=== 'Buffer' && Array
.isArray(obj
.data
)) {
988 return fromArrayLike(obj
.data
)
992 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
995 function checked (length
) {
996 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
997 // length is NaN (which is otherwise coerced to zero.)
998 if (length
>= K_MAX_LENGTH
) {
999 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
1000 'size: 0x' + K_MAX_LENGTH
.toString(16) + ' bytes')
1005 function SlowBuffer (length
) {
1006 if (+length
!= length
) { // eslint-disable-line eqeqeq
1009 return Buffer
.alloc(+length
)
1012 Buffer
.isBuffer
= function isBuffer (b
) {
1013 return b
!= null && b
._isBuffer
=== true
1016 Buffer
.compare
= function compare (a
, b
) {
1017 if (!Buffer
.isBuffer(a
) || !Buffer
.isBuffer(b
)) {
1018 throw new TypeError('Arguments must be Buffers')
1021 if (a
=== b
) return 0
1026 for (var i
= 0, len
= Math
.min(x
, y
); i
< len
; ++i
) {
1027 if (a
[i
] !== b
[i
]) {
1034 if (x
< y
) return -1
1039 Buffer
.isEncoding
= function isEncoding (encoding
) {
1040 switch (String(encoding
).toLowerCase()) {
1058 Buffer
.concat
= function concat (list
, length
) {
1059 if (!Array
.isArray(list
)) {
1060 throw new TypeError('"list" argument must be an Array of Buffers')
1063 if (list
.length
=== 0) {
1064 return Buffer
.alloc(0)
1068 if (length
=== undefined) {
1070 for (i
= 0; i
< list
.length
; ++i
) {
1071 length
+= list
[i
].length
1075 var buffer
= Buffer
.allocUnsafe(length
)
1077 for (i
= 0; i
< list
.length
; ++i
) {
1079 if (!Buffer
.isBuffer(buf
)) {
1080 throw new TypeError('"list" argument must be an Array of Buffers')
1082 buf
.copy(buffer
, pos
)
1088 function byteLength (string
, encoding
) {
1089 if (Buffer
.isBuffer(string
)) {
1090 return string
.length
1092 if (isArrayBufferView(string
) || string
instanceof ArrayBuffer
) {
1093 return string
.byteLength
1095 if (typeof string
!== 'string') {
1096 string
= '' + string
1099 var len
= string
.length
1100 if (len
=== 0) return 0
1102 // Use a for loop to avoid recursion
1103 var loweredCase
= false
1113 return utf8ToBytes(string
).length
1122 return base64ToBytes(string
).length
1124 if (loweredCase
) return utf8ToBytes(string
).length
// assume utf8
1125 encoding
= ('' + encoding
).toLowerCase()
1130 Buffer
.byteLength
= byteLength
1132 function slowToString (encoding
, start
, end
) {
1133 var loweredCase
= false
1135 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
1136 // property of a typed array.
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) {
1145 // Return early if start > this.length. Done here to prevent potential uint32
1146 // coercion fail below.
1147 if (start
> this.length
) {
1151 if (end
=== undefined || end
> this.length
) {
1159 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
1167 if (!encoding
) encoding
= 'utf8'
1172 return hexSlice(this, start
, end
)
1176 return utf8Slice(this, start
, end
)
1179 return asciiSlice(this, start
, end
)
1183 return latin1Slice(this, start
, end
)
1186 return base64Slice(this, start
, end
)
1192 return utf16leSlice(this, start
, end
)
1195 if (loweredCase
) throw new TypeError('Unknown encoding: ' + encoding
)
1196 encoding
= (encoding
+ '').toLowerCase()
1202 // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
1203 // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
1204 // reliably in a browserify context because there could be multiple different
1205 // copies of the 'buffer' package in use. This method works even for Buffer
1206 // instances that were created from another copy of the `buffer` package.
1207 // See: https://github.com/feross/buffer/issues/154
1208 Buffer
.prototype._isBuffer
= true
1210 function swap (b
, n
, m
) {
1216 Buffer
.prototype.swap16
= function swap16 () {
1217 var len
= this.length
1218 if (len
% 2 !== 0) {
1219 throw new RangeError('Buffer size must be a multiple of 16-bits')
1221 for (var i
= 0; i
< len
; i
+= 2) {
1222 swap(this, i
, i
+ 1)
1227 Buffer
.prototype.swap32
= function swap32 () {
1228 var len
= this.length
1229 if (len
% 4 !== 0) {
1230 throw new RangeError('Buffer size must be a multiple of 32-bits')
1232 for (var i
= 0; i
< len
; i
+= 4) {
1233 swap(this, i
, i
+ 3)
1234 swap(this, i
+ 1, i
+ 2)
1239 Buffer
.prototype.swap64
= function swap64 () {
1240 var len
= this.length
1241 if (len
% 8 !== 0) {
1242 throw new RangeError('Buffer size must be a multiple of 64-bits')
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)
1253 Buffer
.prototype.toString
= function toString () {
1254 var length
= this.length
1255 if (length
=== 0) return ''
1256 if (arguments
.length
=== 0) return utf8Slice(this, 0, length
)
1257 return slowToString
.apply(this, arguments
)
1260 Buffer
.prototype.equals
= function equals (b
) {
1261 if (!Buffer
.isBuffer(b
)) throw new TypeError('Argument must be a Buffer')
1262 if (this === b
) return true
1263 return Buffer
.compare(this, b
) === 0
1266 Buffer
.prototype.inspect
= function inspect () {
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
+= ' ... '
1273 return '<Buffer ' + str
+ '>'
1276 Buffer
.prototype.compare
= function compare (target
, start
, end
, thisStart
, thisEnd
) {
1277 if (!Buffer
.isBuffer(target
)) {
1278 throw new TypeError('Argument must be a Buffer')
1281 if (start
=== undefined) {
1284 if (end
=== undefined) {
1285 end
= target
? target
.length : 0
1287 if (thisStart
=== undefined) {
1290 if (thisEnd
=== undefined) {
1291 thisEnd
= this.length
1294 if (start
< 0 || end
> target
.length
|| thisStart
< 0 || thisEnd
> this.length
) {
1295 throw new RangeError('out of range index')
1298 if (thisStart
>= thisEnd
&& start
>= end
) {
1301 if (thisStart
>= thisEnd
) {
1313 if (this === target
) return 0
1315 var x
= thisEnd
- thisStart
1317 var len
= Math
.min(x
, y
)
1319 var thisCopy
= this.slice(thisStart
, thisEnd
)
1320 var targetCopy
= target
.slice(start
, end
)
1322 for (var i
= 0; i
< len
; ++i
) {
1323 if (thisCopy
[i
] !== targetCopy
[i
]) {
1330 if (x
< y
) return -1
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`.
1339 // - buffer - a Buffer to search
1340 // - val - a string, Buffer, or number
1341 // - byteOffset - an index into `buffer`; will be clamped to an int32
1342 // - encoding - an optional encoding, relevant is val is a string
1343 // - dir - true for indexOf, false for lastIndexOf
1344 function bidirectionalIndexOf (buffer
, val
, byteOffset
, encoding
, dir
) {
1345 // Empty buffer means no match
1346 if (buffer
.length
=== 0) return -1
1348 // Normalize byteOffset
1349 if (typeof byteOffset
=== 'string') {
1350 encoding
= byteOffset
1352 } else if (byteOffset
> 0x7fffffff) {
1353 byteOffset
= 0x7fffffff
1354 } else if (byteOffset
< -0x80000000) {
1355 byteOffset
= -0x80000000
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)
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
) {
1367 else byteOffset
= buffer
.length
- 1
1368 } else if (byteOffset
< 0) {
1369 if (dir
) byteOffset
= 0
1374 if (typeof val
=== 'string') {
1375 val
= Buffer
.from(val
, encoding
)
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) {
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') {
1389 return Uint8Array
.prototype.indexOf
.call(buffer
, val
, byteOffset
)
1391 return Uint8Array
.prototype.lastIndexOf
.call(buffer
, val
, byteOffset
)
1394 return arrayIndexOf(buffer
, [ val
], byteOffset
, encoding
, dir
)
1397 throw new TypeError('val must be string, number or Buffer')
1400 function arrayIndexOf (arr
, val
, byteOffset
, encoding
, dir
) {
1402 var arrLength
= arr
.length
1403 var valLength
= val
.length
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) {
1419 function read (buf
, i
) {
1420 if (indexSize
=== 1) {
1423 return buf
.readUInt16BE(i
* indexSize
)
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
1435 if (foundIndex
!== -1) i
-= i
- foundIndex
1440 if (byteOffset
+ valLength
> arrLength
) byteOffset
= arrLength
- valLength
1441 for (i
= byteOffset
; i
>= 0; i
--) {
1443 for (var j
= 0; j
< valLength
; j
++) {
1444 if (read(arr
, i
+ j
) !== read(val
, j
)) {
1456 Buffer
.prototype.includes
= function includes (val
, byteOffset
, encoding
) {
1457 return this.indexOf(val
, byteOffset
, encoding
) !== -1
1460 Buffer
.prototype.indexOf
= function indexOf (val
, byteOffset
, encoding
) {
1461 return bidirectionalIndexOf(this, val
, byteOffset
, encoding
, true)
1464 Buffer
.prototype.lastIndexOf
= function lastIndexOf (val
, byteOffset
, encoding
) {
1465 return bidirectionalIndexOf(this, val
, byteOffset
, encoding
, false)
1468 function hexWrite (buf
, string
, offset
, length
) {
1469 offset
= Number(offset
) || 0
1470 var remaining
= buf
.length
- offset
1474 length
= Number(length
)
1475 if (length
> remaining
) {
1480 // must be an even number of digits
1481 var strLen
= string
.length
1482 if (strLen
% 2 !== 0) throw new TypeError('Invalid hex string')
1484 if (length
> strLen
/ 2) {
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
1495 function utf8Write (buf
, string
, offset
, length
) {
1496 return blitBuffer(utf8ToBytes(string
, buf
.length
- offset
), buf
, offset
, length
)
1499 function asciiWrite (buf
, string
, offset
, length
) {
1500 return blitBuffer(asciiToBytes(string
), buf
, offset
, length
)
1503 function latin1Write (buf
, string
, offset
, length
) {
1504 return asciiWrite(buf
, string
, offset
, length
)
1507 function base64Write (buf
, string
, offset
, length
) {
1508 return blitBuffer(base64ToBytes(string
), buf
, offset
, length
)
1511 function ucs2Write (buf
, string
, offset
, length
) {
1512 return blitBuffer(utf16leToBytes(string
, buf
.length
- offset
), buf
, offset
, length
)
1515 Buffer
.prototype.write
= function write (string
, offset
, length
, encoding
) {
1516 // Buffer#write(string)
1517 if (offset
=== undefined) {
1519 length
= this.length
1521 // Buffer#write(string, encoding)
1522 } else if (length
=== undefined && typeof offset
=== 'string') {
1524 length
= this.length
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'
1538 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
1542 var remaining
= this.length
- offset
1543 if (length
=== undefined || length
> remaining
) length
= remaining
1545 if ((string
.length
> 0 && (length
< 0 || offset
< 0)) || offset
> this.length
) {
1546 throw new RangeError('Attempt to write outside buffer bounds')
1549 if (!encoding
) encoding
= 'utf8'
1551 var loweredCase
= false
1555 return hexWrite(this, string
, offset
, length
)
1559 return utf8Write(this, string
, offset
, length
)
1562 return asciiWrite(this, string
, offset
, length
)
1566 return latin1Write(this, string
, offset
, length
)
1569 // Warning: maxLength not taken into account in base64Write
1570 return base64Write(this, string
, offset
, length
)
1576 return ucs2Write(this, string
, offset
, length
)
1579 if (loweredCase
) throw new TypeError('Unknown encoding: ' + encoding
)
1580 encoding
= ('' + encoding
).toLowerCase()
1586 Buffer
.prototype.toJSON
= function toJSON () {
1589 data: Array
.prototype.slice
.call(this._arr
|| this, 0)
1593 function base64Slice (buf
, start
, end
) {
1594 if (start
=== 0 && end
=== buf
.length
) {
1595 return base64
.fromByteArray(buf
)
1597 return base64
.fromByteArray(buf
.slice(start
, end
))
1601 function utf8Slice (buf
, start
, end
) {
1602 end
= Math
.min(buf
.length
, end
)
1607 var firstByte
= buf
[i
]
1608 var codePoint
= null
1609 var bytesPerSequence
= (firstByte
> 0xEF) ? 4
1610 : (firstByte
> 0xDF) ? 3
1611 : (firstByte
> 0xBF) ? 2
1614 if (i
+ bytesPerSequence
<= end
) {
1615 var secondByte
, thirdByte
, fourthByte
, tempCodePoint
1617 switch (bytesPerSequence
) {
1619 if (firstByte
< 0x80) {
1620 codePoint
= firstByte
1624 secondByte
= buf
[i
+ 1]
1625 if ((secondByte
& 0xC0) === 0x80) {
1626 tempCodePoint
= (firstByte
& 0x1F) << 0x6 | (secondByte
& 0x3F)
1627 if (tempCodePoint
> 0x7F) {
1628 codePoint
= tempCodePoint
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
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
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
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
1668 i
+= bytesPerSequence
1671 return decodeCodePointsArray(res
)
1674 // Based on http://stackoverflow.com/a/22747272/680742, the browser with
1675 // the lowest limit is Chrome, with 0x10000 args.
1676 // We go 1 magnitude less, for safety
1677 var MAX_ARGUMENTS_LENGTH
= 0x1000
1679 function decodeCodePointsArray (codePoints
) {
1680 var len
= codePoints
.length
1681 if (len
<= MAX_ARGUMENTS_LENGTH
) {
1682 return String
.fromCharCode
.apply(String
, codePoints
) // avoid extra slice()
1685 // Decode in chunks to avoid "call stack size exceeded".
1689 res
+= String
.fromCharCode
.apply(
1691 codePoints
.slice(i
, i
+= MAX_ARGUMENTS_LENGTH
)
1697 function asciiSlice (buf
, start
, end
) {
1699 end
= Math
.min(buf
.length
, end
)
1701 for (var i
= start
; i
< end
; ++i
) {
1702 ret
+= String
.fromCharCode(buf
[i
] & 0x7F)
1707 function latin1Slice (buf
, start
, end
) {
1709 end
= Math
.min(buf
.length
, end
)
1711 for (var i
= start
; i
< end
; ++i
) {
1712 ret
+= String
.fromCharCode(buf
[i
])
1717 function hexSlice (buf
, start
, end
) {
1718 var len
= buf
.length
1720 if (!start
|| start
< 0) start
= 0
1721 if (!end
|| end
< 0 || end
> len
) end
= len
1724 for (var i
= start
; i
< end
; ++i
) {
1725 out
+= toHex(buf
[i
])
1730 function utf16leSlice (buf
, start
, end
) {
1731 var bytes
= buf
.slice(start
, end
)
1733 for (var i
= 0; i
< bytes
.length
; i
+= 2) {
1734 res
+= String
.fromCharCode(bytes
[i
] + (bytes
[i
+ 1] * 256))
1739 Buffer
.prototype.slice
= function slice (start
, end
) {
1740 var len
= this.length
1742 end
= end
=== undefined ? len : ~~end
1746 if (start
< 0) start
= 0
1747 } else if (start
> len
) {
1753 if (end
< 0) end
= 0
1754 } else if (end
> len
) {
1758 if (end
< start
) end
= start
1760 var newBuf
= this.subarray(start
, end
)
1761 // Return an augmented `Uint8Array` instance
1762 newBuf
.__proto__
= Buffer
.prototype
1767 * Need to make sure that buffer isn't trying to write out of bounds.
1769 function checkOffset (offset
, ext
, length
) {
1770 if ((offset
% 1) !== 0 || offset
< 0) throw new RangeError('offset is not uint')
1771 if (offset
+ ext
> length
) throw new RangeError('Trying to access beyond buffer length')
1774 Buffer
.prototype.readUIntLE
= function readUIntLE (offset
, byteLength
, noAssert
) {
1775 offset
= offset
>>> 0
1776 byteLength
= byteLength
>>> 0
1777 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
1779 var val
= this[offset
]
1782 while (++i
< byteLength
&& (mul
*= 0x100)) {
1783 val
+= this[offset
+ i
] * mul
1789 Buffer
.prototype.readUIntBE
= function readUIntBE (offset
, byteLength
, noAssert
) {
1790 offset
= offset
>>> 0
1791 byteLength
= byteLength
>>> 0
1793 checkOffset(offset
, byteLength
, this.length
)
1796 var val
= this[offset
+ --byteLength
]
1798 while (byteLength
> 0 && (mul
*= 0x100)) {
1799 val
+= this[offset
+ --byteLength
] * mul
1805 Buffer
.prototype.readUInt8
= function readUInt8 (offset
, noAssert
) {
1806 offset
= offset
>>> 0
1807 if (!noAssert
) checkOffset(offset
, 1, this.length
)
1811 Buffer
.prototype.readUInt16LE
= function readUInt16LE (offset
, noAssert
) {
1812 offset
= offset
>>> 0
1813 if (!noAssert
) checkOffset(offset
, 2, this.length
)
1814 return this[offset
] | (this[offset
+ 1] << 8)
1817 Buffer
.prototype.readUInt16BE
= function readUInt16BE (offset
, noAssert
) {
1818 offset
= offset
>>> 0
1819 if (!noAssert
) checkOffset(offset
, 2, this.length
)
1820 return (this[offset
] << 8) | this[offset
+ 1]
1823 Buffer
.prototype.readUInt32LE
= function readUInt32LE (offset
, noAssert
) {
1824 offset
= offset
>>> 0
1825 if (!noAssert
) checkOffset(offset
, 4, this.length
)
1827 return ((this[offset
]) |
1828 (this[offset
+ 1] << 8) |
1829 (this[offset
+ 2] << 16)) +
1830 (this[offset
+ 3] * 0x1000000)
1833 Buffer
.prototype.readUInt32BE
= function readUInt32BE (offset
, noAssert
) {
1834 offset
= offset
>>> 0
1835 if (!noAssert
) checkOffset(offset
, 4, this.length
)
1837 return (this[offset
] * 0x1000000) +
1838 ((this[offset
+ 1] << 16) |
1839 (this[offset
+ 2] << 8) |
1843 Buffer
.prototype.readIntLE
= function readIntLE (offset
, byteLength
, noAssert
) {
1844 offset
= offset
>>> 0
1845 byteLength
= byteLength
>>> 0
1846 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
1848 var val
= this[offset
]
1851 while (++i
< byteLength
&& (mul
*= 0x100)) {
1852 val
+= this[offset
+ i
] * mul
1856 if (val
>= mul
) val
-= Math
.pow(2, 8 * byteLength
)
1861 Buffer
.prototype.readIntBE
= function readIntBE (offset
, byteLength
, noAssert
) {
1862 offset
= offset
>>> 0
1863 byteLength
= byteLength
>>> 0
1864 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
1868 var val
= this[offset
+ --i
]
1869 while (i
> 0 && (mul
*= 0x100)) {
1870 val
+= this[offset
+ --i
] * mul
1874 if (val
>= mul
) val
-= Math
.pow(2, 8 * byteLength
)
1879 Buffer
.prototype.readInt8
= function readInt8 (offset
, noAssert
) {
1880 offset
= offset
>>> 0
1881 if (!noAssert
) checkOffset(offset
, 1, this.length
)
1882 if (!(this[offset
] & 0x80)) return (this[offset
])
1883 return ((0xff - this[offset
] + 1) * -1)
1886 Buffer
.prototype.readInt16LE
= function readInt16LE (offset
, noAssert
) {
1887 offset
= offset
>>> 0
1888 if (!noAssert
) checkOffset(offset
, 2, this.length
)
1889 var val
= this[offset
] | (this[offset
+ 1] << 8)
1890 return (val
& 0x8000) ? val
| 0xFFFF0000 : val
1893 Buffer
.prototype.readInt16BE
= function readInt16BE (offset
, noAssert
) {
1894 offset
= offset
>>> 0
1895 if (!noAssert
) checkOffset(offset
, 2, this.length
)
1896 var val
= this[offset
+ 1] | (this[offset
] << 8)
1897 return (val
& 0x8000) ? val
| 0xFFFF0000 : val
1900 Buffer
.prototype.readInt32LE
= function readInt32LE (offset
, noAssert
) {
1901 offset
= offset
>>> 0
1902 if (!noAssert
) checkOffset(offset
, 4, this.length
)
1904 return (this[offset
]) |
1905 (this[offset
+ 1] << 8) |
1906 (this[offset
+ 2] << 16) |
1907 (this[offset
+ 3] << 24)
1910 Buffer
.prototype.readInt32BE
= function readInt32BE (offset
, noAssert
) {
1911 offset
= offset
>>> 0
1912 if (!noAssert
) checkOffset(offset
, 4, this.length
)
1914 return (this[offset
] << 24) |
1915 (this[offset
+ 1] << 16) |
1916 (this[offset
+ 2] << 8) |
1920 Buffer
.prototype.readFloatLE
= function readFloatLE (offset
, noAssert
) {
1921 offset
= offset
>>> 0
1922 if (!noAssert
) checkOffset(offset
, 4, this.length
)
1923 return ieee754
.read(this, offset
, true, 23, 4)
1926 Buffer
.prototype.readFloatBE
= function readFloatBE (offset
, noAssert
) {
1927 offset
= offset
>>> 0
1928 if (!noAssert
) checkOffset(offset
, 4, this.length
)
1929 return ieee754
.read(this, offset
, false, 23, 4)
1932 Buffer
.prototype.readDoubleLE
= function readDoubleLE (offset
, noAssert
) {
1933 offset
= offset
>>> 0
1934 if (!noAssert
) checkOffset(offset
, 8, this.length
)
1935 return ieee754
.read(this, offset
, true, 52, 8)
1938 Buffer
.prototype.readDoubleBE
= function readDoubleBE (offset
, noAssert
) {
1939 offset
= offset
>>> 0
1940 if (!noAssert
) checkOffset(offset
, 8, this.length
)
1941 return ieee754
.read(this, offset
, false, 52, 8)
1944 function checkInt (buf
, value
, offset
, ext
, max
, min
) {
1945 if (!Buffer
.isBuffer(buf
)) throw new TypeError('"buffer" argument must be a Buffer instance')
1946 if (value
> max
|| value
< min
) throw new RangeError('"value" argument is out of bounds')
1947 if (offset
+ ext
> buf
.length
) throw new RangeError('Index out of range')
1950 Buffer
.prototype.writeUIntLE
= function writeUIntLE (value
, offset
, byteLength
, noAssert
) {
1952 offset
= offset
>>> 0
1953 byteLength
= byteLength
>>> 0
1955 var maxBytes
= Math
.pow(2, 8 * byteLength
) - 1
1956 checkInt(this, value
, offset
, byteLength
, maxBytes
, 0)
1961 this[offset
] = value
& 0xFF
1962 while (++i
< byteLength
&& (mul
*= 0x100)) {
1963 this[offset
+ i
] = (value
/ mul
) & 0xFF
1966 return offset
+ byteLength
1969 Buffer
.prototype.writeUIntBE
= function writeUIntBE (value
, offset
, byteLength
, noAssert
) {
1971 offset
= offset
>>> 0
1972 byteLength
= byteLength
>>> 0
1974 var maxBytes
= Math
.pow(2, 8 * byteLength
) - 1
1975 checkInt(this, value
, offset
, byteLength
, maxBytes
, 0)
1978 var i
= byteLength
- 1
1980 this[offset
+ i
] = value
& 0xFF
1981 while (--i
>= 0 && (mul
*= 0x100)) {
1982 this[offset
+ i
] = (value
/ mul
) & 0xFF
1985 return offset
+ byteLength
1988 Buffer
.prototype.writeUInt8
= function writeUInt8 (value
, offset
, noAssert
) {
1990 offset
= offset
>>> 0
1991 if (!noAssert
) checkInt(this, value
, offset
, 1, 0xff, 0)
1992 this[offset
] = (value
& 0xff)
1996 Buffer
.prototype.writeUInt16LE
= function writeUInt16LE (value
, offset
, noAssert
) {
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)
2005 Buffer
.prototype.writeUInt16BE
= function writeUInt16BE (value
, offset
, noAssert
) {
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)
2014 Buffer
.prototype.writeUInt32LE
= function writeUInt32LE (value
, offset
, noAssert
) {
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)
2025 Buffer
.prototype.writeUInt32BE
= function writeUInt32BE (value
, offset
, noAssert
) {
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)
2036 Buffer
.prototype.writeIntLE
= function writeIntLE (value
, offset
, byteLength
, noAssert
) {
2038 offset
= offset
>>> 0
2040 var limit
= Math
.pow(2, (8 * byteLength
) - 1)
2042 checkInt(this, value
, offset
, byteLength
, limit
- 1, -limit
)
2048 this[offset
] = value
& 0xFF
2049 while (++i
< byteLength
&& (mul
*= 0x100)) {
2050 if (value
< 0 && sub
=== 0 && this[offset
+ i
- 1] !== 0) {
2053 this[offset
+ i
] = ((value
/ mul
) >> 0) - sub
& 0xFF
2056 return offset
+ byteLength
2059 Buffer
.prototype.writeIntBE
= function writeIntBE (value
, offset
, byteLength
, noAssert
) {
2061 offset
= offset
>>> 0
2063 var limit
= Math
.pow(2, (8 * byteLength
) - 1)
2065 checkInt(this, value
, offset
, byteLength
, limit
- 1, -limit
)
2068 var i
= byteLength
- 1
2071 this[offset
+ i
] = value
& 0xFF
2072 while (--i
>= 0 && (mul
*= 0x100)) {
2073 if (value
< 0 && sub
=== 0 && this[offset
+ i
+ 1] !== 0) {
2076 this[offset
+ i
] = ((value
/ mul
) >> 0) - sub
& 0xFF
2079 return offset
+ byteLength
2082 Buffer
.prototype.writeInt8
= function writeInt8 (value
, offset
, noAssert
) {
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)
2091 Buffer
.prototype.writeInt16LE
= function writeInt16LE (value
, offset
, noAssert
) {
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)
2100 Buffer
.prototype.writeInt16BE
= function writeInt16BE (value
, offset
, noAssert
) {
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)
2109 Buffer
.prototype.writeInt32LE
= function writeInt32LE (value
, offset
, noAssert
) {
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)
2120 Buffer
.prototype.writeInt32BE
= function writeInt32BE (value
, offset
, noAssert
) {
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)
2132 function checkIEEE754 (buf
, value
, offset
, ext
, max
, min
) {
2133 if (offset
+ ext
> buf
.length
) throw new RangeError('Index out of range')
2134 if (offset
< 0) throw new RangeError('Index out of range')
2137 function writeFloat (buf
, value
, offset
, littleEndian
, noAssert
) {
2139 offset
= offset
>>> 0
2141 checkIEEE754(buf
, value
, offset
, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
2143 ieee754
.write(buf
, value
, offset
, littleEndian
, 23, 4)
2147 Buffer
.prototype.writeFloatLE
= function writeFloatLE (value
, offset
, noAssert
) {
2148 return writeFloat(this, value
, offset
, true, noAssert
)
2151 Buffer
.prototype.writeFloatBE
= function writeFloatBE (value
, offset
, noAssert
) {
2152 return writeFloat(this, value
, offset
, false, noAssert
)
2155 function writeDouble (buf
, value
, offset
, littleEndian
, noAssert
) {
2157 offset
= offset
>>> 0
2159 checkIEEE754(buf
, value
, offset
, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
2161 ieee754
.write(buf
, value
, offset
, littleEndian
, 52, 8)
2165 Buffer
.prototype.writeDoubleLE
= function writeDoubleLE (value
, offset
, noAssert
) {
2166 return writeDouble(this, value
, offset
, true, noAssert
)
2169 Buffer
.prototype.writeDoubleBE
= function writeDoubleBE (value
, offset
, noAssert
) {
2170 return writeDouble(this, value
, offset
, false, noAssert
)
2173 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
2174 Buffer
.prototype.copy
= function copy (target
, targetStart
, start
, end
) {
2175 if (!start
) start
= 0
2176 if (!end
&& end
!== 0) end
= this.length
2177 if (targetStart
>= target
.length
) targetStart
= target
.length
2178 if (!targetStart
) targetStart
= 0
2179 if (end
> 0 && end
< start
) end
= start
2181 // Copy 0 bytes; we're done
2182 if (end
=== start
) return 0
2183 if (target
.length
=== 0 || this.length
=== 0) return 0
2185 // Fatal error conditions
2186 if (targetStart
< 0) {
2187 throw new RangeError('targetStart out of bounds')
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')
2193 if (end
> this.length
) end
= this.length
2194 if (target
.length
- targetStart
< end
- start
) {
2195 end
= target
.length
- targetStart
+ start
2198 var len
= end
- start
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
]
2206 } else if (len
< 1000) {
2207 // ascending copy from start
2208 for (i
= 0; i
< len
; ++i
) {
2209 target
[i
+ targetStart
] = this[i
+ start
]
2212 Uint8Array
.prototype.set.call(
2214 this.subarray(start
, start
+ len
),
2223 // buffer.fill(number[, offset[, end]])
2224 // buffer.fill(buffer[, offset[, end]])
2225 // buffer.fill(string[, offset[, end]][, encoding])
2226 Buffer
.prototype.fill
= function fill (val
, start
, end
, encoding
) {
2227 // Handle string cases:
2228 if (typeof val
=== 'string') {
2229 if (typeof start
=== 'string') {
2233 } else if (typeof end
=== 'string') {
2237 if (val
.length
=== 1) {
2238 var code
= val
.charCodeAt(0)
2243 if (encoding
!== undefined && typeof encoding
!== 'string') {
2244 throw new TypeError('encoding must be a string')
2246 if (typeof encoding
=== 'string' && !Buffer
.isEncoding(encoding
)) {
2247 throw new TypeError('Unknown encoding: ' + encoding
)
2249 } else if (typeof val
=== 'number') {
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')
2263 end
= end
=== undefined ? this.length : end
>>> 0
2268 if (typeof val
=== 'number') {
2269 for (i
= start
; i
< end
; ++i
) {
2273 var bytes
= Buffer
.isBuffer(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
]
2288 var INVALID_BASE64_RE
= /[^+/0-9A
-Za
-z
-_
]/g
2290 function base64clean (str
) {
2291 // Node strips out invalid characters like \n and \t from the string, base64-js does not
2292 str
= str
.trim().replace(INVALID_BASE64_RE
, '')
2293 // Node converts strings with length < 2 to ''
2294 if (str
.length
< 2) return ''
2295 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
2296 while (str
.length
% 4 !== 0) {
2302 function toHex (n
) {
2303 if (n
< 16) return '0' + n
.toString(16)
2304 return n
.toString(16)
2307 function utf8ToBytes (string
, units
) {
2308 units
= units
|| Infinity
2310 var length
= string
.length
2311 var leadSurrogate
= null
2314 for (var i
= 0; i
< length
; ++i
) {
2315 codePoint
= string
.charCodeAt(i
)
2317 // is surrogate component
2318 if (codePoint
> 0xD7FF && codePoint
< 0xE000) {
2319 // last char was a lead
2320 if (!leadSurrogate
) {
2322 if (codePoint
> 0xDBFF) {
2324 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
2326 } else if (i
+ 1 === length
) {
2328 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
2333 leadSurrogate
= codePoint
2339 if (codePoint
< 0xDC00) {
2340 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
2341 leadSurrogate
= codePoint
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)
2352 leadSurrogate
= null
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
2361 codePoint
>> 0x6 | 0xC0,
2362 codePoint
& 0x3F | 0x80
2364 } else if (codePoint
< 0x10000) {
2365 if ((units
-= 3) < 0) break
2367 codePoint
>> 0xC | 0xE0,
2368 codePoint
>> 0x6 & 0x3F | 0x80,
2369 codePoint
& 0x3F | 0x80
2371 } else if (codePoint
< 0x110000) {
2372 if ((units
-= 4) < 0) break
2374 codePoint
>> 0x12 | 0xF0,
2375 codePoint
>> 0xC & 0x3F | 0x80,
2376 codePoint
>> 0x6 & 0x3F | 0x80,
2377 codePoint
& 0x3F | 0x80
2380 throw new Error('Invalid code point')
2387 function asciiToBytes (str
) {
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)
2396 function utf16leToBytes (str
, units
) {
2399 for (var i
= 0; i
< str
.length
; ++i
) {
2400 if ((units
-= 2) < 0) break
2402 c
= str
.charCodeAt(i
)
2412 function base64ToBytes (str
) {
2413 return base64
.toByteArray(base64clean(str
))
2416 function blitBuffer (src
, dst
, offset
, length
) {
2417 for (var i
= 0; i
< length
; ++i
) {
2418 if ((i
+ offset
>= dst
.length
) || (i
>= src
.length
)) break
2419 dst
[i
+ offset
] = src
[i
]
2424 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
2425 function isArrayBufferView (obj
) {
2426 return (typeof ArrayBuffer
.isView
=== 'function') && ArrayBuffer
.isView(obj
)
2429 function numberIsNaN (obj
) {
2430 return obj
!== obj
// eslint-disable-line no-self-compare
2433 },{"base64-js":2,"ieee754":8}],6:[function(require
,module
,exports
){
2435 // Copyright Joyent, Inc. and other Node contributors.
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:
2445 // The above copyright notice and this permission notice shall be included
2446 // in all copies or substantial portions of the Software.
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.
2456 // NOTE: These type checking functions intentionally don't use `instanceof`
2457 // because it is fragile and can be easily faked with `Object.create()`.
2459 function isArray(arg
) {
2460 if (Array
.isArray
) {
2461 return Array
.isArray(arg
);
2463 return objectToString(arg
) === '[object Array]';
2465 exports
.isArray
= isArray
;
2467 function isBoolean(arg
) {
2468 return typeof arg
=== 'boolean';
2470 exports
.isBoolean
= isBoolean
;
2472 function isNull(arg
) {
2473 return arg
=== null;
2475 exports
.isNull
= isNull
;
2477 function isNullOrUndefined(arg
) {
2480 exports
.isNullOrUndefined
= isNullOrUndefined
;
2482 function isNumber(arg
) {
2483 return typeof arg
=== 'number';
2485 exports
.isNumber
= isNumber
;
2487 function isString(arg
) {
2488 return typeof arg
=== 'string';
2490 exports
.isString
= isString
;
2492 function isSymbol(arg
) {
2493 return typeof arg
=== 'symbol';
2495 exports
.isSymbol
= isSymbol
;
2497 function isUndefined(arg
) {
2498 return arg
=== void 0;
2500 exports
.isUndefined
= isUndefined
;
2502 function isRegExp(re
) {
2503 return objectToString(re
) === '[object RegExp]';
2505 exports
.isRegExp
= isRegExp
;
2507 function isObject(arg
) {
2508 return typeof arg
=== 'object' && arg
!== null;
2510 exports
.isObject
= isObject
;
2512 function isDate(d
) {
2513 return objectToString(d
) === '[object Date]';
2515 exports
.isDate
= isDate
;
2517 function isError(e
) {
2518 return (objectToString(e
) === '[object Error]' || e
instanceof Error
);
2520 exports
.isError
= isError
;
2522 function isFunction(arg
) {
2523 return typeof arg
=== 'function';
2525 exports
.isFunction
= isFunction
;
2527 function isPrimitive(arg
) {
2528 return arg
=== null ||
2529 typeof arg
=== 'boolean' ||
2530 typeof arg
=== 'number' ||
2531 typeof arg
=== 'string' ||
2532 typeof arg
=== 'symbol' || // ES6 symbol
2533 typeof arg
=== 'undefined';
2535 exports
.isPrimitive
= isPrimitive
;
2537 exports
.isBuffer
= Buffer
.isBuffer
;
2539 function objectToString(o
) {
2540 return Object
.prototype.toString
.call(o
);
2543 }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
2544 },{"../../is-buffer/index.js":10}],7:[function(require
,module
,exports
){
2545 // Copyright Joyent, Inc. and other Node contributors.
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:
2555 // The above copyright notice and this permission notice shall be included
2556 // in all copies or substantial portions of the Software.
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.
2566 function EventEmitter() {
2567 this._events
= this._events
|| {};
2568 this._maxListeners
= this._maxListeners
|| undefined;
2570 module
.exports
= EventEmitter
;
2572 // Backwards-compat with node 0.10.x
2573 EventEmitter
.EventEmitter
= EventEmitter
;
2575 EventEmitter
.prototype._events
= undefined;
2576 EventEmitter
.prototype._maxListeners
= undefined;
2578 // By default EventEmitters will print a warning if more than 10 listeners are
2579 // added to it. This is a useful default which helps finding memory leaks.
2580 EventEmitter
.defaultMaxListeners
= 10;
2582 // Obviously not all Emitters should be limited to 10. This function allows
2583 // that to be increased. Set to zero for unlimited.
2584 EventEmitter
.prototype.setMaxListeners = function(n
) {
2585 if (!isNumber(n
) || n
< 0 || isNaN(n
))
2586 throw TypeError('n must be a positive number');
2587 this._maxListeners
= n
;
2591 EventEmitter
.prototype.emit = function(type
) {
2592 var er
, handler
, len
, args
, i
, listeners
;
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
)) {
2602 if (er
instanceof Error
) {
2603 throw er
; // Unhandled 'error' event
2605 // At least give some kind of context to the user
2606 var err
= new Error('Uncaught, unspecified "error" event. (' + er
+ ')');
2613 handler
= this._events
[type
];
2615 if (isUndefined(handler
))
2618 if (isFunction(handler
)) {
2619 switch (arguments
.length
) {
2625 handler
.call(this, arguments
[1]);
2628 handler
.call(this, arguments
[1], arguments
[2]);
2632 args
= Array
.prototype.slice
.call(arguments
, 1);
2633 handler
.apply(this, args
);
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
);
2646 EventEmitter
.prototype.addListener = function(type
, listener
) {
2649 if (!isFunction(listener
))
2650 throw TypeError('listener must be a function');
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
);
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
);
2669 // Adding the second element, need to change to array.
2670 this._events
[type
] = [this._events
[type
], listener
];
2672 // Check for listener leak
2673 if (isObject(this._events
[type
]) && !this._events
[type
].warned
) {
2674 if (!isUndefined(this._maxListeners
)) {
2675 m
= this._maxListeners
;
2677 m
= EventEmitter
.defaultMaxListeners
;
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
2696 EventEmitter
.prototype.on
= EventEmitter
.prototype.addListener
;
2698 EventEmitter
.prototype.once = function(type
, listener
) {
2699 if (!isFunction(listener
))
2700 throw TypeError('listener must be a function');
2705 this.removeListener(type
, g
);
2709 listener
.apply(this, arguments
);
2713 g
.listener
= listener
;
2719 // emits a 'removeListener' event iff the listener was removed
2720 EventEmitter
.prototype.removeListener = function(type
, listener
) {
2721 var list
, position
, length
, i
;
2723 if (!isFunction(listener
))
2724 throw TypeError('listener must be a function');
2726 if (!this._events
|| !this._events
[type
])
2729 list
= this._events
[type
];
2730 length
= list
.length
;
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
);
2739 } else if (isObject(list
)) {
2740 for (i
= length
; i
-- > 0;) {
2741 if (list
[i
] === listener
||
2742 (list
[i
].listener
&& list
[i
].listener
=== listener
)) {
2751 if (list
.length
=== 1) {
2753 delete this._events
[type
];
2755 list
.splice(position
, 1);
2758 if (this._events
.removeListener
)
2759 this.emit('removeListener', type
, listener
);
2765 EventEmitter
.prototype.removeAllListeners = function(type
) {
2771 // not listening for removeListener, no need to emit
2772 if (!this._events
.removeListener
) {
2773 if (arguments
.length
=== 0)
2775 else if (this._events
[type
])
2776 delete this._events
[type
];
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
);
2786 this.removeAllListeners('removeListener');
2791 listeners
= this._events
[type
];
2793 if (isFunction(listeners
)) {
2794 this.removeListener(type
, listeners
);
2795 } else if (listeners
) {
2797 while (listeners
.length
)
2798 this.removeListener(type
, listeners
[listeners
.length
- 1]);
2800 delete this._events
[type
];
2805 EventEmitter
.prototype.listeners = function(type
) {
2807 if (!this._events
|| !this._events
[type
])
2809 else if (isFunction(this._events
[type
]))
2810 ret
= [this._events
[type
]];
2812 ret
= this._events
[type
].slice();
2816 EventEmitter
.prototype.listenerCount = function(type
) {
2818 var evlistener
= this._events
[type
];
2820 if (isFunction(evlistener
))
2822 else if (evlistener
)
2823 return evlistener
.length
;
2828 EventEmitter
.listenerCount = function(emitter
, type
) {
2829 return emitter
.listenerCount(type
);
2832 function isFunction(arg
) {
2833 return typeof arg
=== 'function';
2836 function isNumber(arg
) {
2837 return typeof arg
=== 'number';
2840 function isObject(arg
) {
2841 return typeof arg
=== 'object' && arg
!== null;
2844 function isUndefined(arg
) {
2845 return arg
=== void 0;
2848 },{}],8:[function(require
,module
,exports
){
2849 exports
.read = function (buffer
, offset
, isLE
, mLen
, nBytes
) {
2851 var eLen
= nBytes
* 8 - mLen
- 1
2852 var eMax
= (1 << eLen
) - 1
2853 var eBias
= eMax
>> 1
2855 var i
= isLE
? (nBytes
- 1) : 0
2856 var d
= isLE
? -1 : 1
2857 var s
= buffer
[offset
+ i
]
2861 e
= s
& ((1 << (-nBits
)) - 1)
2864 for (; nBits
> 0; e
= e
* 256 + buffer
[offset
+ i
], i
+= d
, nBits
-= 8) {}
2866 m
= e
& ((1 << (-nBits
)) - 1)
2869 for (; nBits
> 0; m
= m
* 256 + buffer
[offset
+ i
], i
+= d
, nBits
-= 8) {}
2873 } else if (e
=== eMax
) {
2874 return m
? NaN : ((s
? -1 : 1) * Infinity
)
2876 m
= m
+ Math
.pow(2, mLen
)
2879 return (s
? -1 : 1) * m
* Math
.pow(2, e
- mLen
)
2882 exports
.write = function (buffer
, value
, offset
, isLE
, mLen
, nBytes
) {
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
2892 value
= Math
.abs(value
)
2894 if (isNaN(value
) || value
=== Infinity
) {
2895 m
= isNaN(value
) ? 1 : 0
2898 e
= Math
.floor(Math
.log(value
) / Math
.LN2
)
2899 if (value
* (c
= Math
.pow(2, -e
)) < 1) {
2903 if (e
+ eBias
>= 1) {
2906 value
+= rt
* Math
.pow(2, 1 - eBias
)
2908 if (value
* c
>= 2) {
2913 if (e
+ eBias
>= eMax
) {
2916 } else if (e
+ eBias
>= 1) {
2917 m
= (value
* c
- 1) * Math
.pow(2, mLen
)
2920 m
= value
* Math
.pow(2, eBias
- 1) * Math
.pow(2, mLen
)
2925 for (; mLen
>= 8; buffer
[offset
+ i
] = m
& 0xff, i
+= d
, m
/= 256, mLen
-= 8) {}
2929 for (; eLen
> 0; buffer
[offset
+ i
] = e
& 0xff, i
+= d
, e
/= 256, eLen
-= 8) {}
2931 buffer
[offset
+ i
- d
] |= s
* 128
2934 },{}],9:[function(require
,module
,exports
){
2935 if (typeof Object
.create
=== 'function') {
2936 // implementation from standard node.js 'util' module
2937 module
.exports
= function inherits(ctor
, superCtor
) {
2938 ctor
.super_
= superCtor
2939 ctor
.prototype = Object
.create(superCtor
.prototype, {
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
2959 },{}],10:[function(require
,module
,exports
){
2961 * Determine if an object is a Buffer
2963 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
2967 // The _isBuffer check is for Safari 5-7 support, because it's missing
2968 // Object.prototype.constructor. Remove this eventually
2969 module
.exports = function (obj
) {
2970 return obj
!= null && (isBuffer(obj
) || isSlowBuffer(obj
) || !!obj
._isBuffer
)
2973 function isBuffer (obj
) {
2974 return !!obj
.constructor && typeof obj
.constructor.isBuffer
=== 'function' && obj
.constructor.isBuffer(obj
)
2977 // For Node v0.10 support. Remove this eventually.
2978 function isSlowBuffer (obj
) {
2979 return typeof obj
.readFloatLE
=== 'function' && typeof obj
.slice
=== 'function' && isBuffer(obj
.slice(0, 0))
2982 },{}],11:[function(require
,module
,exports
){
2983 var toString
= {}.toString
;
2985 module
.exports
= Array
.isArray
|| function (arr
) {
2986 return toString
.call(arr
) == '[object Array]';
2989 },{}],12:[function(require
,module
,exports
){
2990 (function (process
){
2993 if (!process
.version
||
2994 process
.version
.indexOf('v0.') === 0 ||
2995 process
.version
.indexOf('v1.') === 0 && process
.version
.indexOf('v1.8.') !== 0) {
2996 module
.exports
= nextTick
;
2998 module
.exports
= process
.nextTick
;
3001 function nextTick(fn
, arg1
, arg2
, arg3
) {
3002 if (typeof fn
!== 'function') {
3003 throw new TypeError('"callback" argument must be a function');
3005 var len
= arguments
.length
;
3010 return process
.nextTick(fn
);
3012 return process
.nextTick(function afterTickOne() {
3013 fn
.call(null, arg1
);
3016 return process
.nextTick(function afterTickTwo() {
3017 fn
.call(null, arg1
, arg2
);
3020 return process
.nextTick(function afterTickThree() {
3021 fn
.call(null, arg1
, arg2
, arg3
);
3024 args
= new Array(len
- 1);
3026 while (i
< args
.length
) {
3027 args
[i
++] = arguments
[i
];
3029 return process
.nextTick(function afterTick() {
3030 fn
.apply(null, args
);
3035 }).call(this,require('_process'))
3036 },{"_process":13}],13:[function(require
,module
,exports
){
3037 // shim for using process in browser
3038 var process
= module
.exports
= {};
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.
3045 var cachedSetTimeout
;
3046 var cachedClearTimeout
;
3048 function defaultSetTimout() {
3049 throw new Error('setTimeout has not been defined');
3051 function defaultClearTimeout () {
3052 throw new Error('clearTimeout has not been defined');
3056 if (typeof setTimeout
=== 'function') {
3057 cachedSetTimeout
= setTimeout
;
3059 cachedSetTimeout
= defaultSetTimout
;
3062 cachedSetTimeout
= defaultSetTimout
;
3065 if (typeof clearTimeout
=== 'function') {
3066 cachedClearTimeout
= clearTimeout
;
3068 cachedClearTimeout
= defaultClearTimeout
;
3071 cachedClearTimeout
= defaultClearTimeout
;
3074 function runTimeout(fun
) {
3075 if (cachedSetTimeout
=== setTimeout
) {
3076 //normal enviroments in sane situations
3077 return setTimeout(fun
, 0);
3079 // if setTimeout wasn't available but was latter defined
3080 if ((cachedSetTimeout
=== defaultSetTimout
|| !cachedSetTimeout
) && setTimeout
) {
3081 cachedSetTimeout
= setTimeout
;
3082 return setTimeout(fun
, 0);
3085 // when when somebody has screwed with setTimeout but no I.E. maddness
3086 return cachedSetTimeout(fun
, 0);
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);
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);
3099 function runClearTimeout(marker
) {
3100 if (cachedClearTimeout
=== clearTimeout
) {
3101 //normal enviroments in sane situations
3102 return clearTimeout(marker
);
3104 // if clearTimeout wasn't available but was latter defined
3105 if ((cachedClearTimeout
=== defaultClearTimeout
|| !cachedClearTimeout
) && clearTimeout
) {
3106 cachedClearTimeout
= clearTimeout
;
3107 return clearTimeout(marker
);
3110 // when when somebody has screwed with setTimeout but no I.E. maddness
3111 return cachedClearTimeout(marker
);
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
);
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
);
3127 var draining
= false;
3129 var queueIndex
= -1;
3131 function cleanUpNextTick() {
3132 if (!draining
|| !currentQueue
) {
3136 if (currentQueue
.length
) {
3137 queue
= currentQueue
.concat(queue
);
3146 function drainQueue() {
3150 var timeout
= runTimeout(cleanUpNextTick
);
3153 var len
= queue
.length
;
3155 currentQueue
= queue
;
3157 while (++queueIndex
< len
) {
3159 currentQueue
[queueIndex
].run();
3165 currentQueue
= null;
3167 runClearTimeout(timeout
);
3170 process
.nextTick = function (fun
) {
3171 var args
= new Array(arguments
.length
- 1);
3172 if (arguments
.length
> 1) {
3173 for (var i
= 1; i
< arguments
.length
; i
++) {
3174 args
[i
- 1] = arguments
[i
];
3177 queue
.push(new Item(fun
, args
));
3178 if (queue
.length
=== 1 && !draining
) {
3179 runTimeout(drainQueue
);
3183 // v8 likes predictible objects
3184 function Item(fun
, array
) {
3188 Item
.prototype.run = function () {
3189 this.fun
.apply(null, this.array
);
3191 process
.title
= 'browser';
3192 process
.browser
= true;
3195 process
.version
= ''; // empty string to avoid regexp issues
3196 process
.versions
= {};
3201 process
.addListener
= noop
;
3202 process
.once
= noop
;
3204 process
.removeListener
= noop
;
3205 process
.removeAllListeners
= noop
;
3206 process
.emit
= noop
;
3207 process
.prependListener
= noop
;
3208 process
.prependOnceListener
= noop
;
3210 process
.listeners = function (name
) { return [] }
3212 process
.binding = function (name
) {
3213 throw new Error('process.binding is not supported');
3216 process
.cwd = function () { return '/' };
3217 process
.chdir = function (dir
) {
3218 throw new Error('process.chdir is not supported');
3220 process
.umask = function() { return 0; };
3222 },{}],14:[function(require
,module
,exports
){
3223 module
.exports
= require('./lib/_stream_duplex.js');
3225 },{"./lib/_stream_duplex.js":15}],15:[function(require
,module
,exports
){
3226 // a duplex stream is just a stream that is both readable and writable.
3227 // Since JS doesn't have multiple prototypal inheritance, this class
3228 // prototypally inherits from Readable, and then parasitically from
3235 var objectKeys
= Object
.keys
|| function (obj
) {
3237 for (var key
in obj
) {
3243 module.exports = Duplex;
3246 var processNextTick
= require('process-nextick-args');
3250 var util
= require('core-util-is');
3251 util
.inherits
= require('inherits');
3254 var Readable = require('./_stream_readable');
3255 var Writable = require('./_stream_writable');
3257 util.inherits(Duplex, Readable);
3259 var keys = objectKeys(Writable.prototype);
3260 for (var v = 0; v < keys.length; v++) {
3261 var method = keys[v];
3262 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
3265 function Duplex(options) {
3266 if (!(this instanceof Duplex)) return new Duplex(options);
3268 Readable.call(this, options);
3269 Writable.call(this, options);
3271 if (options && options.readable === false) this.readable = false;
3273 if (options && options.writable === false) this.writable = false;
3275 this.allowHalfOpen = true;
3276 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
3278 this.once('end', onend);
3281 // the no-half-open enforcer
3283 // if we allow half-open state, or if the writable side ended,
3285 if (this.allowHalfOpen || this._writableState.ended) return;
3287 // no more data can be written.
3288 // But allow more writes to happen in this tick.
3289 processNextTick(onEndNT, this);
3292 function onEndNT(self) {
3296 function forEach(xs, f) {
3297 for (var i = 0, l = xs.length; i < l; i++) {
3301 },{"./_stream_readable":17,"./_stream_writable":19,"core-util-is":6,"inherits":9,"process-nextick-args":12}],16:[function(require,module,exports){
3302 // a passthrough stream.
3303 // basically just the most minimal sort of Transform stream.
3304 // Every written chunk gets output as-is.
3308 module.exports = PassThrough;
3310 var Transform = require('./_stream_transform');
3313 var util
= require('core-util-is');
3314 util
.inherits
= require('inherits');
3317 util.inherits(PassThrough, Transform);
3319 function PassThrough(options) {
3320 if (!(this instanceof PassThrough)) return new PassThrough(options);
3322 Transform.call(this, options);
3325 PassThrough.prototype._transform = function (chunk, encoding, cb) {
3328 },{"./_stream_transform":18,"core-util-is":6,"inherits":9}],17:[function(require,module,exports){
3329 (function (process){
3332 module.exports = Readable;
3335 var processNextTick
= require('process-nextick-args');
3339 var isArray
= require('isarray');
3346 Readable.ReadableState = ReadableState;
3349 var EE
= require('events').EventEmitter
;
3351 var EElistenerCount = function (emitter
, type
) {
3352 return emitter
.listeners(type
).length
;
3357 var Stream
= require('./internal/streams/stream');
3360 var Buffer = require('buffer').Buffer;
3362 var bufferShim
= require('buffer-shims');
3366 var util
= require('core-util-is');
3367 util
.inherits
= require('inherits');
3371 var debugUtil
= require('util');
3373 if (debugUtil
&& debugUtil
.debuglog
) {
3374 debug
= debugUtil
.debuglog('stream');
3376 debug = function () {};
3380 var BufferList = require('./internal/streams/BufferList');
3383 util.inherits(Readable, Stream);
3385 var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
3387 function prependListener(emitter, event, fn) {
3388 // Sadly this is not cacheable as some libraries bundle their own
3389 // event emitter implementation with them.
3390 if (typeof emitter.prependListener === 'function') {
3391 return emitter.prependListener(event, fn);
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]];
3401 function ReadableState(options, stream) {
3402 Duplex = Duplex || require('./_stream_duplex');
3404 options = options || {};
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;
3410 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
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;
3419 this.highWaterMark = ~~this.highWaterMark;
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
3424 this.buffer = new BufferList();
3427 this.pipesCount = 0;
3428 this.flowing = null;
3430 this.endEmitted = false;
3431 this.reading = false;
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.
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;
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';
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;
3455 // the number of writers that are awaiting a drain event in .pipe()s
3456 this.awaitDrain = 0;
3458 // if true, a maybeReadMore has been scheduled
3459 this.readingMore = false;
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;
3470 function Readable(options) {
3471 Duplex = Duplex || require('./_stream_duplex');
3473 if (!(this instanceof Readable)) return new Readable(options);
3475 this._readableState = new ReadableState(options, this);
3478 this.readable = true;
3480 if (options && typeof options.read === 'function') this._read = options.read;
3485 // Manually shove something into the read() buffer.
3486 // This returns true if the highWaterMark has not been hit yet,
3487 // similar to how Writable.write() returns true if you should
3488 // write() some more.
3489 Readable.prototype.push = function (chunk, encoding) {
3490 var state = this._readableState;
3492 if (!state.objectMode && typeof chunk === 'string') {
3493 encoding = encoding || state.defaultEncoding;
3494 if (encoding !== state.encoding) {
3495 chunk = bufferShim.from(chunk, encoding);
3500 return readableAddChunk(this, state, chunk, encoding, false);
3503 // Unshift should *always* be something directly out of read()
3504 Readable.prototype.unshift = function (chunk) {
3505 var state = this._readableState;
3506 return readableAddChunk(this, state, chunk, '', true);
3509 Readable.prototype.isPaused = function () {
3510 return this._readableState.flowing === false;
3513 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
3514 var er = chunkInvalid(state, chunk);
3516 stream.emit('error', er);
3517 } else if (chunk === null) {
3518 state.reading = false;
3519 onEofChunk(stream, state);
3520 } else if (state.objectMode || chunk && chunk.length > 0) {
3521 if (state.ended && !addToFront) {
3522 var e = new Error('stream.push() after EOF');
3523 stream.emit('error', e);
3524 } else if (state.endEmitted && addToFront) {
3525 var _e = new Error('stream.unshift() after end event');
3526 stream.emit('error', _e);
3529 if (state.decoder && !addToFront && !encoding) {
3530 chunk = state.decoder.write(chunk);
3531 skipAdd = !state.objectMode && chunk.length === 0;
3534 if (!addToFront) state.reading = false;
3536 // Don't add to the buffer if we've decoded to an empty string chunk and
3537 // we're not in object mode
3539 // if we want the data now, just emit it.
3540 if (state.flowing && state.length === 0 && !state.sync) {
3541 stream.emit('data', chunk);
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);
3548 if (state.needReadable) emitReadable(stream);
3552 maybeReadMore(stream, state);
3554 } else if (!addToFront) {
3555 state.reading = false;
3558 return needMoreData(state);
3561 // if it's past the high water mark, we can push in some more.
3562 // Also, if we have no data yet, we can stand some
3563 // more bytes. This is to work around cases where hwm=0,
3564 // such as the repl. Also, if the push() triggered a
3565 // readable event, and the user called read(largeNumber) such that
3566 // needReadable was set, then we ought to push more, so that another
3567 // 'readable' event will be triggered.
3568 function needMoreData(state) {
3569 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
3572 // backwards compatibility.
3573 Readable.prototype.setEncoding = function (enc) {
3574 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
3575 this._readableState.decoder = new StringDecoder(enc);
3576 this._readableState.encoding = enc;
3580 // Don't raise the hwm > 8MB
3581 var MAX_HWM = 0x800000;
3582 function computeNewHighWaterMark(n) {
3586 // Get the next highest power of 2 to prevent increasing hwm excessively in
3599 // This function is designed to be inlinable, so please take care when making
3600 // changes to the function body.
3601 function howMuchToRead(n, state) {
3602 if (n <= 0 || state.length === 0 && state.ended) return 0;
3603 if (state.objectMode) return 1;
3605 // Only flow one buffer at a time
3606 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
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
3613 state.needReadable = true;
3616 return state.length;
3619 // you can override either this method, or the async _read(n) below.
3620 Readable.prototype.read = function (n) {
3622 n = parseInt(n, 10);
3623 var state = this._readableState;
3626 if (n !== 0) state.emittedReadable = false;
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);
3637 n = howMuchToRead(n, state);
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);
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.
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.
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
3665 // 3. Actually pull the requested chunks out of the buffer and return.
3667 // if we need a readable event, then we need to do some reading.
3668 var doRead = state.needReadable;
3669 debug('need readable', doRead);
3671 // if we currently have less than the highWaterMark, then also read some
3672 if (state.length === 0 || state.length - n < state.highWaterMark) {
3674 debug('length less than watermark', doRead);
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) {
3681 debug('reading or ended', doRead);
3682 } else if (doRead) {
3684 state.reading = 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);
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);
3697 if (n > 0) ret = fromList(n, state);else ret = null;
3700 state.needReadable = true;
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;
3711 // If we tried to read() past the EOF, then emit end on the next tick.
3712 if (nOrig !== n && state.ended) endReadable(this);
3715 if (ret !== null) this.emit('data', ret);
3720 function chunkInvalid(state, chunk) {
3722 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
3723 er = new TypeError('Invalid non-string/buffer chunk');
3728 function onEofChunk(stream, state) {
3729 if (state.ended) return;
3730 if (state.decoder) {
3731 var chunk = state.decoder.end();
3732 if (chunk && chunk.length) {
3733 state.buffer.push(chunk);
3734 state.length += state.objectMode ? 1 : chunk.length;
3739 // emit 'readable' now to make sure it gets picked up.
3740 emitReadable(stream);
3743 // Don't emit readable right away in sync mode, because this can trigger
3744 // another read() call => stack overflow. This way, it might trigger
3745 // a nextTick recursion warning, but that's not so bad.
3746 function emitReadable(stream) {
3747 var state = stream._readableState;
3748 state.needReadable = false;
3749 if (!state.emittedReadable) {
3750 debug('emitReadable', state.flowing);
3751 state.emittedReadable = true;
3752 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
3756 function emitReadable_(stream) {
3757 debug('emit readable');
3758 stream.emit('readable');
3762 // at this point, the user has presumably seen the 'readable' event,
3763 // and called read() to consume some data. that may have triggered
3764 // in turn another _read(n) call, in which case reading = true if
3765 // it's in progress.
3766 // However, if we're not ended, or reading, and the length < hwm,
3767 // then go ahead and try to read some more preemptively.
3768 function maybeReadMore(stream, state) {
3769 if (!state.readingMore) {
3770 state.readingMore = true;
3771 processNextTick(maybeReadMore_, stream, state);
3775 function maybeReadMore_(stream, state) {
3776 var len = state.length;
3777 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
3778 debug('maybeReadMore read 0');
3780 if (len === state.length)
3781 // didn't get any data, stop spinning.
3782 break;else len = state.length;
3784 state.readingMore = false;
3787 // abstract method. to be overridden in specific implementation classes.
3788 // call cb(er, data) where data is <= n in length.
3789 // for virtual (non-string, non-buffer) streams, "length" is somewhat
3790 // arbitrary, and perhaps not very meaningful.
3791 Readable.prototype._read = function (n) {
3792 this.emit('error', new Error('_read() is not implemented'));
3795 Readable.prototype.pipe = function (dest, pipeOpts) {
3797 var state = this._readableState;
3799 switch (state.pipesCount) {
3804 state.pipes = [state.pipes, dest];
3807 state.pipes.push(dest);
3810 state.pipesCount += 1;
3811 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
3813 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
3815 var endFn = doEnd ? onend : cleanup;
3816 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
3818 dest.on('unpipe', onunpipe);
3819 function onunpipe(readable) {
3821 if (readable === src) {
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
3835 var ondrain = pipeOnDrain(src);
3836 dest.on('drain', ondrain);
3838 var cleanedUp = false;
3839 function cleanup() {
3841 // cleanup event handlers once the pipe is broken
3842 dest.removeListener('close', onclose);
3843 dest.removeListener('finish', onfinish);
3844 dest.removeListener('drain', ondrain);
3845 dest.removeListener('error', onerror);
3846 dest.removeListener('unpipe', onunpipe);
3847 src.removeListener('end', onend);
3848 src.removeListener('end', cleanup);
3849 src.removeListener('data', ondata);
3853 // if the reader is waiting for a drain event from this
3854 // specific writer, then it would cause it to never start
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();
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) {
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;
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);
3890 dest.removeListener('error', onerror);
3891 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
3894 // Make sure our error handler is attached before userland ones.
3895 prependListener(dest, 'error', onerror);
3897 // Both close and finish should trigger unpipe, but only once.
3898 function onclose() {
3899 dest.removeListener('finish', onfinish);
3902 dest.once('close', onclose);
3903 function onfinish() {
3905 dest.removeListener('close', onclose);
3908 dest.once('finish', onfinish);
3915 // tell the dest that it's being piped to
3916 dest.emit('pipe', src);
3918 // start the flow if it hasn't been started already.
3919 if (!state.flowing) {
3920 debug('pipe resume');
3927 function pipeOnDrain(src) {
3928 return function () {
3929 var state = src._readableState;
3930 debug('pipeOnDrain', state.awaitDrain);
3931 if (state.awaitDrain) state.awaitDrain--;
3932 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
3933 state.flowing = true;
3939 Readable.prototype.unpipe = function (dest) {
3940 var state = this._readableState;
3942 // if we're not piping anywhere, then do nothing.
3943 if (state.pipesCount === 0) return this;
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;
3950 if (!dest) dest = state.pipes;
3954 state.pipesCount = 0;
3955 state.flowing = false;
3956 if (dest) dest.emit('unpipe', this);
3960 // slow case. multiple pipe destinations.
3964 var dests = state.pipes;
3965 var len = state.pipesCount;
3967 state.pipesCount = 0;
3968 state.flowing = false;
3970 for (var i = 0; i < len; i++) {
3971 dests[i].emit('unpipe', this);
3975 // try to find the right one.
3976 var index = indexOf(state.pipes, dest);
3977 if (index === -1) return this;
3979 state.pipes.splice(index, 1);
3980 state.pipesCount -= 1;
3981 if (state.pipesCount === 1) state.pipes = state.pipes[0];
3983 dest.emit('unpipe', this);
3988 // set up data events if they are asked for
3989 // Ensure readable listeners eventually get something
3990 Readable.prototype.on = function (ev, fn) {
3991 var res = Stream.prototype.on.call(this, ev, fn);
3993 if (ev === 'data') {
3994 // Start flowing on next tick if stream isn't explicitly paused
3995 if (this._readableState.flowing !== false) this.resume();
3996 } else if (ev === 'readable') {
3997 var state = this._readableState;
3998 if (!state.endEmitted && !state.readableListening) {
3999 state.readableListening = state.needReadable = true;
4000 state.emittedReadable = false;
4001 if (!state.reading) {
4002 processNextTick(nReadingNextTick, this);
4003 } else if (state.length) {
4004 emitReadable(this, state);
4011 Readable.prototype.addListener = Readable.prototype.on;
4013 function nReadingNextTick(self) {
4014 debug('readable nexttick read 0');
4018 // pause() and resume() are remnants of the legacy readable stream API
4019 // If the user uses them, then switch into old mode.
4020 Readable.prototype.resume = function () {
4021 var state = this._readableState;
4022 if (!state.flowing) {
4024 state.flowing = true;
4025 resume(this, state);
4030 function resume(stream, state) {
4031 if (!state.resumeScheduled) {
4032 state.resumeScheduled = true;
4033 processNextTick(resume_, stream, state);
4037 function resume_(stream, state) {
4038 if (!state.reading) {
4039 debug('resume read 0');
4043 state.resumeScheduled = false;
4044 state.awaitDrain = 0;
4045 stream.emit('resume');
4047 if (state.flowing && !state.reading) stream.read(0);
4050 Readable.prototype.pause = function () {
4051 debug('call pause flowing=%j', this._readableState.flowing);
4052 if (false !== this._readableState.flowing) {
4054 this._readableState.flowing = false;
4060 function flow(stream) {
4061 var state = stream._readableState;
4062 debug('flow', state.flowing);
4063 while (state.flowing && stream.read() !== null) {}
4066 // wrap an old-style stream as the async data source.
4067 // This is *not* part of the readable stream interface.
4068 // It is an ugly unfortunate mess of history.
4069 Readable.prototype.wrap = function (stream) {
4070 var state = this._readableState;
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);
4084 stream.on('data', function (chunk) {
4085 debug('wrapped data');
4086 if (state.decoder) chunk = state.decoder.write(chunk);
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;
4091 var ret = self.push(chunk);
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);
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]));
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);
4128 // exposed for testing purposes only.
4129 Readable._fromList = fromList;
4131 // Pluck off n bytes from an array of buffers.
4132 // Length is the combined lengths of all the buffers in the list.
4133 // This function is designed to be inlinable, so please take care when making
4134 // changes to the function body.
4135 function fromList(n, state) {
4137 if (state.length === 0) return null;
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();
4145 // read part of list
4146 ret = fromListPartial(n, state.buffer, state.decoder);
4152 // Extracts only enough buffered data to satisfy the amount requested.
4153 // This function is designed to be inlinable, so please take care when making
4154 // changes to the function body.
4155 function fromListPartial(n, list, hasStrings) {
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
4165 // result spans more than one buffer
4166 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
4171 // Copies a specified amount of characters from the list of buffered data
4173 // This function is designed to be inlinable, so please take care when making
4174 // changes to the function body.
4175 function copyFromBufferString(n, list) {
4180 while (p = p.next) {
4182 var nb = n > str.length ? str.length : n;
4183 if (nb === str.length) ret += str;else ret += str.slice(0, n);
4186 if (nb === str.length) {
4188 if (p.next) list.head = p.next;else list.head = list.tail = null;
4191 p.data = str.slice(nb);
4201 // Copies a specified amount of bytes from the list of buffered data chunks.
4202 // This function is designed to be inlinable, so please take care when making
4203 // changes to the function body.
4204 function copyFromBuffer(n, list) {
4205 var ret = bufferShim.allocUnsafe(n);
4210 while (p = p.next) {
4212 var nb = n > buf.length ? buf.length : n;
4213 buf.copy(ret, ret.length - n, 0, nb);
4216 if (nb === buf.length) {
4218 if (p.next) list.head = p.next;else list.head = list.tail = null;
4221 p.data = buf.slice(nb);
4231 function endReadable(stream) {
4232 var state = stream._readableState;
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');
4238 if (!state.endEmitted) {
4240 processNextTick(endReadableNT, state, stream);
4244 function endReadableNT(state, stream) {
4245 // Check that we didn't get one last unshift.
4246 if (!state.endEmitted && state.length === 0) {
4247 state.endEmitted = true;
4248 stream.readable = false;
4253 function forEach(xs, f) {
4254 for (var i = 0, l = xs.length; i < l; i++) {
4259 function indexOf(xs, x) {
4260 for (var i = 0, l = xs.length; i < l; i++) {
4261 if (xs[i] === x) return i;
4265 }).call(this,require('_process'))
4266 },{"./_stream_duplex":15,"./internal/streams/BufferList":20,"./internal/streams/stream":21,"_process":13,"buffer":5,"buffer-shims":4,"core-util-is":6,"events":7,"inherits":9,"isarray":11,"process-nextick-args":12,"string_decoder/":22,"util":3}],18:[function(require,module,exports){
4267 // a transform stream is a readable/writable stream where you do
4268 // something with the data. Sometimes it's called a "filter",
4269 // but that's not a great name for it, since that implies a thing where
4270 // some bits pass through, and others are simply ignored. (That would
4271 // be a valid example of a transform, of course.)
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.
4278 // Here's how this works:
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.
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.
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.
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.
4311 module.exports = Transform;
4313 var Duplex = require('./_stream_duplex');
4316 var util
= require('core-util-is');
4317 util
.inherits
= require('inherits');
4320 util.inherits(Transform, Duplex);
4322 function TransformState(stream) {
4323 this.afterTransform = function (er, data) {
4324 return afterTransform(stream, er, data);
4327 this.needTransform = false;
4328 this.transforming = false;
4329 this.writecb = null;
4330 this.writechunk = null;
4331 this.writeencoding = null;
4334 function afterTransform(stream, er, data) {
4335 var ts = stream._transformState;
4336 ts.transforming = false;
4338 var cb = ts.writecb;
4340 if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
4342 ts.writechunk = null;
4345 if (data !== null && data !== undefined) stream.push(data);
4349 var rs = stream._readableState;
4351 if (rs.needReadable || rs.length < rs.highWaterMark) {
4352 stream._read(rs.highWaterMark);
4356 function Transform(options) {
4357 if (!(this instanceof Transform)) return new Transform(options);
4359 Duplex.call(this, options);
4361 this._transformState = new TransformState(this);
4365 // start out asking for a readable event once data is transformed.
4366 this._readableState.needReadable = true;
4368 // we have implemented the _read method, and done the other things
4369 // that Readable wants before the first _read call, so unset the
4371 this._readableState.sync = false;
4374 if (typeof options.transform === 'function') this._transform = options.transform;
4376 if (typeof options.flush === 'function') this._flush = options.flush;
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);
4387 Transform.prototype.push = function (chunk, encoding) {
4388 this._transformState.needTransform = false;
4389 return Duplex.prototype.push.call(this, chunk, encoding);
4392 // This is the part where you do stuff!
4393 // override this function in implementation classes.
4394 // 'chunk' is an input chunk.
4396 // Call `push(newChunk)` to pass along transformed output
4397 // to the readable side. You may call 'push' zero or more times.
4399 // Call `cb(err)` when you are done with this chunk. If you pass
4400 // an error, then that'll put the hurt on the whole operation. If you
4401 // never call cb(), then you'll never get another chunk.
4402 Transform.prototype._transform = function (chunk, encoding, cb) {
4403 throw new Error('_transform() is not implemented');
4406 Transform.prototype._write = function (chunk, encoding, cb) {
4407 var ts = this._transformState;
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);
4417 // Doesn't matter what the args are here.
4418 // _transform does all the work.
4419 // That we got here means that the readable side wants more data.
4420 Transform.prototype._read = function (n) {
4421 var ts = this._transformState;
4423 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
4424 ts.transforming = true;
4425 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
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;
4433 function done(stream, er, data) {
4434 if (er) return stream.emit('error', er);
4436 if (data !== null && data !== undefined) stream.push(data);
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;
4443 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
4445 if (ts.transforming) throw new Error('Calling transform done when still transforming');
4447 return stream.push(null);
4449 },{"./_stream_duplex":15,"core-util-is":6,"inherits":9}],19:[function(require,module,exports){
4450 (function (process){
4451 // A bit simpler than readable streams.
4452 // Implement an async ._write(chunk, encoding, cb), and it'll handle all
4453 // the drain event emission and buffering.
4457 module.exports = Writable;
4460 var processNextTick
= require('process-nextick-args');
4464 var asyncWrite
= !process
.browser
&& ['v0.10', 'v0.9.'].indexOf(process
.version
.slice(0, 5)) > -1 ? setImmediate : processNextTick
;
4471 Writable.WritableState = WritableState;
4474 var util
= require('core-util-is');
4475 util
.inherits
= require('inherits');
4479 var internalUtil
= {
4480 deprecate: require('util-deprecate')
4485 var Stream
= require('./internal/streams/stream');
4488 var Buffer = require('buffer').Buffer;
4490 var bufferShim
= require('buffer-shims');
4493 util.inherits(Writable, Stream);
4497 function WriteReq(chunk, encoding, cb) {
4499 this.encoding = encoding;
4504 function WritableState(options, stream) {
4505 Duplex = Duplex || require('./_stream_duplex');
4507 options = options || {};
4509 // object stream flag to indicate whether or not this stream
4510 // contains buffers or objects.
4511 this.objectMode = !!options.objectMode;
4513 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
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;
4523 this.highWaterMark = ~~this.highWaterMark;
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
4531 // when 'finish' is emitted
4532 this.finished = false;
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;
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';
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
4550 // a flag to see when we're in the middle of a write.
4551 this.writing = false;
4553 // when true all writes will be buffered until .uncork() call
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.
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;
4567 // the callback that's passed to _write(chunk,cb)
4568 this.onwrite = function (er) {
4569 onwrite(stream, er);
4572 // the callback that the user supplies to write(chunk,encoding,cb)
4573 this.writecb = null;
4575 // the amount that is being written when _write is called.
4578 this.bufferedRequest = null;
4579 this.lastBufferedRequest = null;
4581 // number of pending user-supplied write callbacks
4582 // this must be 0 before 'finish' can be emitted
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;
4589 // True if the error was already emitted and should not be thrown again
4590 this.errorEmitted = false;
4592 // count buffered requests
4593 this.bufferedRequestCount = 0;
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);
4600 WritableState.prototype.getBuffer = function getBuffer() {
4601 var current = this.bufferedRequest;
4605 current = current.next;
4612 Object.defineProperty(WritableState.prototype, 'buffer', {
4613 get: internalUtil.deprecate(function () {
4614 return this.getBuffer();
4615 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
4620 // Test _writableState for inheritance to account for Duplex streams,
4621 // whose prototype chain only points to Readable.
4622 var realHasInstance;
4623 if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
4624 realHasInstance = Function.prototype[Symbol.hasInstance];
4625 Object.defineProperty(Writable, Symbol.hasInstance, {
4626 value: function (object) {
4627 if (realHasInstance.call(this, object)) return true;
4629 return object && object._writableState instanceof WritableState;
4633 realHasInstance = function (object) {
4634 return object instanceof this;
4638 function Writable(options) {
4639 Duplex = Duplex || require('./_stream_duplex');
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.
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);
4652 this._writableState = new WritableState(options, this);
4655 this.writable = true;
4658 if (typeof options.write === 'function') this._write = options.write;
4660 if (typeof options.writev === 'function') this._writev = options.writev;
4666 // Otherwise people can pipe Writable streams, which is just wrong.
4667 Writable.prototype.pipe = function () {
4668 this.emit('error', new Error('Cannot pipe, not readable'));
4671 function writeAfterEnd(stream, cb) {
4672 var er = new Error('write after end');
4673 // TODO: defer error events consistently everywhere, not just the cb
4674 stream.emit('error', er);
4675 processNextTick(cb, er);
4678 // Checks that a user-supplied chunk is valid, especially for the particular
4679 // mode the stream is in. Currently this means that `null` is never accepted
4680 // and undefined/non-string values are only allowed in object mode.
4681 function validChunk(stream, state, chunk, cb) {
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');
4691 stream.emit('error', er);
4692 processNextTick(cb, er);
4698 Writable.prototype.write = function (chunk, encoding, cb) {
4699 var state = this._writableState;
4701 var isBuf = Buffer.isBuffer(chunk);
4703 if (typeof encoding === 'function') {
4708 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
4710 if (typeof cb !== 'function') cb = nop;
4712 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
4714 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
4720 Writable.prototype.cork = function () {
4721 var state = this._writableState;
4726 Writable.prototype.uncork = function () {
4727 var state = this._writableState;
4732 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
4736 Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
4737 // node::ParseEncoding() requires lower case.
4738 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
4739 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
4740 this._writableState.defaultEncoding = encoding;
4744 function decodeChunk(state, chunk, encoding) {
4745 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
4746 chunk = bufferShim.from(chunk, encoding);
4751 // if we're already writing something, then just put this
4752 // in the queue, and wait our turn. Otherwise, call _write
4753 // If we return false, then we need a drain event, so set that flag.
4754 function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
4756 chunk = decodeChunk(state, chunk, encoding);
4757 if (Buffer.isBuffer(chunk)) encoding = 'buffer';
4759 var len = state.objectMode ? 1 : chunk.length;
4761 state.length += len;
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;
4767 if (state.writing || state.corked) {
4768 var last = state.lastBufferedRequest;
4769 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
4771 last.next = state.lastBufferedRequest;
4773 state.bufferedRequest = state.lastBufferedRequest;
4775 state.bufferedRequestCount += 1;
4777 doWrite(stream, state, false, len, chunk, encoding, cb);
4783 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
4784 state.writelen = len;
4786 state.writing = true;
4788 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
4792 function onwriteError(stream, state, sync, er, cb) {
4794 if (sync) processNextTick(cb, er);else cb(er);
4796 stream._writableState.errorEmitted = true;
4797 stream.emit('error', er);
4800 function onwriteStateUpdate(state) {
4801 state.writing = false;
4802 state.writecb = null;
4803 state.length -= state.writelen;
4807 function onwrite(stream, er) {
4808 var state = stream._writableState;
4809 var sync = state.sync;
4810 var cb = state.writecb;
4812 onwriteStateUpdate(state);
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);
4818 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
4819 clearBuffer(stream, state);
4824 asyncWrite(afterWrite
, stream
, state
, finished
, cb
);
4827 afterWrite(stream, state, finished, cb);
4832 function afterWrite(stream, state, finished, cb) {
4833 if (!finished) onwriteDrain(stream, state);
4836 finishMaybe(stream, state);
4839 // Must force callback to be called on nextTick, so that we don't
4840 // emit 'drain' before the write() consumer gets the 'false' return
4841 // value, and has a chance to attach a 'drain' listener.
4842 function onwriteDrain(stream, state) {
4843 if (state.length === 0 && state.needDrain) {
4844 state.needDrain = false;
4845 stream.emit('drain');
4849 // if there's something in the buffer waiting, then process it
4850 function clearBuffer(stream, state) {
4851 state.bufferProcessing = true;
4852 var entry = state.bufferedRequest;
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;
4863 buffer[count] = entry;
4868 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
4870 // doWrite is almost always async, defer these to save a bit of time
4871 // as the hot path ends with doWrite
4873 state.lastBufferedRequest = null;
4875 state.corkedRequestsFree = holder.next;
4878 state.corkedRequestsFree = new CorkedRequest(state);
4881 // Slow case, write chunks one-by-one
4883 var chunk = entry.chunk;
4884 var encoding = entry.encoding;
4885 var cb = entry.callback;
4886 var len = state.objectMode ? 1 : chunk.length;
4888 doWrite(stream, state, false, len, chunk, encoding, cb);
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) {
4899 if (entry === null) state.lastBufferedRequest = null;
4902 state.bufferedRequestCount = 0;
4903 state.bufferedRequest = entry;
4904 state.bufferProcessing = false;
4907 Writable.prototype._write = function (chunk, encoding, cb) {
4908 cb(new Error('_write() is not implemented'));
4911 Writable.prototype._writev = null;
4913 Writable.prototype.end = function (chunk, encoding, cb) {
4914 var state = this._writableState;
4916 if (typeof chunk === 'function') {
4920 } else if (typeof encoding === 'function') {
4925 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
4927 // .end() fully uncorks
4933 // ignore unnecessary end() calls.
4934 if (!state.ending && !state.finished) endWritable(this, state, cb);
4937 function needFinish(state) {
4938 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
4941 function prefinish(stream, state) {
4942 if (!state.prefinished) {
4943 state.prefinished = true;
4944 stream.emit('prefinish');
4948 function finishMaybe(stream, state) {
4949 var need = needFinish(state);
4951 if (state.pendingcb === 0) {
4952 prefinish(stream, state);
4953 state.finished = true;
4954 stream.emit('finish');
4956 prefinish(stream, state);
4962 function endWritable(stream, state, cb) {
4963 state.ending = true;
4964 finishMaybe(stream, state);
4966 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
4969 stream.writable = false;
4972 // It seems a linked list but it is not
4973 // there will be only 2 of these for each stream
4974 function CorkedRequest(state) {
4979 this.finish = function (err) {
4980 var entry = _this.entry;
4983 var cb = entry.callback;
4988 if (state.corkedRequestsFree) {
4989 state.corkedRequestsFree.next = _this;
4991 state.corkedRequestsFree = _this;
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){
4999 var Buffer = require('buffer').Buffer;
5001 var bufferShim
= require('buffer-shims');
5004 module.exports = BufferList;
5006 function BufferList() {
5012 BufferList.prototype.push = function (v) {
5013 var entry = { data: v, next: null };
5014 if (this.length > 0) this.tail.next = entry;else this.head = entry;
5019 BufferList.prototype.unshift = function (v) {
5020 var entry = { data: v, next: this.head };
5021 if (this.length === 0) this.tail = entry;
5026 BufferList.prototype.shift = function () {
5027 if (this.length === 0) return;
5028 var ret = this.head.data;
5029 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
5034 BufferList.prototype.clear = function () {
5035 this.head = this.tail = null;
5039 BufferList.prototype.join = function (s) {
5040 if (this.length === 0) return '';
5042 var ret = '' + p.data;
5043 while (p = p.next) {
5048 BufferList.prototype.concat = function (n) {
5049 if (this.length === 0) return bufferShim.alloc(0);
5050 if (this.length === 1) return this.head.data;
5051 var ret = bufferShim.allocUnsafe(n >>> 0);
5055 p.data.copy(ret, i);
5061 },{"buffer":5,"buffer-shims":4}],21:[function(require,module,exports){
5062 module.exports = require('events').EventEmitter;
5064 },{"events":7}],22:[function(require,module,exports){
5067 var Buffer = require('safe-buffer').Buffer;
5069 var isEncoding = Buffer.isEncoding || function (encoding) {
5070 encoding = '' + encoding;
5071 switch (encoding && encoding.toLowerCase()) {
5072 case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
5079 function _normalizeEncoding(enc) {
5080 if (!enc) return 'utf8';
5100 if (retried) return; // undefined
5101 enc = ('' + enc).toLowerCase();
5107 // Do not cache `Buffer.isEncoding` when checking encoding names as some
5108 // modules monkey-patch it to support additional encodings
5109 function normalizeEncoding(enc) {
5110 var nenc = _normalizeEncoding(enc);
5111 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
5115 // StringDecoder provides an interface for efficiently splitting a series of
5116 // buffers into a series of JS strings without breaking apart multi-byte
5118 exports.StringDecoder = StringDecoder;
5119 function StringDecoder(encoding) {
5120 this.encoding = normalizeEncoding(encoding);
5122 switch (this.encoding) {
5124 this.text = utf16Text;
5125 this.end = utf16End;
5129 this.fillLast = utf8FillLast;
5133 this.text = base64Text;
5134 this.end = base64End;
5138 this.write = simpleWrite;
5139 this.end = simpleEnd;
5144 this.lastChar = Buffer.allocUnsafe(nb);
5147 StringDecoder.prototype.write = function (buf) {
5148 if (buf.length === 0) return '';
5151 if (this.lastNeed) {
5152 r = this.fillLast(buf);
5153 if (r === undefined) return '';
5159 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
5163 StringDecoder.prototype.end = utf8End;
5165 // Returns only complete characters in a Buffer
5166 StringDecoder.prototype.text = utf8Text;
5168 // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
5169 StringDecoder.prototype.fillLast = function (buf) {
5170 if (this.lastNeed <= buf.length) {
5171 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
5172 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5174 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
5175 this.lastNeed -= buf.length;
5178 // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
5179 // continuation byte.
5180 function utf8CheckByte(byte) {
5181 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
5185 // Checks at most 3 bytes at the end of a Buffer in order to detect an
5186 // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
5187 // needed to complete the UTF-8 character (if applicable) are returned.
5188 function utf8CheckIncomplete(self, buf, i) {
5189 var j = buf.length - 1;
5190 if (j < i) return 0;
5191 var nb = utf8CheckByte(buf[j]);
5193 if (nb > 0) self.lastNeed = nb - 1;
5196 if (--j < i) return 0;
5197 nb = utf8CheckByte(buf[j]);
5199 if (nb > 0) self.lastNeed = nb - 2;
5202 if (--j < i) return 0;
5203 nb = utf8CheckByte(buf[j]);
5206 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
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
5221 function utf8CheckExtraBytes(self, buf, p) {
5222 if ((buf[0] & 0xC0) !== 0x80) {
5224 return '\ufffd'.repeat(p);
5226 if (self.lastNeed > 1 && buf.length > 1) {
5227 if ((buf[1] & 0xC0) !== 0x80) {
5229 return '\ufffd'.repeat(p + 1);
5231 if (self.lastNeed > 2 && buf.length > 2) {
5232 if ((buf[2] & 0xC0) !== 0x80) {
5234 return '\ufffd'.repeat(p + 2);
5240 // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
5241 function utf8FillLast(buf) {
5242 var p = this.lastTotal - this.lastNeed;
5243 var r = utf8CheckExtraBytes(this, buf, p);
5244 if (r !== undefined) return r;
5245 if (this.lastNeed <= buf.length) {
5246 buf.copy(this.lastChar, p, 0, this.lastNeed);
5247 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
5249 buf.copy(this.lastChar, p, 0, buf.length);
5250 this.lastNeed -= buf.length;
5253 // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
5254 // partial character, the character's bytes are buffered until the required
5255 // number of bytes are available.
5256 function utf8Text(buf, i) {
5257 var total = utf8CheckIncomplete(this, buf, i);
5258 if (!this.lastNeed) return buf.toString('utf8', i);
5259 this.lastTotal = total;
5260 var end = buf.length - (total - this.lastNeed);
5261 buf.copy(this.lastChar, 0, end);
5262 return buf.toString('utf8', i, end);
5265 // For UTF-8, a replacement character for each buffered byte of a (partial)
5266 // character needs to be added to the output.
5267 function utf8End(buf) {
5268 var r = buf && buf.length ? this.write(buf) : '';
5269 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
5273 // UTF-16LE typically needs two bytes per character, but even if we have an even
5274 // number of bytes available, we need to check if we end on a leading/high
5275 // surrogate. In that case, we need to wait for the next two bytes in order to
5276 // decode the last character properly.
5277 function utf16Text(buf, i) {
5278 if ((buf.length - i) % 2 === 0) {
5279 var r = buf.toString('utf16le', i);
5281 var c = r.charCodeAt(r.length - 1);
5282 if (c >= 0xD800 && c <= 0xDBFF) {
5285 this.lastChar[0] = buf[buf.length - 2];
5286 this.lastChar[1] = buf[buf.length - 1];
5287 return r.slice(0, -1);
5294 this.lastChar[0] = buf[buf.length - 1];
5295 return buf.toString('utf16le', i, buf.length - 1);
5298 // For UTF-16LE we do not explicitly append special replacement characters if we
5299 // end on a partial character, we simply let v8 handle that.
5300 function utf16End(buf) {
5301 var r = buf && buf.length ? this.write(buf) : '';
5302 if (this.lastNeed) {
5303 var end = this.lastTotal - this.lastNeed;
5304 return r + this.lastChar.toString('utf16le', 0, end);
5309 function base64Text(buf, i) {
5310 var n = (buf.length - i) % 3;
5311 if (n === 0) return buf.toString('base64', i);
5312 this.lastNeed = 3 - n;
5315 this.lastChar[0] = buf[buf.length - 1];
5317 this.lastChar[0] = buf[buf.length - 2];
5318 this.lastChar[1] = buf[buf.length - 1];
5320 return buf.toString('base64', i, buf.length - n);
5323 function base64End(buf) {
5324 var r = buf && buf.length ? this.write(buf) : '';
5325 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
5329 // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
5330 function simpleWrite(buf) {
5331 return buf.toString(this.encoding);
5334 function simpleEnd(buf) {
5335 return buf && buf.length ? this.write(buf) : '';
5337 },{"safe-buffer":27}],23:[function(require,module,exports){
5338 module.exports = require('./readable').PassThrough
5340 },{"./readable":24}],24:[function(require,module,exports){
5341 exports = module.exports = require('./lib/_stream_readable.js');
5342 exports.Stream = exports;
5343 exports.Readable = exports;
5344 exports.Writable = require('./lib/_stream_writable.js');
5345 exports.Duplex = require('./lib/_stream_duplex.js');
5346 exports.Transform = require('./lib/_stream_transform.js');
5347 exports.PassThrough = require('./lib/_stream_passthrough.js');
5349 },{"./lib/_stream_duplex.js":15,"./lib/_stream_passthrough.js":16,"./lib/_stream_readable.js":17,"./lib/_stream_transform.js":18,"./lib/_stream_writable.js":19}],25:[function(require,module,exports){
5350 module.exports = require('./readable').Transform
5352 },{"./readable":24}],26:[function(require,module,exports){
5353 module.exports = require('./lib/_stream_writable.js');
5355 },{"./lib/_stream_writable.js":19}],27:[function(require,module,exports){
5356 module.exports = require('buffer')
5358 },{"buffer":5}],28:[function(require,module,exports){
5359 // Copyright Joyent, Inc. and other Node contributors.
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:
5369 // The above copyright notice and this permission notice shall be included
5370 // in all copies or substantial portions of the Software.
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.
5380 module.exports = Stream;
5382 var EE = require('events').EventEmitter;
5383 var inherits = require('inherits');
5385 inherits(Stream, EE);
5386 Stream.Readable = require('readable-stream/readable.js');
5387 Stream.Writable = require('readable-stream/writable.js');
5388 Stream.Duplex = require('readable-stream/duplex.js');
5389 Stream.Transform = require('readable-stream/transform.js');
5390 Stream.PassThrough = require('readable-stream/passthrough.js');
5392 // Backwards-compat with node 0.4.x
5393 Stream.Stream = Stream;
5397 // old-style streams. Note that the pipe method (the only relevant
5398 // part of this class) is overridden in the Readable class.
5404 Stream.prototype.pipe = function(dest, options) {
5407 function ondata(chunk) {
5408 if (dest.writable) {
5409 if (false === dest.write(chunk) && source.pause) {
5415 source.on('data', ondata);
5417 function ondrain() {
5418 if (source.readable && source.resume) {
5423 dest.on('drain', ondrain);
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);
5432 var didOnEnd = false;
5434 if (didOnEnd) return;
5441 function onclose() {
5442 if (didOnEnd) return;
5445 if (typeof dest.destroy === 'function') dest.destroy();
5448 // don't leave dangling pipes when there are errors.
5449 function onerror(er) {
5451 if (EE.listenerCount(this, 'error') === 0) {
5452 throw er; // Unhandled stream error in pipe.
5456 source.on('error', onerror);
5457 dest.on('error', onerror);
5459 // remove all the event listeners that were added.
5460 function cleanup() {
5461 source.removeListener('data', ondata);
5462 dest.removeListener('drain', ondrain);
5464 source.removeListener('end', onend);
5465 source.removeListener('close', onclose);
5467 source.removeListener('error', onerror);
5468 dest.removeListener('error', onerror);
5470 source.removeListener('end', cleanup);
5471 source.removeListener('close', cleanup);
5473 dest.removeListener('close', cleanup);
5476 source.on('end', cleanup);
5477 source.on('close', cleanup);
5479 dest.on('close', cleanup);
5481 dest.emit('pipe', source);
5483 // Allow for unix-like usage: A.pipe(B).pipe(C)
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.
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:
5498 // The above copyright notice and this permission notice shall be included
5499 // in all copies or substantial portions of the Software.
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.
5509 var Buffer = require('buffer').Buffer;
5511 var isBufferEncoding = Buffer.isEncoding
5512 || function(encoding) {
5513 switch (encoding && encoding.toLowerCase()) {
5514 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
5515 default: return false;
5520 function assertEncoding(encoding) {
5521 if (encoding && !isBufferEncoding(encoding)) {
5522 throw new Error('Unknown encoding: ' + encoding);
5526 // StringDecoder provides an interface for efficiently splitting a series of
5527 // buffers into a series of JS strings without breaking apart multi-byte
5528 // characters. CESU-8 is handled as part of the UTF-8 encoding.
5530 // @TODO Handling all encodings inside a single object makes it very difficult
5531 // to reason about this code, so it should be split up in the future.
5532 // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
5533 // points as used by CESU-8.
5534 var StringDecoder = exports.StringDecoder = function(encoding) {
5535 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
5536 assertEncoding(encoding);
5537 switch (this.encoding) {
5539 // CESU-8 represents each of Surrogate Pair by 3-bytes
5540 this.surrogateSize = 3;
5544 // UTF-16 represents each of Surrogate Pair by 2-bytes
5545 this.surrogateSize = 2;
5546 this.detectIncompleteChar = utf16DetectIncompleteChar;
5549 // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
5550 this.surrogateSize = 3;
5551 this.detectIncompleteChar = base64DetectIncompleteChar;
5554 this.write = passThroughWrite;
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;
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.
5573 // Note: Converting a Buffer containing an orphan surrogate to a String
5574 // currently works, but converting a String to a Buffer (via `new Buffer`, or
5575 // Buffer#write) will replace incomplete surrogates with the unicode
5576 // replacement character. See https://codereview.chromium.org/121173009/ .
5577 StringDecoder.prototype.write = function(buffer) {
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 :
5586 // add the new bytes to the char buffer
5587 buffer.copy(this.charBuffer, this.charReceived, 0, available);
5588 this.charReceived += available;
5590 if (this.charReceived < this.charLength) {
5591 // still not enough chars in this buffer? wait for more ...
5595 // remove bytes belonging to the current character from the buffer
5596 buffer = buffer.slice(available, buffer.length);
5598 // get the character that was split
5599 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
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;
5608 this.charReceived = this.charLength = 0;
5610 // if there are no more bytes in this buffer, just emit our char
5611 if (buffer.length === 0) {
5617 // determine and set charLength / charReceived
5618 this.detectIncompleteChar(buffer);
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;
5627 charStr += buffer.toString(this.encoding, 0, end);
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);
5641 // or just emit the charStr
5645 // detectIncompleteChar determines if there is an incomplete UTF-8 character at
5646 // the end of the given buffer. If so, it sets this.charLength to the byte
5647 // length that character, and sets this.charReceived to the number of bytes
5648 // that are available for this character.
5649 StringDecoder.prototype.detectIncompleteChar = function(buffer) {
5650 // determine how many bytes we have to check at the end of this buffer
5651 var i = (buffer.length >= 3) ? 3 : buffer.length;
5653 // Figure out if one of the last i bytes of our buffer announces an
5655 for (; i > 0; i--) {
5656 var c = buffer[buffer.length - i];
5658 // See http://en.wikipedia.org/wiki/UTF-8#Description
5661 if (i == 1 && c >> 5 == 0x06) {
5662 this.charLength = 2;
5667 if (i <= 2 && c >> 4 == 0x0E) {
5668 this.charLength = 3;
5673 if (i <= 3 && c >> 3 == 0x1E) {
5674 this.charLength = 4;
5678 this.charReceived = i;
5681 StringDecoder.prototype.end = function(buffer) {
5683 if (buffer && buffer.length)
5684 res = this.write(buffer);
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);
5696 function passThroughWrite(buffer) {
5697 return buffer.toString(this.encoding);
5700 function utf16DetectIncompleteChar(buffer) {
5701 this.charReceived = buffer.length % 2;
5702 this.charLength = this.charReceived ? 2 : 0;
5705 function base64DetectIncompleteChar(buffer) {
5706 this.charReceived = buffer.length % 3;
5707 this.charLength = this.charReceived ? 3 : 0;
5710 },{"buffer":5}],30:[function(require,module,exports){
5717 module
.exports
= deprecate
;
5720 * Mark that a method should not be used.
5721 * Returns a modified function which warns once by default.
5723 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
5725 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
5726 * will throw an Error when invoked.
5728 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
5729 * will invoke `console.trace()` instead of `console.error()`.
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`
5737 function deprecate (fn
, msg
) {
5738 if (config('noDeprecation')) {
5743 function deprecated() {
5745 if (config('throwDeprecation')) {
5746 throw new Error(msg
);
5747 } else if (config('traceDeprecation')) {
5754 return fn
.apply(this, arguments
);
5761 * Checks `localStorage` for boolean values for the given `name`.
5763 * @param {String} name
5764 * @returns {Boolean}
5768 function config (name
) {
5769 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
5771 if (!global
.localStorage
) return false;
5775 var val
= global
.localStorage
[name
];
5776 if (null == val
) return false;
5777 return String(val
).toLowerCase() === 'true';
5780 }).call(this,typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
5781 },{}],31:[function(require
,module
,exports
){
5782 arguments
[4][9][0].apply(exports
,arguments
)
5783 },{"dup":9}],32:[function(require
,module
,exports
){
5784 module
.exports
= function isBuffer(arg
) {
5785 return arg
&& typeof arg
=== 'object'
5786 && typeof arg
.copy
=== 'function'
5787 && typeof arg
.fill
=== 'function'
5788 && typeof arg
.readUInt8
=== 'function';
5790 },{}],33:[function(require
,module
,exports
){
5791 (function (process
,global
){
5792 // Copyright Joyent, Inc. and other Node contributors.
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:
5802 // The above copyright notice and this permission notice shall be included
5803 // in all copies or substantial portions of the Software.
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.
5813 var formatRegExp
= /%[sdj%]/g;
5814 exports
.format = function(f
) {
5817 for (var i
= 0; i
< arguments
.length
; i
++) {
5818 objects
.push(inspect(arguments
[i
]));
5820 return objects
.join(' ');
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
;
5830 case '%s': return String(args
[i
++]);
5831 case '%d': return Number(args
[i
++]);
5834 return JSON
.stringify(args
[i
++]);
5836 return '[Circular]';
5842 for (var x
= args
[i
]; i
< len
; x
= args
[++i
]) {
5843 if (isNull(x
) || !isObject(x
)) {
5846 str
+= ' ' + inspect(x
);
5853 // Mark that a method should not be used.
5854 // Returns a modified function which warns once by default.
5855 // If --no-deprecation is set, then it is a no-op.
5856 exports
.deprecate = function(fn
, msg
) {
5857 // Allow for deprecating things in the process of starting up.
5858 if (isUndefined(global
.process
)) {
5860 return exports
.deprecate(fn
, msg
).apply(this, arguments
);
5864 if (process
.noDeprecation
=== true) {
5869 function deprecated() {
5871 if (process
.throwDeprecation
) {
5872 throw new Error(msg
);
5873 } else if (process
.traceDeprecation
) {
5880 return fn
.apply(this, arguments
);
5889 exports
.debuglog = function(set) {
5890 if (isUndefined(debugEnviron
))
5891 debugEnviron
= process
.env
.NODE_DEBUG
|| '';
5892 set = set.toUpperCase();
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
);
5901 debugs
[set] = function() {};
5909 * Echos the value of a value. Trys to print the value out
5910 * in the best way possible given the different types.
5912 * @param {Object} obj The object to print out.
5913 * @param {Object} opts Optional options object that alters the output.
5915 /* legacy: obj, showHidden, depth, colors*/
5916 function inspect(obj
, opts
) {
5920 stylize: stylizeNoColor
5923 if (arguments
.length
>= 3) ctx
.depth
= arguments
[2];
5924 if (arguments
.length
>= 4) ctx
.colors
= arguments
[3];
5925 if (isBoolean(opts
)) {
5927 ctx
.showHidden
= opts
;
5929 // got an "options" object
5930 exports
._extend(ctx
, opts
);
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
);
5940 exports
.inspect
= inspect
;
5943 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
5947 'underline' : [4, 24],
5948 'inverse' : [7, 27],
5955 'magenta' : [35, 39],
5960 // Don't use 'blue' not visible on cmd.exe
5964 'boolean': 'yellow',
5965 'undefined': 'grey',
5969 // "name": intentionally not styling
5974 function stylizeWithColor(str
, styleType
) {
5975 var style
= inspect
.styles
[styleType
];
5978 return '\u001b[' + inspect
.colors
[style
][0] + 'm' + str
+
5979 '\u001b[' + inspect
.colors
[style
][1] + 'm';
5986 function stylizeNoColor(str
, styleType
) {
5991 function arrayToHash(array
) {
5994 array
.forEach(function(val
, idx
) {
6002 function formatValue(ctx
, value
, recurseTimes
) {
6003 // Provide a hook for user-specified inspect functions.
6004 // Check that value is an object with an inspect function on it
6005 if (ctx
.customInspect
&&
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
);
6019 // Primitive types cannot have properties
6020 var primitive
= formatPrimitive(ctx
, value
);
6025 // Look up the keys of the object.
6026 var keys
= Object
.keys(value
);
6027 var visibleKeys
= arrayToHash(keys
);
6029 if (ctx
.showHidden
) {
6030 keys
= Object
.getOwnPropertyNames(value
);
6033 // IE doesn't make error fields non-enumerable
6034 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
6036 && (keys
.indexOf('message') >= 0 || keys
.indexOf('description') >= 0)) {
6037 return formatError(value
);
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');
6046 if (isRegExp(value
)) {
6047 return ctx
.stylize(RegExp
.prototype.toString
.call(value
), 'regexp');
6049 if (isDate(value
)) {
6050 return ctx
.stylize(Date
.prototype.toString
.call(value
), 'date');
6052 if (isError(value
)) {
6053 return formatError(value
);
6057 var base
= '', array
= false, braces
= ['{', '}'];
6059 // Make Array say that they are Array
6060 if (isArray(value
)) {
6062 braces
= ['[', ']'];
6065 // Make functions say that they are functions
6066 if (isFunction(value
)) {
6067 var n
= value
.name
? ': ' + value
.name : '';
6068 base
= ' [Function' + n
+ ']';
6071 // Make RegExps say that they are RegExps
6072 if (isRegExp(value
)) {
6073 base
= ' ' + RegExp
.prototype.toString
.call(value
);
6076 // Make dates with properties first say the date
6077 if (isDate(value
)) {
6078 base
= ' ' + Date
.prototype.toUTCString
.call(value
);
6081 // Make error with message first say the error
6082 if (isError(value
)) {
6083 base
= ' ' + formatError(value
);
6086 if (keys
.length
=== 0 && (!array
|| value
.length
== 0)) {
6087 return braces
[0] + base
+ braces
[1];
6090 if (recurseTimes
< 0) {
6091 if (isRegExp(value
)) {
6092 return ctx
.stylize(RegExp
.prototype.toString
.call(value
), 'regexp');
6094 return ctx
.stylize('[Object]', 'special');
6098 ctx
.seen
.push(value
);
6102 output
= formatArray(ctx
, value
, recurseTimes
, visibleKeys
, keys
);
6104 output
= keys
.map(function(key
) {
6105 return formatProperty(ctx
, value
, recurseTimes
, visibleKeys
, key
, array
);
6111 return reduceToSingleString(output
, base
, braces
);
6115 function formatPrimitive(ctx
, value
) {
6116 if (isUndefined(value
))
6117 return ctx
.stylize('undefined', 'undefined');
6118 if (isString(value
)) {
6119 var simple
= '\'' + JSON
.stringify(value
).replace(/^"|"$/g, '')
6120 .replace(/'/g, "\\'")
6121 .replace(/\\"/g
, '"') + '\'';
6122 return ctx
.stylize(simple
, 'string');
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.
6130 return ctx
.stylize('null', 'null');
6134 function formatError(value
) {
6135 return '[' + Error
.prototype.toString
.call(value
) + ']';
6139 function formatArray(ctx
, value
, recurseTimes
, visibleKeys
, keys
) {
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
,
6149 keys
.forEach(function(key
) {
6150 if (!key
.match(/^\d+$/)) {
6151 output
.push(formatProperty(ctx
, value
, recurseTimes
, visibleKeys
,
6159 function formatProperty(ctx
, value
, recurseTimes
, visibleKeys
, key
, array
) {
6160 var name
, str
, desc
;
6161 desc
= Object
.getOwnPropertyDescriptor(value
, key
) || { value: value
[key
] };
6164 str
= ctx
.stylize('[Getter/Setter]', 'special');
6166 str
= ctx
.stylize('[Getter]', 'special');
6170 str
= ctx
.stylize('[Setter]', 'special');
6173 if (!hasOwnProperty(visibleKeys
, key
)) {
6174 name
= '[' + key
+ ']';
6177 if (ctx
.seen
.indexOf(desc
.value
) < 0) {
6178 if (isNull(recurseTimes
)) {
6179 str
= formatValue(ctx
, desc
.value
, null);
6181 str
= formatValue(ctx
, desc
.value
, recurseTimes
- 1);
6183 if (str
.indexOf('\n') > -1) {
6185 str
= str
.split('\n').map(function(line
) {
6187 }).join('\n').substr(2);
6189 str
= '\n' + str
.split('\n').map(function(line
) {
6195 str
= ctx
.stylize('[Circular]', 'special');
6198 if (isUndefined(name
)) {
6199 if (array
&& key
.match(/^\d+$/)) {
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');
6207 name
= name
.replace(/'/g, "\\'")
6208 .replace(/\\"/g
, '"')
6209 .replace(/(^"|"$)/g, "'");
6210 name
= ctx
.stylize(name
, 'string');
6214 return name
+ ': ' + str
;
6218 function reduceToSingleString(output
, base
, braces
) {
6219 var numLinesEst
= 0;
6220 var length
= output
.reduce(function(prev
, cur
) {
6222 if (cur
.indexOf('\n') >= 0) numLinesEst
++;
6223 return prev
+ cur
.replace(/\u001b\[\d\d?m/g, '').length
+ 1;
6228 (base
=== '' ? '' : base
+ '\n ') +
6230 output
.join(',\n ') +
6235 return braces
[0] + base
+ ' ' + output
.join(', ') + ' ' + braces
[1];
6239 // NOTE: These type checking functions intentionally don't use `instanceof`
6240 // because it is fragile and can be easily faked with `Object.create()`.
6241 function isArray(ar
) {
6242 return Array
.isArray(ar
);
6244 exports
.isArray
= isArray
;
6246 function isBoolean(arg
) {
6247 return typeof arg
=== 'boolean';
6249 exports
.isBoolean
= isBoolean
;
6251 function isNull(arg
) {
6252 return arg
=== null;
6254 exports
.isNull
= isNull
;
6256 function isNullOrUndefined(arg
) {
6259 exports
.isNullOrUndefined
= isNullOrUndefined
;
6261 function isNumber(arg
) {
6262 return typeof arg
=== 'number';
6264 exports
.isNumber
= isNumber
;
6266 function isString(arg
) {
6267 return typeof arg
=== 'string';
6269 exports
.isString
= isString
;
6271 function isSymbol(arg
) {
6272 return typeof arg
=== 'symbol';
6274 exports
.isSymbol
= isSymbol
;
6276 function isUndefined(arg
) {
6277 return arg
=== void 0;
6279 exports
.isUndefined
= isUndefined
;
6281 function isRegExp(re
) {
6282 return isObject(re
) && objectToString(re
) === '[object RegExp]';
6284 exports
.isRegExp
= isRegExp
;
6286 function isObject(arg
) {
6287 return typeof arg
=== 'object' && arg
!== null;
6289 exports
.isObject
= isObject
;
6291 function isDate(d
) {
6292 return isObject(d
) && objectToString(d
) === '[object Date]';
6294 exports
.isDate
= isDate
;
6296 function isError(e
) {
6297 return isObject(e
) &&
6298 (objectToString(e
) === '[object Error]' || e
instanceof Error
);
6300 exports
.isError
= isError
;
6302 function isFunction(arg
) {
6303 return typeof arg
=== 'function';
6305 exports
.isFunction
= isFunction
;
6307 function isPrimitive(arg
) {
6308 return arg
=== null ||
6309 typeof arg
=== 'boolean' ||
6310 typeof arg
=== 'number' ||
6311 typeof arg
=== 'string' ||
6312 typeof arg
=== 'symbol' || // ES6 symbol
6313 typeof arg
=== 'undefined';
6315 exports
.isPrimitive
= isPrimitive
;
6317 exports
.isBuffer
= require('./support/isBuffer');
6319 function objectToString(o
) {
6320 return Object
.prototype.toString
.call(o
);
6325 return n
< 10 ? '0' + n
.toString(10) : n
.toString(10);
6329 var months
= ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
6330 'Oct', 'Nov', 'Dec'];
6333 function timestamp() {
6335 var time
= [pad(d
.getHours()),
6336 pad(d
.getMinutes()),
6337 pad(d
.getSeconds())].join(':');
6338 return [d
.getDate(), months
[d
.getMonth()], time
].join(' ');
6342 // log is just a thin wrapper to console.log that prepends a timestamp
6343 exports
.log = function() {
6344 console
.log('%s - %s', timestamp(), exports
.format
.apply(exports
, arguments
));
6349 * Inherit the prototype methods from one constructor into another.
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).
6357 * @param {function} ctor Constructor function which needs to inherit the
6359 * @param {function} superCtor Constructor function to inherit prototype from.
6361 exports
.inherits
= require('inherits');
6363 exports
._extend = function(origin
, add
) {
6364 // Don't do anything if add isn't an object
6365 if (!add
|| !isObject(add
)) return origin
;
6367 var keys
= Object
.keys(add
);
6368 var i
= keys
.length
;
6370 origin
[keys
[i
]] = add
[keys
[i
]];
6375 function hasOwnProperty(obj
, prop
) {
6376 return Object
.prototype.hasOwnProperty
.call(obj
, prop
);
6379 }).call(this,require('_process'),typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
6380 },{"./support/isBuffer":32,"_process":13,"inherits":31}],34:[function(require
,module
,exports
){
6381 let bitcoin
= require('bitcoinjs-lib');
6387 },{"bitcoinjs-lib":52}],35:[function(require
,module
,exports
){
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
6396 var Buffer
= require('safe-buffer').Buffer
6398 module
.exports
= function base (ALPHABET
) {
6399 var ALPHABET_MAP
= {}
6400 var BASE
= ALPHABET
.length
6401 var LEADER
= ALPHABET
.charAt(0)
6403 // pre-compute lookup table
6404 for (var z
= 0; z
< ALPHABET
.length
; z
++) {
6405 var x
= ALPHABET
.charAt(z
)
6407 if (ALPHABET_MAP
[x
] !== undefined) throw new TypeError(x
+ ' is ambiguous')
6411 function encode (source
) {
6412 if (source
.length
=== 0) return ''
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
6423 digits
.push(carry
% BASE
)
6424 carry
= (carry
/ BASE
) | 0
6430 // deal with leading zeros
6431 for (var k
= 0; source
[k
] === 0 && k
< source
.length
- 1; ++k
) string
+= LEADER
6432 // convert digits to a string
6433 for (var q
= digits
.length
- 1; q
>= 0; --q
) string
+= ALPHABET
[digits
[q
]]
6438 function decodeUnsafe (string
) {
6439 if (typeof string
!== 'string') throw new TypeError('Expected String')
6440 if (string
.length
=== 0) return Buffer
.allocUnsafe(0)
6443 for (var i
= 0; i
< string
.length
; i
++) {
6444 var value
= ALPHABET_MAP
[string
[i
]]
6445 if (value
=== undefined) return
6447 for (var j
= 0, carry
= value
; j
< bytes
.length
; ++j
) {
6448 carry
+= bytes
[j
] * BASE
6449 bytes
[j
] = carry
& 0xff
6454 bytes
.push(carry
& 0xff)
6459 // deal with leading zeros
6460 for (var k
= 0; string
[k
] === LEADER
&& k
< string
.length
- 1; ++k
) {
6464 return Buffer
.from(bytes
.reverse())
6467 function decode (string
) {
6468 var buffer
= decodeUnsafe(string
)
6469 if (buffer
) return buffer
6471 throw new Error('Non-base' + BASE
+ ' character')
6476 decodeUnsafe: decodeUnsafe
,
6481 },{"safe-buffer":101}],36:[function(require
,module
,exports
){
6483 var ALPHABET
= 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
6485 // pre-compute lookup table
6486 var ALPHABET_MAP
= {}
6487 for (var z
= 0; z
< ALPHABET
.length
; z
++) {
6488 var x
= ALPHABET
.charAt(z
)
6490 if (ALPHABET_MAP
[x
] !== undefined) throw new TypeError(x
+ ' is ambiguous')
6494 function polymodStep (pre
) {
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)
6504 function prefixChk (prefix
) {
6506 for (var i
= 0; i
< prefix
.length
; ++i
) {
6507 var c
= prefix
.charCodeAt(i
)
6508 if (c
< 33 || c
> 126) throw new Error('Invalid prefix (' + prefix
+ ')')
6510 chk
= polymodStep(chk
) ^ (c
>> 5)
6512 chk
= polymodStep(chk
)
6514 for (i
= 0; i
< prefix
.length
; ++i
) {
6515 var v
= prefix
.charCodeAt(i
)
6516 chk
= polymodStep(chk
) ^ (v
& 0x1f)
6521 function encode (prefix
, words
, LIMIT
) {
6523 if ((prefix
.length
+ 7 + words
.length
) > LIMIT
) throw new TypeError('Exceeds length limit')
6525 prefix
= prefix
.toLowerCase()
6527 // determine chk mod
6528 var chk
= prefixChk(prefix
)
6529 var result
= prefix
+ '1'
6530 for (var i
= 0; i
< words
.length
; ++i
) {
6532 if ((x
>> 5) !== 0) throw new Error('Non 5-bit word')
6534 chk
= polymodStep(chk
) ^ x
6535 result
+= ALPHABET
.charAt(x
)
6538 for (i
= 0; i
< 6; ++i
) {
6539 chk
= polymodStep(chk
)
6543 for (i
= 0; i
< 6; ++i
) {
6544 var v
= (chk
>> ((5 - i
) * 5)) & 0x1f
6545 result
+= ALPHABET
.charAt(v
)
6551 function decode (str
, LIMIT
) {
6553 if (str
.length
< 8) throw new TypeError(str
+ ' too short')
6554 if (str
.length
> LIMIT
) throw new TypeError('Exceeds length limit')
6556 // don't allow mixed case
6557 var lowered
= str
.toLowerCase()
6558 var uppered
= str
.toUpperCase()
6559 if (str
!== lowered
&& str
!== uppered
) throw new Error('Mixed-case string ' + str
)
6562 var split
= str
.lastIndexOf('1')
6563 if (split
=== -1) throw new Error('No separator character for ' + str
)
6564 if (split
=== 0) throw new Error('Missing prefix for ' + str
)
6566 var prefix
= str
.slice(0, split
)
6567 var wordChars
= str
.slice(split
+ 1)
6568 if (wordChars
.length
< 6) throw new Error('Data too short')
6570 var chk
= prefixChk(prefix
)
6572 for (var i
= 0; i
< wordChars
.length
; ++i
) {
6573 var c
= wordChars
.charAt(i
)
6574 var v
= ALPHABET_MAP
[c
]
6575 if (v
=== undefined) throw new Error('Unknown character ' + c
)
6576 chk
= polymodStep(chk
) ^ v
6578 // not in the checksum?
6579 if (i
+ 6 >= wordChars
.length
) continue
6583 if (chk
!== 1) throw new Error('Invalid checksum for ' + str
)
6584 return { prefix: prefix
, words: words
}
6587 function convert (data
, inBits
, outBits
, pad
) {
6590 var maxV
= (1 << outBits
) - 1
6593 for (var i
= 0; i
< data
.length
; ++i
) {
6594 value
= (value
<< inBits
) | data
[i
]
6597 while (bits
>= outBits
) {
6599 result
.push((value
>> bits
) & maxV
)
6605 result
.push((value
<< (outBits
- bits
)) & maxV
)
6608 if (bits
>= inBits
) throw new Error('Excess padding')
6609 if ((value
<< (outBits
- bits
)) & maxV
) throw new Error('Non-zero padding')
6615 function toWords (bytes
) {
6616 return convert(bytes
, 8, 5, true)
6619 function fromWords (words
) {
6620 return convert(words
, 5, 8, false)
6627 fromWords: fromWords
6630 },{}],37:[function(require
,module
,exports
){
6631 // (public) Constructor
6632 function BigInteger(a
, b
, c
) {
6633 if (!(this instanceof BigInteger
))
6634 return new BigInteger(a
, b
, c
)
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
)
6643 var proto
= BigInteger
.prototype
6645 // duck-typed isBigInteger
6646 proto
.__bigi
= require('../package.json').version
6647 BigInteger
.isBigInteger = function (obj
, check_ver
) {
6648 return obj
&& obj
.__bigi
&& (!check_ver
|| obj
.__bigi
=== proto
.__bigi
)
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.
6659 // am1: use a single mult and divide to get the high bits,
6660 // max digit bits should be 26 because
6661 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
6662 function am1(i
, x
, w
, j
, c
, n
) {
6664 var v
= x
* this[i
++] + w
[j
] + c
6665 c
= Math
.floor(v
/ 0x4000000)
6666 w
[j
++] = v
& 0x3ffffff
6670 // am2 avoids a big mult-and-extract completely.
6671 // Max digit bits should be <= 30 because we do bitwise ops
6672 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
6673 function am2(i
, x
, w
, j
, c
, n
) {
6674 var xl
= x
& 0x7fff,
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
6686 // Alternately, set max digit bits to 28 since some
6687 // browsers slow down when dealing with 32-bit numbers.
6688 function am3(i
, x
, w
, j
, c
, n
) {
6689 var xl
= x
& 0x3fff,
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
6703 BigInteger
.prototype.am
= am1
6706 BigInteger
.prototype.DB
= dbits
6707 BigInteger
.prototype.DM
= ((1 << dbits
) - 1)
6708 var DV
= BigInteger
.prototype.DV
= (1 << dbits
)
6711 BigInteger
.prototype.FV
= Math
.pow(2, BI_FP
)
6712 BigInteger
.prototype.F1
= BI_FP
- dbits
6713 BigInteger
.prototype.F2
= 2 * dbits
- BI_FP
6715 // Digit conversions
6716 var BI_RM
= "0123456789abcdefghijklmnopqrstuvwxyz"
6717 var BI_RC
= new Array()
6719 rr
= "0".charCodeAt(0)
6720 for (vv
= 0; vv
<= 9; ++vv
) BI_RC
[rr
++] = vv
6721 rr
= "a".charCodeAt(0)
6722 for (vv
= 10; vv
< 36; ++vv
) BI_RC
[rr
++] = vv
6723 rr
= "A".charCodeAt(0)
6724 for (vv
= 10; vv
< 36; ++vv
) BI_RC
[rr
++] = vv
6726 function int2char(n
) {
6727 return BI_RM
.charAt(n
)
6730 function intAt(s
, i
) {
6731 var c
= BI_RC
[s
.charCodeAt(i
)]
6732 return (c
== null) ? -1 : c
6735 // (protected) copy this to r
6736 function bnpCopyTo(r
) {
6737 for (var i
= this.t
- 1; i
>= 0; --i
) r
[i
] = this[i
]
6742 // (protected) set from integer value x, -DV <= x < DV
6743 function bnpFromInt(x
) {
6745 this.s
= (x
< 0) ? -1 : 0
6746 if (x
> 0) this[0] = x
6747 else if (x
< -1) this[0] = x
+ DV
6751 // return bigint initialized to value
6753 var r
= new BigInteger()
6758 // (protected) set from string and radix
6759 function bnpFromString(s
, b
) {
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
6770 self
.fromRadix(s
, b
)
6779 var x
= (k
== 8) ? s
[i
] & 0xff : intAt(s
, i
)
6781 if (s
.charAt(i
) == "-") mi
= true
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
))
6791 self
[self
.t
- 1] |= x
<< sh
6793 if (sh
>= self
.DB
) sh
-= self
.DB
6795 if (k
== 8 && (s
[0] & 0x80) != 0) {
6797 if (sh
> 0) self
[self
.t
- 1] |= ((1 << (self
.DB
- sh
)) - 1) << sh
6800 if (mi
) BigInteger
.ZERO
.subTo(self
, self
)
6803 // (protected) clamp off excess high words
6804 function bnpClamp() {
6805 var c
= this.s
& this.DM
6806 while (this.t
> 0 && this[this.t
- 1] == c
)--this.t
6809 // (public) return string representation in given radix
6810 function bnToString(b
) {
6812 if (self
.s
< 0) return "-" + self
.negate()
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,
6825 var p
= self
.DB
- (i
* self
.DB
) % k
6827 if (p
< self
.DB
&& (d
= self
[i
] >> p
) > 0) {
6833 d
= (self
[i
] & ((1 << p
) - 1)) << (k
- p
)
6834 d
|= self
[--i
] >> (p
+= self
.DB
- k
)
6836 d
= (self
[i
] >> (p
-= k
)) & km
6843 if (m
) r
+= int2char(d
)
6850 function bnNegate() {
6851 var r
= new BigInteger()
6852 BigInteger
.ZERO
.subTo(this, r
)
6858 return (this.s
< 0) ? this.negate() : this
6861 // (public) return + if this > a, - if this < a, 0 if equal
6862 function bnCompareTo(a
) {
6863 var r
= this.s
- a
.s
6864 if (r
!= 0) return r
6867 if (r
!= 0) return (this.s
< 0) ? -r : r
6869 if ((r
= this[i
] - a
[i
]) != 0) return r
6873 // returns bit length of the integer x
6877 if ((t
= x
>>> 16) != 0) {
6881 if ((t
= x
>> 8) != 0) {
6885 if ((t
= x
>> 4) != 0) {
6889 if ((t
= x
>> 2) != 0) {
6893 if ((t
= x
>> 1) != 0) {
6900 // (public) return the number of bits in "this"
6901 function bnBitLength() {
6902 if (this.t
<= 0) return 0
6903 return this.DB
* (this.t
- 1) + nbits(this[this.t
- 1] ^ (this.s
& this.DM
))
6906 // (public) return the number of bytes in "this"
6907 function bnByteLength() {
6908 return this.bitLength() >> 3
6911 // (protected) r = this << n*DB
6912 function bnpDLShiftTo(n
, r
) {
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
6920 // (protected) r = this >> n*DB
6921 function bnpDRShiftTo(n
, r
) {
6922 for (var i
= n
; i
< this.t
; ++i
) r
[i
- n
] = this[i
]
6923 r
.t
= Math
.max(this.t
- n
, 0)
6927 // (protected) r = this << n
6928 function bnpLShiftTo(n
, r
) {
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
,
6936 for (i
= self
.t
- 1; i
>= 0; --i
) {
6937 r
[i
+ ds
+ 1] = (self
[i
] >> cbs
) | c
6938 c
= (self
[i
] & bm
) << bs
6940 for (i
= ds
- 1; i
>= 0; --i
) r
[i
] = 0
6942 r
.t
= self
.t
+ ds
+ 1
6947 // (protected) r = this >> n
6948 function bnpRShiftTo(n
, r
) {
6951 var ds
= Math
.floor(n
/ self
.DB
)
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
6964 if (bs
> 0) r
[self
.t
- ds
- 1] |= (self
.s
& bm
) << cbs
6969 // (protected) r = this - a
6970 function bnpSubTo(a
, r
) {
6974 m
= Math
.min(a
.t
, self
.t
)
6977 r
[i
++] = c
& self
.DM
6982 while (i
< self
.t
) {
6984 r
[i
++] = c
& self
.DM
6992 r
[i
++] = c
& self
.DM
6997 r
.s
= (c
< 0) ? -1 : 0
6998 if (c
< -1) r
[i
++] = self
.DV
+ c
6999 else if (c
> 0) r
[i
++] = c
7004 // (protected) r = this * a, r != this,a (HAC 14.12)
7005 // "this" should be the larger one if appropriate.
7006 function bnpMultiplyTo(a
, r
) {
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
)
7015 if (this.s
!= a
.s
) BigInteger
.ZERO
.subTo(r
, r
)
7018 // (protected) r = this^2, r != this (HAC 14.16)
7019 function bnpSquareTo(r
) {
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
) {
7030 if (r
.t
> 0) r
[r
.t
- 1] += x
.am(i
, x
[i
], r
, 2 * i
, 0, 1)
7035 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
7036 // r != q, this != m. q or r may be null.
7037 function bnpDivRemTo(m
, q
, r
) {
7040 if (pm
.t
<= 0) return
7043 if (q
!= null) q
.fromInt(0)
7044 if (r
!= null) self
.copyTo(r
)
7047 if (r
== null) r
= new BigInteger()
7048 var y
= new BigInteger(),
7051 var nsh
= self
.DB
- nbits(pm
[pm
.t
- 1]); // normalize modulus
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
,
7068 t
= (q
== null) ? new BigInteger() : q
7070 if (r
.compareTo(t
) >= 0) {
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
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
7083 while (r
[i
] < --qd
) r
.subTo(t
, r
)
7088 if (ts
!= ms
) BigInteger
.ZERO
.subTo(q
, q
)
7092 if (nsh
> 0) r
.rShiftTo(nsh
, r
); // Denormalize remainder
7093 if (ts
< 0) BigInteger
.ZERO
.subTo(r
, r
)
7096 // (public) this mod a
7098 var r
= new BigInteger()
7100 .divRemTo(a
, null, r
)
7101 if (this.s
< 0 && r
.compareTo(BigInteger
.ZERO
) > 0) a
.subTo(r
, r
)
7105 // Modular reduction using "classic" algorithm
7106 function Classic(m
) {
7110 function cConvert(x
) {
7111 if (x
.s
< 0 || x
.compareTo(this.m
) >= 0) return x
.mod(this.m
)
7115 function cRevert(x
) {
7119 function cReduce(x
) {
7120 x
.divRemTo(this.m
, null, x
)
7123 function cMulTo(x
, y
, r
) {
7128 function cSqrTo(x
, r
) {
7133 Classic
.prototype.convert
= cConvert
7134 Classic
.prototype.revert
= cRevert
7135 Classic
.prototype.reduce
= cReduce
7136 Classic
.prototype.mulTo
= cMulTo
7137 Classic
.prototype.sqrTo
= cSqrTo
7139 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
7143 // xy(2-xy) = (1+km)(1-km)
7144 // x[y(2-xy)] = 1-k^2m^2
7145 // x[y(2-xy)] == 1 (mod m^2)
7146 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
7147 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
7148 // JS multiply "overflows" differently from C/C++, so care is needed here.
7149 function bnpInvDigit() {
7150 if (this.t
< 1) return 0
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
7164 // Montgomery reduction
7165 function Montgomery(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
7175 function montConvert(x
) {
7176 var r
= new BigInteger()
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
)
7185 function montRevert(x
) {
7186 var r
= new BigInteger()
7192 // x = x/R mod m (HAC 14.32)
7193 function montReduce(x
) {
7194 while (x
.t
<= this.mt2
) // pad x so am has enough room later
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
7202 x
[j
] += this.m
.am(0, u0
, x
, i
, 0, this.m
.t
)
7204 while (x
[j
] >= x
.DV
) {
7210 x
.drShiftTo(this.m
.t
, x
)
7211 if (x
.compareTo(this.m
) >= 0) x
.subTo(this.m
, x
)
7214 // r = "x^2/R mod m"; x != r
7215 function montSqrTo(x
, r
) {
7220 // r = "xy/R mod m"; x,y != r
7221 function montMulTo(x
, y
, r
) {
7226 Montgomery
.prototype.convert
= montConvert
7227 Montgomery
.prototype.revert
= montRevert
7228 Montgomery
.prototype.reduce
= montReduce
7229 Montgomery
.prototype.mulTo
= montMulTo
7230 Montgomery
.prototype.sqrTo
= montSqrTo
7232 // (protected) true iff this is even
7233 function bnpIsEven() {
7234 return ((this.t
> 0) ? (this[0] & 1) : this.s
) == 0
7237 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
7238 function bnpExp(e
, z
) {
7239 if (e
> 0xffffffff || e
< 1) return BigInteger
.ONE
7240 var r
= new BigInteger(),
7241 r2
= new BigInteger(),
7242 g
= z
.convert(this),
7247 if ((e
& (1 << i
)) > 0) z
.mulTo(r2
, g
, r
)
7257 // (public) this^e % m, 0 <= e < 2^32
7258 function bnModPowInt(e
, m
) {
7260 if (e
< 256 || m
.isEven()) z
= new Classic(m
)
7261 else z
= new Montgomery(m
)
7262 return this.exp(e
, z
)
7266 proto
.copyTo
= bnpCopyTo
7267 proto
.fromInt
= bnpFromInt
7268 proto
.fromString
= bnpFromString
7269 proto
.clamp
= bnpClamp
7270 proto
.dlShiftTo
= bnpDLShiftTo
7271 proto
.drShiftTo
= bnpDRShiftTo
7272 proto
.lShiftTo
= bnpLShiftTo
7273 proto
.rShiftTo
= bnpRShiftTo
7274 proto
.subTo
= bnpSubTo
7275 proto
.multiplyTo
= bnpMultiplyTo
7276 proto
.squareTo
= bnpSquareTo
7277 proto
.divRemTo
= bnpDivRemTo
7278 proto
.invDigit
= bnpInvDigit
7279 proto
.isEven
= bnpIsEven
7283 proto
.toString
= bnToString
7284 proto
.negate
= bnNegate
7286 proto
.compareTo
= bnCompareTo
7287 proto
.bitLength
= bnBitLength
7288 proto
.byteLength
= bnByteLength
7290 proto
.modPowInt
= bnModPowInt
7293 function bnClone() {
7294 var r
= new BigInteger()
7299 // (public) return value as integer
7300 function bnIntValue() {
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]
7310 // (public) return value as byte
7311 function bnByteValue() {
7312 return (this.t
== 0) ? this.s : (this[0] << 24) >> 24
7315 // (public) return value as short (assumes DB>=16)
7316 function bnShortValue() {
7317 return (this.t
== 0) ? this.s : (this[0] << 16) >> 16
7320 // (protected) return x s.t. r^x < DV
7321 function bnpChunkSize(r
) {
7322 return Math
.floor(Math
.LN2
* this.DB
/ Math
.log(r
))
7325 // (public) 0 if this == 0, 1 if this > 0
7326 function bnSigNum() {
7327 if (this.s
< 0) return -1
7328 else if (this.t
<= 0 || (this.t
== 1 && this[0] <= 0)) return 0
7332 // (protected) convert to radix string
7333 function bnpToRadix(b
) {
7334 if (b
== null) b
= 10
7335 if (this.signum() == 0 || b
< 2 || b
> 36) return "0"
7336 var cs
= this.chunkSize(b
)
7337 var a
= Math
.pow(b
, cs
)
7339 y
= new BigInteger(),
7340 z
= new BigInteger(),
7342 this.divRemTo(d
, y
, z
)
7343 while (y
.signum() > 0) {
7344 r
= (a
+ z
.intValue())
7353 // (protected) convert from radix string
7354 function bnpFromRadix(s
, b
) {
7357 if (b
== null) b
= 10
7358 var cs
= self
.chunkSize(b
)
7359 var d
= Math
.pow(b
, cs
),
7363 for (var i
= 0; i
< s
.length
; ++i
) {
7366 if (s
.charAt(i
) == "-" && self
.signum() == 0) mi
= true
7372 self
.dAddOffset(w
, 0)
7378 self
.dMultiply(Math
.pow(b
, j
))
7379 self
.dAddOffset(w
, 0)
7381 if (mi
) BigInteger
.ZERO
.subTo(self
, self
)
7384 // (protected) alternate constructor
7385 function bnpFromNumber(a
, b
, c
) {
7387 if ("number" == typeof b
) {
7388 // new BigInteger(int,int,RNG)
7389 if (a
< 2) self
.fromInt(1)
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
)
7401 // new BigInteger(int,RNG)
7402 var x
= new Array(),
7404 x
.length
= (a
>> 3) + 1
7406 if (t
> 0) x
[0] &= ((1 << t
) - 1)
7408 self
.fromString(x
, 256)
7412 // (public) convert to bigendian byte array
7413 function bnToByteArray() {
7418 var p
= self
.DB
- (i
* self
.DB
) % 8,
7421 if (p
< self
.DB
&& (d
= self
[i
] >> p
) != (self
.s
& self
.DM
) >> p
)
7422 r
[k
++] = d
| (self
.s
<< (self
.DB
- p
))
7425 d
= (self
[i
] & ((1 << p
) - 1)) << (8 - p
)
7426 d
|= self
[--i
] >> (p
+= self
.DB
- 8)
7428 d
= (self
[i
] >> (p
-= 8)) & 0xff
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
7442 function bnEquals(a
) {
7443 return (this.compareTo(a
) == 0)
7447 return (this.compareTo(a
) < 0) ? this : a
7451 return (this.compareTo(a
) > 0) ? this : a
7454 // (protected) r = this op a (bitwise)
7455 function bnpBitwiseTo(a
, op
, r
) {
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
])
7461 for (i
= m
; i
< self
.t
; ++i
) r
[i
] = op(self
[i
], f
)
7464 f
= self
.s
& self
.DM
7465 for (i
= m
; i
< a
.t
; ++i
) r
[i
] = op(f
, a
[i
])
7468 r
.s
= op(self
.s
, a
.s
)
7472 // (public) this & a
7473 function op_and(x
, y
) {
7478 var r
= new BigInteger()
7479 this.bitwiseTo(a
, op_and
, r
)
7483 // (public) this | a
7484 function op_or(x
, y
) {
7489 var r
= new BigInteger()
7490 this.bitwiseTo(a
, op_or
, r
)
7494 // (public) this ^ a
7495 function op_xor(x
, y
) {
7500 var r
= new BigInteger()
7501 this.bitwiseTo(a
, op_xor
, r
)
7505 // (public) this & ~a
7506 function op_andnot(x
, y
) {
7510 function bnAndNot(a
) {
7511 var r
= new BigInteger()
7512 this.bitwiseTo(a
, op_andnot
, r
)
7518 var r
= new BigInteger()
7519 for (var i
= 0; i
< this.t
; ++i
) r
[i
] = this.DM
& ~this[i
]
7525 // (public) this << n
7526 function bnShiftLeft(n
) {
7527 var r
= new BigInteger()
7528 if (n
< 0) this.rShiftTo(-n
, r
)
7529 else this.lShiftTo(n
, r
)
7533 // (public) this >> n
7534 function bnShiftRight(n
) {
7535 var r
= new BigInteger()
7536 if (n
< 0) this.lShiftTo(-n
, r
)
7537 else this.rShiftTo(n
, r
)
7541 // return index of lowest 1-bit in x, x < 2^31
7543 if (x
== 0) return -1
7545 if ((x
& 0xffff) == 0) {
7549 if ((x
& 0xff) == 0) {
7553 if ((x
& 0xf) == 0) {
7561 if ((x
& 1) == 0)++r
7565 // (public) returns index of lowest 1-bit (or -1 if none)
7566 function bnGetLowestSetBit() {
7567 for (var i
= 0; i
< this.t
; ++i
)
7568 if (this[i
] != 0) return i
* this.DB
+ lbit(this[i
])
7569 if (this.s
< 0) return this.t
* this.DB
7573 // return number of 1 bits in x
7583 // (public) return number of set bits
7584 function bnBitCount() {
7586 x
= this.s
& this.DM
7587 for (var i
= 0; i
< this.t
; ++i
) r
+= cbit(this[i
] ^ x
)
7591 // (public) true iff nth bit is set
7592 function bnTestBit(n
) {
7593 var j
= Math
.floor(n
/ this.DB
)
7594 if (j
>= this.t
) return (this.s
!= 0)
7595 return ((this[j
] & (1 << (n
% this.DB
))) != 0)
7598 // (protected) this op (1<<n)
7599 function bnpChangeBit(n
, op
) {
7600 var r
= BigInteger
.ONE
.shiftLeft(n
)
7601 this.bitwiseTo(r
, op
, r
)
7605 // (public) this | (1<<n)
7606 function bnSetBit(n
) {
7607 return this.changeBit(n
, op_or
)
7610 // (public) this & ~(1<<n)
7611 function bnClearBit(n
) {
7612 return this.changeBit(n
, op_andnot
)
7615 // (public) this ^ (1<<n)
7616 function bnFlipBit(n
) {
7617 return this.changeBit(n
, op_xor
)
7620 // (protected) r = this + a
7621 function bnpAddTo(a
, r
) {
7626 m
= Math
.min(a
.t
, self
.t
)
7629 r
[i
++] = c
& self
.DM
7634 while (i
< self
.t
) {
7636 r
[i
++] = c
& self
.DM
7644 r
[i
++] = c
& self
.DM
7649 r
.s
= (c
< 0) ? -1 : 0
7650 if (c
> 0) r
[i
++] = c
7651 else if (c
< -1) r
[i
++] = self
.DV
+ c
7656 // (public) this + a
7658 var r
= new BigInteger()
7663 // (public) this - a
7664 function bnSubtract(a
) {
7665 var r
= new BigInteger()
7670 // (public) this * a
7671 function bnMultiply(a
) {
7672 var r
= new BigInteger()
7673 this.multiplyTo(a
, r
)
7678 function bnSquare() {
7679 var r
= new BigInteger()
7684 // (public) this / a
7685 function bnDivide(a
) {
7686 var r
= new BigInteger()
7687 this.divRemTo(a
, r
, null)
7691 // (public) this % a
7692 function bnRemainder(a
) {
7693 var r
= new BigInteger()
7694 this.divRemTo(a
, null, r
)
7698 // (public) [this/a,this%a]
7699 function bnDivideAndRemainder(a
) {
7700 var q
= new BigInteger(),
7701 r
= new BigInteger()
7702 this.divRemTo(a
, q
, r
)
7703 return new Array(q
, r
)
7706 // (protected) this *= n, this >= 0, 1 < n < DV
7707 function bnpDMultiply(n
) {
7708 this[this.t
] = this.am(0, n
- 1, this, 0, 0, this.t
)
7713 // (protected) this += n << w words, this >= 0
7714 function bnpDAddOffset(n
, w
) {
7716 while (this.t
<= w
) this[this.t
++] = 0
7718 while (this[w
] >= this.DV
) {
7720 if (++w
>= this.t
) this[this.t
++] = 0
7726 function NullExp() {}
7732 function nMulTo(x
, y
, r
) {
7736 function nSqrTo(x
, r
) {
7740 NullExp
.prototype.convert
= nNop
7741 NullExp
.prototype.revert
= nNop
7742 NullExp
.prototype.mulTo
= nMulTo
7743 NullExp
.prototype.sqrTo
= nSqrTo
7747 return this.exp(e
, new NullExp())
7750 // (protected) r = lower n words of "this * a", a.t <= n
7751 // "this" should be the larger one if appropriate.
7752 function bnpMultiplyLowerTo(a
, n
, r
) {
7753 var i
= Math
.min(this.t
+ a
.t
, n
)
7754 r
.s
= 0; // assumes a,this >= 0
7756 while (i
> 0) r
[--i
] = 0
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
)
7763 // (protected) r = "this * a" without lower n words, n > 0
7764 // "this" should be the larger one if appropriate.
7765 function bnpMultiplyUpperTo(a
, n
, r
) {
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
)
7776 // Barrett modular reduction
7777 function Barrett(m
) {
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
)
7786 function barrettConvert(x
) {
7787 if (x
.s
< 0 || x
.t
> 2 * this.m
.t
) return x
.mod(this.m
)
7788 else if (x
.compareTo(this.m
) < 0) return x
7790 var r
= new BigInteger()
7797 function barrettRevert(x
) {
7801 // x = x mod m (HAC 14.42)
7802 function barrettReduce(x
) {
7804 x
.drShiftTo(self
.m
.t
- 1, self
.r2
)
7805 if (x
.t
> self
.m
.t
+ 1) {
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)
7813 while (x
.compareTo(self
.m
) >= 0) x
.subTo(self
.m
, x
)
7816 // r = x^2 mod m; x != r
7817 function barrettSqrTo(x
, r
) {
7822 // r = x*y mod m; x,y != r
7823 function barrettMulTo(x
, y
, r
) {
7828 Barrett
.prototype.convert
= barrettConvert
7829 Barrett
.prototype.revert
= barrettRevert
7830 Barrett
.prototype.reduce
= barrettReduce
7831 Barrett
.prototype.mulTo
= barrettMulTo
7832 Barrett
.prototype.sqrTo
= barrettSqrTo
7834 // (public) this^e % m (HAC 14.85)
7835 function bnModPow(e
, m
) {
7836 var i
= e
.bitLength(),
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
7847 else if (m
.isEven())
7850 z
= new Montgomery(m
)
7853 var g
= new Array(),
7857 g
[1] = z
.convert(this)
7859 var g2
= new BigInteger()
7862 g
[n
] = new BigInteger()
7863 z
.mulTo(g2
, g
[n
- 2], g
[n
])
7870 r2
= new BigInteger(),
7874 if (i
>= k1
) w
= (e
[j
] >> (i
- k1
)) & km
7876 w
= (e
[j
] & ((1 << (i
+ 1)) - 1)) << (k1
- i
)
7877 if (j
> 0) w
|= e
[j
- 1] >> (this.DB
+ i
- k1
)
7881 while ((w
& 1) == 0) {
7889 if (is1
) { // ret == 1, don't bother squaring or multiplying it
7898 if (n
> 0) z
.sqrTo(r
, r2
)
7904 z
.mulTo(r2
, g
[w
], r
)
7907 while (j
>= 0 && (e
[j
] & (1 << i
)) == 0) {
7921 // (public) gcd(this,a) (HAC 14.54)
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) {
7930 var i
= x
.getLowestSetBit(),
7931 g
= y
.getLowestSetBit()
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) {
7949 if (g
> 0) y
.lShiftTo(g
, y
)
7953 // (protected) this % n, n < 2^26
7954 function bnpModInt(n
) {
7955 if (n
<= 0) return 0
7956 var d
= this.DV
% n
,
7957 r
= (this.s
< 0) ? n
- 1 : 0
7959 if (d
== 0) r
= this[0] % n
7961 for (var i
= this.t
- 1; i
>= 0; --i
) r
= (d
* r
+ this[i
]) % n
7965 // (public) 1/this % m (HAC 14.61)
7966 function bnModInverse(m
) {
7968 if (this.signum() === 0) throw new Error('division by zero')
7969 if ((this.isEven() && ac
) || m
.signum() == 0) return BigInteger
.ZERO
7976 while (u
.signum() != 0) {
7977 while (u
.isEven()) {
7980 if (!a
.isEven() || !b
.isEven()) {
7985 } else if (!b
.isEven()) b
.subTo(m
, b
)
7988 while (v
.isEven()) {
7991 if (!c
.isEven() || !d
.isEven()) {
7996 } else if (!d
.isEven()) d
.subTo(m
, d
)
7999 if (u
.compareTo(v
) >= 0) {
8001 if (ac
) a
.subTo(c
, a
)
8005 if (ac
) c
.subTo(a
, c
)
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
)
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
8029 var lplim
= (1 << 26) / lowprimes
[lowprimes
.length
- 1]
8031 // (public) test primality with certainty >= 1-.5^t
8032 function bnIsProbablePrime(t
) {
8033 var i
, x
= this.abs()
8034 if (x
.t
== 1 && x
[0] <= lowprimes
[lowprimes
.length
- 1]) {
8035 for (i
= 0; i
< lowprimes
.length
; ++i
)
8036 if (x
[0] == lowprimes
[i
]) return true
8039 if (x
.isEven()) return false
8041 while (i
< lowprimes
.length
) {
8042 var m
= lowprimes
[i
],
8044 while (j
< lowprimes
.length
&& m
< lplim
) m
*= lowprimes
[j
++]
8046 while (i
< j
) if (m
% lowprimes
[i
++] == 0) return false
8048 return x
.millerRabin(t
)
8051 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
8052 function bnpMillerRabin(t
) {
8053 var n1
= this.subtract(BigInteger
.ONE
)
8054 var k
= n1
.getLowestSetBit()
8055 if (k
<= 0) return false
8056 var r
= n1
.shiftRight(k
)
8058 if (t
> lowprimes
.length
) t
= lowprimes
.length
8059 var a
= new BigInteger(null)
8061 for (var i
= 0; i
< t
; ++i
) {
8063 j
= lowprimes
[Math
.floor(Math
.random() * lowprimes
.length
)]
8064 if (bases
.indexOf(j
) == -1) break
8068 var y
= a
.modPow(r
, this)
8069 if (y
.compareTo(BigInteger
.ONE
) != 0 && y
.compareTo(n1
) != 0) {
8071 while (j
++ < k
&& y
.compareTo(n1
) != 0) {
8072 y
= y
.modPowInt(2, this)
8073 if (y
.compareTo(BigInteger
.ONE
) == 0) return false
8075 if (y
.compareTo(n1
) != 0) return false
8082 proto
.chunkSize
= bnpChunkSize
8083 proto
.toRadix
= bnpToRadix
8084 proto
.fromRadix
= bnpFromRadix
8085 proto
.fromNumber
= bnpFromNumber
8086 proto
.bitwiseTo
= bnpBitwiseTo
8087 proto
.changeBit
= bnpChangeBit
8088 proto
.addTo
= bnpAddTo
8089 proto
.dMultiply
= bnpDMultiply
8090 proto
.dAddOffset
= bnpDAddOffset
8091 proto
.multiplyLowerTo
= bnpMultiplyLowerTo
8092 proto
.multiplyUpperTo
= bnpMultiplyUpperTo
8093 proto
.modInt
= bnpModInt
8094 proto
.millerRabin
= bnpMillerRabin
8097 proto
.clone
= bnClone
8098 proto
.intValue
= bnIntValue
8099 proto
.byteValue
= bnByteValue
8100 proto
.shortValue
= bnShortValue
8101 proto
.signum
= bnSigNum
8102 proto
.toByteArray
= bnToByteArray
8103 proto
.equals
= bnEquals
8109 proto
.andNot
= bnAndNot
8111 proto
.shiftLeft
= bnShiftLeft
8112 proto
.shiftRight
= bnShiftRight
8113 proto
.getLowestSetBit
= bnGetLowestSetBit
8114 proto
.bitCount
= bnBitCount
8115 proto
.testBit
= bnTestBit
8116 proto
.setBit
= bnSetBit
8117 proto
.clearBit
= bnClearBit
8118 proto
.flipBit
= bnFlipBit
8120 proto
.subtract
= bnSubtract
8121 proto
.multiply
= bnMultiply
8122 proto
.divide
= bnDivide
8123 proto
.remainder
= bnRemainder
8124 proto
.divideAndRemainder
= bnDivideAndRemainder
8125 proto
.modPow
= bnModPow
8126 proto
.modInverse
= bnModInverse
8129 proto
.isProbablePrime
= bnIsProbablePrime
8131 // JSBN-specific extension
8132 proto
.square
= bnSquare
8135 BigInteger
.ZERO
= nbv(0)
8136 BigInteger
.ONE
= nbv(1)
8137 BigInteger
.valueOf
= nbv
8139 module
.exports
= BigInteger
8141 },{"../package.json":40}],38:[function(require
,module
,exports
){
8143 // FIXME: Kind of a weird way to throw exceptions, consider removing
8144 var assert
= require('assert')
8145 var BigInteger
= require('./bigi')
8148 * Turns a byte array into a big integer.
8150 * This function will interpret a byte array as a big integer in big
8153 BigInteger
.fromByteArrayUnsigned = function(byteArray
) {
8154 // BigInteger expects a DER integer conformant byte array
8155 if (byteArray
[0] & 0x80) {
8156 return new BigInteger([0].concat(byteArray
))
8159 return new BigInteger(byteArray
)
8163 * Returns a byte array representation of the big integer.
8165 * This returns the absolute of the contained value in big endian
8166 * form. A value of zero results in an empty array.
8168 BigInteger
.prototype.toByteArrayUnsigned = function() {
8169 var byteArray
= this.toByteArray()
8170 return byteArray
[0] === 0 ? byteArray
.slice(1) : byteArray
8173 BigInteger
.fromDERInteger = function(byteArray
) {
8174 return new BigInteger(byteArray
)
8178 * Converts BigInteger to a DER integer representation.
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.
8198 * -62300 => 0xff0ca4
8200 BigInteger
.prototype.toDERInteger
= BigInteger
.prototype.toByteArray
8202 BigInteger
.fromBuffer = function(buffer
) {
8203 // BigInteger expects a DER integer conformant byte array
8204 if (buffer
[0] & 0x80) {
8205 var byteArray
= Array
.prototype.slice
.call(buffer
)
8207 return new BigInteger([0].concat(byteArray
))
8210 return new BigInteger(buffer
)
8213 BigInteger
.fromHex = function(hex
) {
8214 if (hex
=== '') return BigInteger
.ZERO
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)
8221 BigInteger
.prototype.toBuffer = function(size
) {
8222 var byteArray
= this.toByteArrayUnsigned()
8225 var padding
= size
- byteArray
.length
8226 while (zeros
.length
< padding
) zeros
.push(0)
8228 return new Buffer(zeros
.concat(byteArray
))
8231 BigInteger
.prototype.toHex = function(size
) {
8232 return this.toBuffer(size
).toString('hex')
8235 }).call(this,require("buffer").Buffer
)
8236 },{"./bigi":37,"assert":1,"buffer":5}],39:[function(require
,module
,exports
){
8237 var BigInteger
= require('./bigi')
8240 require('./convert')
8242 module
.exports
= BigInteger
8243 },{"./bigi":37,"./convert":38}],40:[function(require
,module
,exports
){
8248 "/home/ian/git/bitcoin/bitcoinjs-lib-browser/node_modules/bitcoinjs-lib"
8251 "_from": "bigi@>=1.4.0 <2.0.0",
8252 "_id": "bigi@1.4.2",
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"
8262 "email": "jprichardson@gmail.com",
8263 "name": "jprichardson"
8265 "_npmVersion": "3.8.6",
8266 "_phantomChildren": {},
8269 "raw": "bigi@^1.4.0",
8270 "rawSpec": "^1.4.0",
8272 "spec": ">=1.4.0 <2.0.0",
8279 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
8280 "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
8281 "_shrinkwrap": null,
8282 "_spec": "bigi@^1.4.0",
8283 "_where": "/home/ian/git/bitcoin/bitcoinjs-lib-browser/node_modules/bitcoinjs-lib",
8285 "url": "https://github.com/cryptocoinjs/bigi/issues"
8288 "description": "Big integers.",
8289 "devDependencies": {
8290 "coveralls": "^2.11.2",
8291 "istanbul": "^0.3.5",
8298 "shasum": "9c665a95f88b8b08fc05cfd731f561859d725825",
8299 "tarball": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz"
8301 "gitHead": "c25308081c896ff84702303722bf5ecd8b3f78e3",
8302 "homepage": "https://github.com/cryptocoinjs/bigi#readme",
8320 "main": "./lib/index.js",
8323 "email": "boydb@midnightdesign.ws",
8324 "name": "midnightlightning"
8327 "email": "sidazhang89@gmail.com",
8331 "email": "npm@shesek.info",
8335 "email": "jprichardson@gmail.com",
8336 "name": "jprichardson"
8340 "optionalDependencies": {},
8341 "readme": "ERROR: No README data found!",
8344 "url": "git+https://github.com/cryptocoinjs/bigi.git"
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",
8359 "safari/6.0..latest",
8360 "iphone/6.0..latest",
8361 "android-browser/4.2..latest"
8363 "files": "test/*.js",
8369 },{}],41:[function(require
,module
,exports
){
8370 // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
8371 // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
8372 // NOTE: SIGHASH byte ignored AND restricted, truncate before use
8374 var Buffer
= require('safe-buffer').Buffer
8376 function check (buffer
) {
8377 if (buffer
.length
< 8) return false
8378 if (buffer
.length
> 72) return false
8379 if (buffer
[0] !== 0x30) return false
8380 if (buffer
[1] !== buffer
.length
- 2) return false
8381 if (buffer
[2] !== 0x02) return false
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
8388 var lenS
= buffer
[5 + lenR
]
8389 if (lenS
=== 0) return false
8390 if ((6 + lenR
+ lenS
) !== buffer
.length
) return false
8392 if (buffer
[4] & 0x80) return false
8393 if (lenR
> 1 && (buffer
[4] === 0x00) && !(buffer
[5] & 0x80)) return false
8395 if (buffer
[lenR
+ 6] & 0x80) return false
8396 if (lenS
> 1 && (buffer
[lenR
+ 6] === 0x00) && !(buffer
[lenR
+ 7] & 0x80)) return false
8400 function decode (buffer
) {
8401 if (buffer
.length
< 8) throw new Error('DER sequence length is too short')
8402 if (buffer
.length
> 72) throw new Error('DER sequence length is too long')
8403 if (buffer
[0] !== 0x30) throw new Error('Expected DER sequence')
8404 if (buffer
[1] !== buffer
.length
- 2) throw new Error('DER sequence length is invalid')
8405 if (buffer
[2] !== 0x02) throw new Error('Expected DER integer')
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)')
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')
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')
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')
8422 // non-BIP66 - extract R, S values
8424 r: buffer
.slice(4, 4 + lenR
),
8425 s: buffer
.slice(6 + lenR
)
8430 * Expects r and s to be positive DER integers.
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.
8449 * -62300 => 0xff0ca4
8451 function encode (r
, s
) {
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')
8463 var signature
= Buffer
.allocUnsafe(6 + lenR
+ lenS
)
8465 // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
8467 signature
[1] = signature
.length
- 2
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
)
8484 },{"safe-buffer":101}],42:[function(require
,module
,exports
){
8522 "OP_TOALTSTACK": 107,
8523 "OP_FROMALTSTACK": 108,
8553 "OP_EQUALVERIFY": 136,
8554 "OP_RESERVED1": 137,
8555 "OP_RESERVED2": 138,
8564 "OP_0NOTEQUAL": 146,
8576 "OP_NUMEQUALVERIFY": 157,
8577 "OP_NUMNOTEQUAL": 158,
8579 "OP_GREATERTHAN": 160,
8580 "OP_LESSTHANOREQUAL": 161,
8581 "OP_GREATERTHANOREQUAL": 162,
8587 "OP_RIPEMD160": 166,
8592 "OP_CODESEPARATOR": 171,
8594 "OP_CHECKSIGVERIFY": 173,
8595 "OP_CHECKMULTISIG": 174,
8596 "OP_CHECKMULTISIGVERIFY": 175,
8601 "OP_CHECKLOCKTIMEVERIFY": 177,
8604 "OP_CHECKSEQUENCEVERIFY": 178,
8614 "OP_PUBKEYHASH": 253,
8616 "OP_INVALIDOPCODE": 255
8619 },{}],43:[function(require
,module
,exports
){
8620 var OPS
= require('./index.json')
8623 for (var op
in OPS
) {
8628 module
.exports
= map
8630 },{"./index.json":42}],44:[function(require
,module
,exports
){
8631 var Buffer
= require('safe-buffer').Buffer
8632 var bech32
= require('bech32')
8633 var bs58check
= require('bs58check')
8634 var bscript
= require('./script')
8635 var btemplates
= require('./templates')
8636 var networks
= require('./networks')
8637 var typeforce
= require('typeforce')
8638 var types
= require('./types')
8640 function fromBase58Check (address
) {
8641 var payload
= bs58check
.decode(address
)
8643 // TODO: 4.0.0, move to "toOutputScript"
8644 if (payload
.length
< 21) throw new TypeError(address
+ ' is too short')
8645 if (payload
.length
> 21) throw new TypeError(address
+ ' is too long')
8647 var version
= payload
.readUInt8(0)
8648 var hash
= payload
.slice(1)
8650 return { version: version
, hash: hash
}
8653 function fromBech32 (address
) {
8654 var result
= bech32
.decode(address
)
8655 var data
= bech32
.fromWords(result
.words
.slice(1))
8658 version: result
.words
[0],
8659 prefix: result
.prefix
,
8660 data: Buffer
.from(data
)
8664 function toBase58Check (hash
, version
) {
8665 typeforce(types
.tuple(types
.Hash160bit
, types
.UInt8
), arguments
)
8667 var payload
= Buffer
.allocUnsafe(21)
8668 payload
.writeUInt8(version
, 0)
8669 hash
.copy(payload
, 1)
8671 return bs58check
.encode(payload
)
8674 function toBech32 (data
, version
, prefix
) {
8675 var words
= bech32
.toWords(data
)
8676 words
.unshift(version
)
8678 return bech32
.encode(prefix
, words
)
8681 function fromOutputScript (outputScript
, network
) {
8682 network
= network
|| networks
.bitcoin
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
)
8689 throw new Error(bscript
.toASM(outputScript
) + ' has no matching Address')
8692 function toOutputScript (address
, network
) {
8693 network
= network
|| networks
.bitcoin
8697 decode
= fromBase58Check(address
)
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
)
8705 decode
= fromBech32(address
)
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
)
8717 throw new Error(address
+ ' has no matching Script')
8721 fromBase58Check: fromBase58Check
,
8722 fromBech32: fromBech32
,
8723 fromOutputScript: fromOutputScript
,
8724 toBase58Check: toBase58Check
,
8726 toOutputScript: toOutputScript
8729 },{"./networks":53,"./script":54,"./templates":56,"./types":80,"bech32":36,"bs58check":83,"safe-buffer":101,"typeforce":112}],45:[function(require
,module
,exports
){
8730 var Buffer
= require('safe-buffer').Buffer
8731 var bcrypto
= require('./crypto')
8732 var fastMerkleRoot
= require('merkle-lib/fastRoot')
8733 var typeforce
= require('typeforce')
8734 var types
= require('./types')
8735 var varuint
= require('varuint-bitcoin')
8737 var Transaction
= require('./transaction')
8741 this.prevHash
= null
8742 this.merkleRoot
= null
8748 Block
.fromBuffer = function (buffer
) {
8749 if (buffer
.length
< 80) throw new Error('Buffer too small (< 80 bytes)')
8752 function readSlice (n
) {
8754 return buffer
.slice(offset
- n
, offset
)
8757 function readUInt32 () {
8758 var i
= buffer
.readUInt32LE(offset
)
8763 function readInt32 () {
8764 var i
= buffer
.readInt32LE(offset
)
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()
8777 if (buffer
.length
=== 80) return block
8779 function readVarInt () {
8780 var vi
= varuint
.decode(buffer
, offset
)
8781 offset
+= varuint
.decode
.bytes
8785 function readTransaction () {
8786 var tx
= Transaction
.fromBuffer(buffer
.slice(offset
), true)
8787 offset
+= tx
.byteLength()
8791 var nTransactions
= readVarInt()
8792 block
.transactions
= []
8794 for (var i
= 0; i
< nTransactions
; ++i
) {
8795 var tx
= readTransaction()
8796 block
.transactions
.push(tx
)
8802 Block
.prototype.byteLength = function (headersOnly
) {
8803 if (headersOnly
|| !this.transactions
) return 80
8805 return 80 + varuint
.encodingLength(this.transactions
.length
) + this.transactions
.reduce(function (a
, x
) {
8806 return a
+ x
.byteLength()
8810 Block
.fromHex = function (hex
) {
8811 return Block
.fromBuffer(Buffer
.from(hex
, 'hex'))
8814 Block
.prototype.getHash = function () {
8815 return bcrypto
.hash256(this.toBuffer(true))
8818 Block
.prototype.getId = function () {
8819 return this.getHash().reverse().toString('hex')
8822 Block
.prototype.getUTCDate = function () {
8823 var date
= new Date(0) // epoch
8824 date
.setUTCSeconds(this.timestamp
)
8829 // TODO: buffer, offset compatibility
8830 Block
.prototype.toBuffer = function (headersOnly
) {
8831 var buffer
= Buffer
.allocUnsafe(this.byteLength(headersOnly
))
8834 function writeSlice (slice
) {
8835 slice
.copy(buffer
, offset
)
8836 offset
+= slice
.length
8839 function writeInt32 (i
) {
8840 buffer
.writeInt32LE(i
, offset
)
8843 function writeUInt32 (i
) {
8844 buffer
.writeUInt32LE(i
, offset
)
8848 writeInt32(this.version
)
8849 writeSlice(this.prevHash
)
8850 writeSlice(this.merkleRoot
)
8851 writeUInt32(this.timestamp
)
8852 writeUInt32(this.bits
)
8853 writeUInt32(this.nonce
)
8855 if (headersOnly
|| !this.transactions
) return buffer
8857 varuint
.encode(this.transactions
.length
, buffer
, offset
)
8858 offset
+= varuint
.encode
.bytes
8860 this.transactions
.forEach(function (tx
) {
8861 var txSize
= tx
.byteLength() // TODO: extract from toBuffer?
8862 tx
.toBuffer(buffer
, offset
)
8869 Block
.prototype.toHex = function (headersOnly
) {
8870 return this.toBuffer(headersOnly
).toString('hex')
8873 Block
.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
)
8881 Block
.calculateMerkleRoot = function (transactions
) {
8882 typeforce([{ getHash: types
.Function
}], transactions
)
8883 if (transactions
.length
=== 0) throw TypeError('Cannot compute merkle root for zero transactions')
8885 var hashes
= transactions
.map(function (transaction
) {
8886 return transaction
.getHash()
8889 return fastMerkleRoot(hashes
, bcrypto
.hash256
)
8892 Block
.prototype.checkMerkleRoot = function () {
8893 if (!this.transactions
) return false
8895 var actualMerkleRoot
= Block
.calculateMerkleRoot(this.transactions
)
8896 return this.merkleRoot
.compare(actualMerkleRoot
) === 0
8899 Block
.prototype.checkProofOfWork = function () {
8900 var hash
= this.getHash().reverse()
8901 var target
= Block
.calculateTarget(this.bits
)
8903 return hash
.compare(target
) <= 0
8906 module
.exports
= Block
8908 },{"./crypto":47,"./transaction":78,"./types":80,"merkle-lib/fastRoot":97,"safe-buffer":101,"typeforce":112,"varuint-bitcoin":114}],46:[function(require
,module
,exports
){
8909 var pushdata
= require('pushdata-bitcoin')
8910 var varuint
= require('varuint-bitcoin')
8912 // https://github.com/feross/buffer/blob/master/index.js#L1127
8913 function 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')
8920 function readUInt64LE (buffer
, offset
) {
8921 var a
= buffer
.readUInt32LE(offset
)
8922 var b
= buffer
.readUInt32LE(offset
+ 4)
8925 verifuint(b
+ a
, 0x001fffffffffffff)
8930 function writeUInt64LE (buffer
, value
, offset
) {
8931 verifuint(value
, 0x001fffffffffffff)
8933 buffer
.writeInt32LE(value
& -1, offset
)
8934 buffer
.writeUInt32LE(Math
.floor(value
/ 0x100000000), offset
+ 4)
8938 // TODO: remove in 4.0.0?
8939 function readVarInt (buffer
, offset
) {
8940 var result
= varuint
.decode(buffer
, offset
)
8944 size: varuint
.decode
.bytes
8948 // TODO: remove in 4.0.0?
8949 function writeVarInt (buffer
, number
, offset
) {
8950 varuint
.encode(number
, buffer
, offset
)
8951 return varuint
.encode
.bytes
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
8966 },{"pushdata-bitcoin":98,"varuint-bitcoin":114}],47:[function(require
,module
,exports
){
8967 var createHash
= require('create-hash')
8969 function ripemd160 (buffer
) {
8970 return createHash('rmd160').update(buffer
).digest()
8973 function sha1 (buffer
) {
8974 return createHash('sha1').update(buffer
).digest()
8977 function sha256 (buffer
) {
8978 return createHash('sha256').update(buffer
).digest()
8981 function hash160 (buffer
) {
8982 return ripemd160(sha256(buffer
))
8985 function hash256 (buffer
) {
8986 return sha256(sha256(buffer
))
8992 ripemd160: ripemd160
,
8997 },{"create-hash":85}],48:[function(require
,module
,exports
){
8998 var Buffer
= require('safe-buffer').Buffer
8999 var createHmac
= require('create-hmac')
9000 var typeforce
= require('typeforce')
9001 var types
= require('./types')
9003 var BigInteger
= require('bigi')
9004 var ECSignature
= require('./ecsignature')
9006 var ZERO
= Buffer
.alloc(1, 0)
9007 var ONE
= Buffer
.alloc(1, 1)
9009 var ecurve
= require('ecurve')
9010 var secp256k1
= ecurve
.getCurveByName('secp256k1')
9012 // https://tools.ietf.org/html/rfc6979#section-3.2
9013 function deterministicGenerateK (hash
, x
, checkSig
) {
9014 typeforce(types
.tuple(
9020 // Step A, ignored as hash already provided
9023 var k
= Buffer
.alloc(32, 0)
9024 var v
= Buffer
.alloc(32, 1)
9027 k
= createHmac('sha256', k
)
9035 v
= createHmac('sha256', k
).update(v
).digest()
9038 k
= createHmac('sha256', k
)
9046 v
= createHmac('sha256', k
).update(v
).digest()
9048 // Step H1/H2a, ignored as tlen === qlen (256 bit)
9050 v
= createHmac('sha256', k
).update(v
).digest()
9052 var T
= BigInteger
.fromBuffer(v
)
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
)
9061 v
= createHmac('sha256', k
).update(v
).digest()
9063 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
9065 v
= createHmac('sha256', k
).update(v
).digest()
9066 T
= BigInteger
.fromBuffer(v
)
9072 var N_OVER_TWO
= secp256k1
.n
.shiftRight(1)
9074 function sign (hash
, d
) {
9075 typeforce(types
.tuple(types
.Hash256bit
, types
.BigInt
), arguments
)
9077 var x
= d
.toBuffer(32)
9078 var e
= BigInteger
.fromBuffer(hash
)
9083 deterministicGenerateK(hash
, x
, function (k
) {
9084 var Q
= G
.multiply(k
)
9086 if (secp256k1
.isInfinity(Q
)) return false
9088 r
= Q
.affineX
.mod(n
)
9089 if (r
.signum() === 0) return false
9091 s
= k
.modInverse(n
).multiply(e
.add(d
.multiply(r
))).mod(n
)
9092 if (s
.signum() === 0) return false
9097 // enforce low S values, see bip62: 'low s values in signatures'
9098 if (s
.compareTo(N_OVER_TWO
) > 0) {
9102 return new ECSignature(r
, s
)
9105 function verify (hash
, signature
, Q
) {
9106 typeforce(types
.tuple(
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
9122 // 1.4.2 H = Hash(M), already done by the user
9124 var e
= BigInteger
.fromBuffer(hash
)
9127 var sInv
= s
.modInverse(n
)
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
)
9134 // 1.4.5 Compute R = (xR, yR)
9136 var R
= G
.multiplyTwo(u1
, Q
, u2
)
9138 // 1.4.5 (cont.) Enforce R is not at infinity
9139 if (secp256k1
.isInfinity(R
)) return false
9141 // 1.4.6 Convert the field element R.x to an integer
9144 // 1.4.7 Set v = xR mod n
9147 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
9152 deterministicGenerateK: deterministicGenerateK
,
9160 },{"./ecsignature":50,"./types":80,"bigi":39,"create-hmac":88,"ecurve":92,"safe-buffer":101,"typeforce":112}],49:[function(require
,module
,exports
){
9161 var baddress
= require('./address')
9162 var bcrypto
= require('./crypto')
9163 var ecdsa
= require('./ecdsa')
9164 var randomBytes
= require('randombytes')
9165 var typeforce
= require('typeforce')
9166 var types
= require('./types')
9167 var wif
= require('wif')
9169 var NETWORKS
= require('./networks')
9170 var BigInteger
= require('bigi')
9172 var ecurve
= require('ecurve')
9173 var secp256k1
= ecdsa
.__curve
9175 function ECPair (d
, Q
, options
) {
9178 compressed: types
.maybe(types
.Boolean
),
9179 network: types
.maybe(types
.Network
)
9183 options
= options
|| {}
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')
9192 typeforce(types
.ECPoint
, Q
)
9197 this.compressed
= options
.compressed
=== undefined ? true : options
.compressed
9198 this.network
= options
.network
|| NETWORKS
.bitcoin
9201 Object
.defineProperty(ECPair
.prototype, 'Q', {
9203 if (!this.__Q
&& this.d
) {
9204 this.__Q
= secp256k1
.G
.multiply(this.d
)
9211 ECPair
.fromPublicKeyBuffer = function (buffer
, network
) {
9212 var Q
= ecurve
.Point
.decodeFrom(secp256k1
, buffer
)
9214 return new ECPair(null, Q
, {
9215 compressed: Q
.compressed
,
9220 ECPair
.fromWIF = function (string
, network
) {
9221 var decoded
= wif
.decode(string
)
9222 var version
= decoded
.version
9224 // list of networks?
9225 if (types
.Array(network
)) {
9226 network
= network
.filter(function (x
) {
9227 return version
=== x
.wif
9230 if (!network
) throw new Error('Unknown network version')
9232 // otherwise, assume a network object (or default to bitcoin)
9234 network
= network
|| NETWORKS
.bitcoin
9236 if (version
!== network
.wif
) throw new Error('Invalid network version')
9239 var d
= BigInteger
.fromBuffer(decoded
.privateKey
)
9241 return new ECPair(d
, null, {
9242 compressed: decoded
.compressed
,
9247 ECPair
.makeRandom = function (options
) {
9248 options
= options
|| {}
9250 var rng
= options
.rng
|| randomBytes
9254 var buffer
= rng(32)
9255 typeforce(types
.Buffer256bit
, buffer
)
9257 d
= BigInteger
.fromBuffer(buffer
)
9258 } while (d
.signum() <= 0 || d
.compareTo(secp256k1
.n
) >= 0)
9260 return new ECPair(d
, null, options
)
9263 ECPair
.prototype.getAddress = function () {
9264 return baddress
.toBase58Check(bcrypto
.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash
)
9267 ECPair
.prototype.getNetwork = function () {
9271 ECPair
.prototype.getPublicKeyBuffer = function () {
9272 return this.Q
.getEncoded(this.compressed
)
9275 ECPair
.prototype.sign = function (hash
) {
9276 if (!this.d
) throw new Error('Missing private key')
9278 return ecdsa
.sign(hash
, this.d
)
9281 ECPair
.prototype.toWIF = function () {
9282 if (!this.d
) throw new Error('Missing private key')
9284 return wif
.encode(this.network
.wif
, this.d
.toBuffer(32), this.compressed
)
9287 ECPair
.prototype.verify = function (hash
, signature
) {
9288 return ecdsa
.verify(hash
, signature
, this.Q
)
9291 module
.exports
= ECPair
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
){
9295 var bip66
= require('bip66')
9296 var typeforce
= require('typeforce')
9297 var types
= require('./types')
9299 var BigInteger
= require('bigi')
9301 function ECSignature (r
, s
) {
9302 typeforce(types
.tuple(types
.BigInt
, types
.BigInt
), arguments
)
9308 ECSignature
.parseCompact = function (buffer
) {
9309 typeforce(types
.BufferN(65), buffer
)
9311 var flagByte
= buffer
.readUInt8(0) - 27
9312 if (flagByte
!== (flagByte
& 7)) throw new Error('Invalid signature parameter')
9314 var compressed
= !!(flagByte
& 4)
9315 var recoveryParam
= flagByte
& 3
9316 var signature
= ECSignature
.fromRSBuffer(buffer
.slice(1))
9319 compressed: compressed
,
9321 signature: signature
9325 ECSignature
.fromRSBuffer = function (buffer
) {
9326 typeforce(types
.BufferN(64), buffer
)
9328 var r
= BigInteger
.fromBuffer(buffer
.slice(0, 32))
9329 var s
= BigInteger
.fromBuffer(buffer
.slice(32, 64))
9330 return new ECSignature(r
, s
)
9333 ECSignature
.fromDER = function (buffer
) {
9334 var decode
= bip66
.decode(buffer
)
9335 var r
= BigInteger
.fromDERInteger(decode
.r
)
9336 var s
= BigInteger
.fromDERInteger(decode
.s
)
9338 return new ECSignature(r
, s
)
9341 // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
9342 ECSignature
.parseScriptSignature = function (buffer
) {
9343 var hashType
= buffer
.readUInt8(buffer
.length
- 1)
9344 var hashTypeMod
= hashType
& ~0x80
9346 if (hashTypeMod
<= 0x00 || hashTypeMod
>= 0x04) throw new Error('Invalid hashType ' + hashType
)
9349 signature: ECSignature
.fromDER(buffer
.slice(0, -1)),
9354 ECSignature
.prototype.toCompact = function (i
, compressed
) {
9361 var buffer
= Buffer
.alloc(65)
9362 buffer
.writeUInt8(i
, 0)
9363 this.toRSBuffer(buffer
, 1)
9367 ECSignature
.prototype.toDER = function () {
9368 var r
= Buffer
.from(this.r
.toDERInteger())
9369 var s
= Buffer
.from(this.s
.toDERInteger())
9371 return bip66
.encode(r
, s
)
9374 ECSignature
.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)
9381 ECSignature
.prototype.toScriptSignature = function (hashType
) {
9382 var hashTypeMod
= hashType
& ~0x80
9383 if (hashTypeMod
<= 0 || hashTypeMod
>= 4) throw new Error('Invalid hashType ' + hashType
)
9385 var hashTypeBuffer
= Buffer
.alloc(1)
9386 hashTypeBuffer
.writeUInt8(hashType
, 0)
9388 return Buffer
.concat([this.toDER(), hashTypeBuffer
])
9391 module
.exports
= ECSignature
9393 }).call(this,require("buffer").Buffer
)
9394 },{"./types":80,"bigi":39,"bip66":41,"buffer":5,"typeforce":112}],51:[function(require
,module
,exports
){
9395 var Buffer
= require('safe-buffer').Buffer
9396 var base58check
= require('bs58check')
9397 var bcrypto
= require('./crypto')
9398 var createHmac
= require('create-hmac')
9399 var typeforce
= require('typeforce')
9400 var types
= require('./types')
9401 var NETWORKS
= require('./networks')
9403 var BigInteger
= require('bigi')
9404 var ECPair
= require('./ecpair')
9406 var ecurve
= require('ecurve')
9407 var curve
= ecurve
.getCurveByName('secp256k1')
9409 function HDNode (keyPair
, chainCode
) {
9410 typeforce(types
.tuple('ECPair', types
.Buffer256bit
), arguments
)
9412 if (!keyPair
.compressed
) throw new TypeError('BIP32 only allows compressed keyPairs')
9414 this.keyPair
= keyPair
9415 this.chainCode
= chainCode
9418 this.parentFingerprint
= 0x00000000
9421 HDNode
.HIGHEST_BIT
= 0x80000000
9423 HDNode
.MASTER_SECRET
= Buffer
.from('Bitcoin seed', 'utf8')
9425 HDNode
.fromSeedBuffer = function (seed
, network
) {
9426 typeforce(types
.tuple(types
.Buffer
, types
.maybe(types
.Network
)), arguments
)
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')
9431 var I
= createHmac('sha512', HDNode
.MASTER_SECRET
).update(seed
).digest()
9432 var IL
= I
.slice(0, 32)
9433 var IR
= I
.slice(32)
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, {
9442 return new HDNode(keyPair
, IR
)
9445 HDNode
.fromSeedHex = function (hex
, network
) {
9446 return HDNode
.fromSeedBuffer(Buffer
.from(hex
, 'hex'), network
)
9449 HDNode
.fromBase58 = function (string
, networks
) {
9450 var buffer
= base58check
.decode(string
)
9451 if (buffer
.length
!== 78) throw new Error('Invalid buffer length')
9453 // 4 bytes: version bytes
9454 var version
= buffer
.readUInt32BE(0)
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
9464 if (!network
) throw new Error('Unknown network version')
9466 // otherwise, assume a network object (or default to bitcoin)
9468 network
= networks
|| NETWORKS
.bitcoin
9471 if (version
!== network
.bip32
.private &&
9472 version
!== network
.bip32
.public) throw new Error('Invalid network version')
9474 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
9475 var depth
= buffer
[4]
9477 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9478 var parentFingerprint
= buffer
.readUInt32BE(5)
9480 if (parentFingerprint
!== 0x00000000) throw new Error('Invalid parent fingerprint')
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')
9488 // 32 bytes: the chain code
9489 var chainCode
= buffer
.slice(13, 45)
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')
9496 var d
= BigInteger
.fromBuffer(buffer
.slice(46, 78))
9497 keyPair
= new ECPair(d
, null, { network: network
})
9499 // 33 bytes: public key data (0x02 + X or 0x03 + X)
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
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.
9508 keyPair
= new ECPair(null, Q
, { network: network
})
9511 var hd
= new HDNode(keyPair
, chainCode
)
9514 hd
.parentFingerprint
= parentFingerprint
9519 HDNode
.prototype.getAddress = function () {
9520 return this.keyPair
.getAddress()
9523 HDNode
.prototype.getIdentifier = function () {
9524 return bcrypto
.hash160(this.keyPair
.getPublicKeyBuffer())
9527 HDNode
.prototype.getFingerprint = function () {
9528 return this.getIdentifier().slice(0, 4)
9531 HDNode
.prototype.getNetwork = function () {
9532 return this.keyPair
.getNetwork()
9535 HDNode
.prototype.getPublicKeyBuffer = function () {
9536 return this.keyPair
.getPublicKeyBuffer()
9539 HDNode
.prototype.neutered = function () {
9540 var neuteredKeyPair
= new ECPair(null, this.keyPair
.Q
, {
9541 network: this.keyPair
.network
9544 var neutered
= new HDNode(neuteredKeyPair
, this.chainCode
)
9545 neutered
.depth
= this.depth
9546 neutered
.index
= this.index
9547 neutered
.parentFingerprint
= this.parentFingerprint
9552 HDNode
.prototype.sign = function (hash
) {
9553 return this.keyPair
.sign(hash
)
9556 HDNode
.prototype.verify = function (hash
, signature
) {
9557 return this.keyPair
.verify(hash
, signature
)
9560 HDNode
.prototype.toBase58 = function (__isPrivate
) {
9561 if (__isPrivate
!== undefined) throw new TypeError('Unsupported argument in 2.0.0')
9564 var network
= this.keyPair
.network
9565 var version
= (!this.isNeutered()) ? network
.bip32
.private : network
.bip32
.public
9566 var buffer
= Buffer
.allocUnsafe(78)
9568 // 4 bytes: version bytes
9569 buffer
.writeUInt32BE(version
, 0)
9571 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
9572 buffer
.writeUInt8(this.depth
, 4)
9574 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9575 buffer
.writeUInt32BE(this.parentFingerprint
, 5)
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)
9581 // 32 bytes: the chain code
9582 this.chainCode
.copy(buffer
, 13)
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)
9590 // 33 bytes: the public key
9592 // X9.62 encoding for public keys
9593 this.keyPair
.getPublicKeyBuffer().copy(buffer
, 45)
9596 return base58check
.encode(buffer
)
9599 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
9600 HDNode
.prototype.derive = function (index
) {
9601 typeforce(types
.UInt32
, index
)
9603 var isHardened
= index
>= HDNode
.HIGHEST_BIT
9604 var data
= Buffer
.allocUnsafe(37)
9608 if (this.isNeutered()) throw new TypeError('Could not derive hardened child key')
9610 // data = 0x00 || ser256(kpar) || ser32(index)
9612 this.keyPair
.d
.toBuffer(32).copy(data
, 1)
9613 data
.writeUInt32BE(index
, 33)
9617 // data = serP(point(kpar)) || ser32(index)
9618 // = serP(Kpar) || ser32(index)
9619 this.keyPair
.getPublicKeyBuffer().copy(data
, 0)
9620 data
.writeUInt32BE(index
, 33)
9623 var I
= createHmac('sha512', this.chainCode
).update(data
).digest()
9624 var IL
= I
.slice(0, 32)
9625 var IR
= I
.slice(32)
9627 var pIL
= BigInteger
.fromBuffer(IL
)
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)
9634 // Private parent key -> private child key
9636 if (!this.isNeutered()) {
9637 // ki = parse256(IL) + kpar (mod n)
9638 var ki
= pIL
.add(this.keyPair
.d
).mod(curve
.n
)
9640 // In case ki == 0, proceed with the next value for i
9641 if (ki
.signum() === 0) {
9642 return this.derive(index
+ 1)
9645 derivedKeyPair
= new ECPair(ki
, null, {
9646 network: this.keyPair
.network
9649 // Public parent key -> public child key
9651 // Ki = point(parse256(IL)) + Kpar
9653 var Ki
= curve
.G
.multiply(pIL
).add(this.keyPair
.Q
)
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)
9660 derivedKeyPair
= new ECPair(null, Ki
, {
9661 network: this.keyPair
.network
9665 var hd
= new HDNode(derivedKeyPair
, IR
)
9666 hd
.depth
= this.depth
+ 1
9668 hd
.parentFingerprint
= this.getFingerprint().readUInt32BE(0)
9673 HDNode
.prototype.deriveHardened = function (index
) {
9674 typeforce(types
.UInt31
, index
)
9676 // Only derives hardened private keys by default
9677 return this.derive(index
+ HDNode
.HIGHEST_BIT
)
9680 // Private === not neutered
9681 // Public === neutered
9682 HDNode
.prototype.isNeutered = function () {
9683 return !(this.keyPair
.d
)
9686 HDNode
.prototype.derivePath = function (path
) {
9687 typeforce(types
.BIP32Path
, path
)
9689 var splitPath
= path
.split('/')
9690 if (splitPath
[0] === 'm') {
9691 if (this.parentFingerprint
) {
9692 throw new Error('Not a master node')
9695 splitPath
= splitPath
.slice(1)
9698 return splitPath
.reduce(function (prevHd
, indexStr
) {
9700 if (indexStr
.slice(-1) === "'") {
9701 index
= parseInt(indexStr
.slice(0, -1), 10)
9702 return prevHd
.deriveHardened(index
)
9704 index
= parseInt(indexStr
, 10)
9705 return prevHd
.derive(index
)
9710 module
.exports
= HDNode
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
){
9713 var script
= require('./script')
9715 var templates
= require('./templates')
9716 for (var key
in templates
) {
9717 script
[key
] = templates
[key
]
9721 bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0
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'),
9730 address: require('./address'),
9731 crypto: require('./crypto'),
9732 networks: require('./networks'),
9733 opcodes: require('bitcoin-ops'),
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
){
9738 // https://en.bitcoin.it/wiki/List_of_address_prefixes
9739 // Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
9743 messagePrefix: '\x18Bitcoin Signed Message:\n',
9754 messagePrefix: '\x18Bitcoin Signed Message:\n',
9765 messagePrefix: '\x19Litecoin Signed Message:\n',
9776 },{}],54:[function(require
,module
,exports
){
9777 var Buffer
= require('safe-buffer').Buffer
9778 var bip66
= require('bip66')
9779 var pushdata
= require('pushdata-bitcoin')
9780 var typeforce
= require('typeforce')
9781 var types
= require('./types')
9782 var scriptNumber
= require('./script_number')
9784 var OPS
= require('bitcoin-ops')
9785 var REVERSE_OPS
= require('bitcoin-ops/map')
9786 var OP_INT_BASE
= OPS
.OP_RESERVED
// OP_1 - 1
9788 function 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
))
9795 function isPushOnlyChunk (value
) {
9796 return types
.Buffer(value
) || isOPInt(value
)
9799 function isPushOnly (value
) {
9800 return types
.Array(value
) && value
.every(isPushOnlyChunk
)
9803 function 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
9810 function compile (chunks
) {
9812 if (Buffer
.isBuffer(chunks
)) return chunks
9814 typeforce(types
.Array
, chunks
)
9816 var bufferSize
= chunks
.reduce(function (accum
, chunk
) {
9818 if (Buffer
.isBuffer(chunk
)) {
9819 // adhere to BIP62.3, minimal push policy
9820 if (chunk
.length
=== 1 && asMinimalOP(chunk
) !== undefined) {
9824 return accum
+ pushdata
.encodingLength(chunk
.length
) + chunk
.length
9831 var buffer
= Buffer
.allocUnsafe(bufferSize
)
9834 chunks
.forEach(function (chunk
) {
9836 if (Buffer
.isBuffer(chunk
)) {
9837 // adhere to BIP62.3, minimal push policy
9838 var opcode
= asMinimalOP(chunk
)
9839 if (opcode
!== undefined) {
9840 buffer
.writeUInt8(opcode
, offset
)
9845 offset
+= pushdata
.encode(buffer
, chunk
.length
, offset
)
9846 chunk
.copy(buffer
, offset
)
9847 offset
+= chunk
.length
9851 buffer
.writeUInt8(chunk
, offset
)
9856 if (offset
!== buffer
.length
) throw new Error('Could not decode chunks')
9860 function decompile (buffer
) {
9862 if (types
.Array(buffer
)) return buffer
9864 typeforce(types
.Buffer
, buffer
)
9869 while (i
< buffer
.length
) {
9870 var opcode
= buffer
[i
]
9873 if ((opcode
> OPS
.OP_0
) && (opcode
<= OPS
.OP_PUSHDATA4
)) {
9874 var d
= pushdata
.decode(buffer
, i
)
9876 // did reading a pushDataInt fail? empty script
9877 if (d
=== null) return []
9880 // attempt to read too much data? empty script
9881 if (i
+ d
.number
> buffer
.length
) return []
9883 var data
= buffer
.slice(i
, i
+ d
.number
)
9886 // decompile minimally
9887 var op
= asMinimalOP(data
)
9888 if (op
!== undefined) {
9905 function toASM (chunks
) {
9906 if (Buffer
.isBuffer(chunks
)) {
9907 chunks
= decompile(chunks
)
9910 return chunks
.map(function (chunk
) {
9912 if (Buffer
.isBuffer(chunk
)) {
9913 var op
= asMinimalOP(chunk
)
9914 if (op
=== undefined) return chunk
.toString('hex')
9919 return REVERSE_OPS
[chunk
]
9923 function fromASM (asm
) {
9924 typeforce(types
.String
, asm
)
9926 return compile(asm
.split(' ').map(function (chunkStr
) {
9928 if (OPS
[chunkStr
] !== undefined) return OPS
[chunkStr
]
9929 typeforce(types
.Hex
, chunkStr
)
9932 return Buffer
.from(chunkStr
, 'hex')
9936 function toStack (chunks
) {
9937 chunks
= decompile(chunks
)
9938 typeforce(isPushOnly
, chunks
)
9940 return chunks
.map(function (op
) {
9941 if (Buffer
.isBuffer(op
)) return op
9942 if (op
=== OPS
.OP_0
) return Buffer
.allocUnsafe(0)
9944 return scriptNumber
.encode(op
- OP_INT_BASE
)
9948 function isCanonicalPubKey (buffer
) {
9949 if (!Buffer
.isBuffer(buffer
)) return false
9950 if (buffer
.length
< 33) return false
9952 switch (buffer
[0]) {
9955 return buffer
.length
=== 33
9957 return buffer
.length
=== 65
9963 function isDefinedHashType (hashType
) {
9964 var hashTypeMod
= hashType
& ~0x80
9966 // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE
9967 return hashTypeMod
> 0x00 && hashTypeMod
< 0x04
9970 function isCanonicalSignature (buffer
) {
9971 if (!Buffer
.isBuffer(buffer
)) return false
9972 if (!isDefinedHashType(buffer
[buffer
.length
- 1])) return false
9974 return bip66
.check(buffer
.slice(0, -1))
9979 decompile: decompile
,
9984 number: require('./script_number'),
9986 isCanonicalPubKey: isCanonicalPubKey
,
9987 isCanonicalSignature: isCanonicalSignature
,
9988 isPushOnly: isPushOnly
,
9989 isDefinedHashType: isDefinedHashType
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
){
9993 var Buffer
= require('safe-buffer').Buffer
9995 function decode (buffer
, maxLength
, minimal
) {
9996 maxLength
= maxLength
|| 4
9997 minimal
= minimal
=== undefined ? true : minimal
9999 var length
= buffer
.length
10000 if (length
=== 0) return 0
10001 if (length
> maxLength
) throw new TypeError('Script number overflow')
10003 if ((buffer
[length
- 1] & 0x7f) === 0) {
10004 if (length
<= 1 || (buffer
[length
- 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number')
10009 if (length
=== 5) {
10010 var a
= buffer
.readUInt32LE(0)
10011 var b
= buffer
.readUInt8(4)
10013 if (b
& 0x80) return -(((b
& ~0x80) * 0x100000000) + a
)
10014 return (b
* 0x100000000) + a
10019 // 32-bit / 24-bit / 16-bit / 8-bit
10020 for (var i
= 0; i
< length
; ++i
) {
10021 result
|= buffer
[i
] << (8 * i
)
10024 if (buffer
[length
- 1] & 0x80) return -(result
& ~(0x80 << (8 * (length
- 1))))
10028 function scriptNumSize (i
) {
10029 return i
> 0x7fffffff ? 5
10037 function encode (number
) {
10038 var value
= Math
.abs(number
)
10039 var size
= scriptNumSize(value
)
10040 var buffer
= Buffer
.allocUnsafe(size
)
10041 var negative
= number
< 0
10043 for (var i
= 0; i
< size
; ++i
) {
10044 buffer
.writeUInt8(value
& 0xff, i
)
10048 if (buffer
[size
- 1] & 0x80) {
10049 buffer
.writeUInt8(negative
? 0x80 : 0x00, size
- 1)
10050 } else if (negative
) {
10051 buffer
[size
- 1] |= 0x80
10062 },{"safe-buffer":101}],56:[function(require
,module
,exports
){
10063 var decompile
= require('../script').decompile
10064 var multisig
= require('./multisig')
10065 var nullData
= require('./nulldata')
10066 var pubKey
= require('./pubkey')
10067 var pubKeyHash
= require('./pubkeyhash')
10068 var scriptHash
= require('./scripthash')
10069 var witnessPubKeyHash
= require('./witnesspubkeyhash')
10070 var witnessScriptHash
= require('./witnessscripthash')
10071 var witnessCommitment
= require('./witnesscommitment')
10074 MULTISIG: 'multisig',
10075 NONSTANDARD: 'nonstandard',
10076 NULLDATA: 'nulldata',
10078 P2PKH: 'pubkeyhash',
10079 P2SH: 'scripthash',
10080 P2WPKH: 'witnesspubkeyhash',
10081 P2WSH: 'witnessscripthash',
10082 WITNESS_COMMITMENT: 'witnesscommitment'
10085 function 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
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
10098 return types
.NONSTANDARD
10101 function classifyInput (script
, allowIncomplete
) {
10102 // XXX: optimization, below functions .decompile before use
10103 var chunks
= decompile(script
)
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
10110 return types
.NONSTANDARD
10113 function classifyWitness (script
, allowIncomplete
) {
10114 // XXX: optimization, below functions .decompile before use
10115 var chunks
= decompile(script
)
10117 if (witnessPubKeyHash
.input
.check(chunks
)) return types
.P2WPKH
10118 if (witnessScriptHash
.input
.check(chunks
, allowIncomplete
)) return types
.P2WSH
10120 return types
.NONSTANDARD
10124 classifyInput: classifyInput
,
10125 classifyOutput: classifyOutput
,
10126 classifyWitness: classifyWitness
,
10127 multisig: multisig
,
10128 nullData: nullData
,
10130 pubKeyHash: pubKeyHash
,
10131 scriptHash: scriptHash
,
10132 witnessPubKeyHash: witnessPubKeyHash
,
10133 witnessScriptHash: witnessScriptHash
,
10134 witnessCommitment: witnessCommitment
,
10138 },{"../script":54,"./multisig":57,"./nulldata":60,"./pubkey":61,"./pubkeyhash":64,"./scripthash":67,"./witnesscommitment":70,"./witnesspubkeyhash":72,"./witnessscripthash":75}],57:[function(require
,module
,exports
){
10140 input: require('./input'),
10141 output: require('./output')
10144 },{"./input":58,"./output":59}],58:[function(require
,module
,exports
){
10145 // OP_0 [signatures ...]
10147 var Buffer
= require('safe-buffer').Buffer
10148 var bscript
= require('../../script')
10149 var p2mso
= require('./output')
10150 var typeforce
= require('typeforce')
10151 var OPS
= require('bitcoin-ops')
10153 function partialSignature (value
) {
10154 return value
=== OPS
.OP_0
|| bscript
.isCanonicalSignature(value
)
10157 function 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
10162 if (allowIncomplete
) {
10163 return chunks
.slice(1).every(partialSignature
)
10166 return chunks
.slice(1).every(bscript
.isCanonicalSignature
)
10168 check
.toJSON = function () { return 'multisig input' }
10170 var EMPTY_BUFFER
= Buffer
.allocUnsafe(0)
10172 function encodeStack (signatures
, scriptPubKey
) {
10173 typeforce([partialSignature
], signatures
)
10175 if (scriptPubKey
) {
10176 var scriptData
= p2mso
.decode(scriptPubKey
)
10178 if (signatures
.length
< scriptData
.m
) {
10179 throw new TypeError('Not enough signatures provided')
10182 if (signatures
.length
> scriptData
.pubKeys
.length
) {
10183 throw new TypeError('Too many signatures provided')
10187 return [].concat(EMPTY_BUFFER
, signatures
.map(function (sig
) {
10188 if (sig
=== OPS
.OP_0
) {
10189 return EMPTY_BUFFER
10195 function encode (signatures
, scriptPubKey
) {
10196 return bscript
.compile(encodeStack(signatures
, scriptPubKey
))
10199 function decodeStack (stack
, allowIncomplete
) {
10200 typeforce(typeforce
.Array
, stack
)
10201 typeforce(check
, stack
, allowIncomplete
)
10202 return stack
.slice(1)
10205 function decode (buffer
, allowIncomplete
) {
10206 var stack
= bscript
.decompile(buffer
)
10207 return decodeStack(stack
, allowIncomplete
)
10213 decodeStack: decodeStack
,
10215 encodeStack: encodeStack
10218 },{"../../script":54,"./output":59,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],59:[function(require
,module
,exports
){
10219 // m [pubKeys ...] n OP_CHECKMULTISIG
10221 var bscript
= require('../../script')
10222 var types
= require('../../types')
10223 var typeforce
= require('typeforce')
10224 var OPS
= require('bitcoin-ops')
10225 var OP_INT_BASE
= OPS
.OP_RESERVED
// OP_1 - 1
10227 function check (script
, allowIncomplete
) {
10228 var chunks
= bscript
.decompile(script
)
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
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
10243 var keys
= chunks
.slice(1, -2)
10244 return keys
.every(bscript
.isCanonicalPubKey
)
10246 check
.toJSON = function () { return 'multi-sig output' }
10248 function encode (m
, pubKeys
) {
10251 pubKeys: [bscript
.isCanonicalPubKey
]
10257 var n
= pubKeys
.length
10258 if (n
< m
) throw new TypeError('Not enough pubKeys provided')
10260 return bscript
.compile([].concat(
10264 OPS
.OP_CHECKMULTISIG
10268 function decode (buffer
, allowIncomplete
) {
10269 var chunks
= bscript
.decompile(buffer
)
10270 typeforce(check
, chunks
, allowIncomplete
)
10273 m: chunks
[0] - OP_INT_BASE
,
10274 pubKeys: chunks
.slice(1, -2)
10284 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],60:[function(require
,module
,exports
){
10285 // OP_RETURN {data}
10287 var bscript
= require('../script')
10288 var types
= require('../types')
10289 var typeforce
= require('typeforce')
10290 var OPS
= require('bitcoin-ops')
10292 function check (script
) {
10293 var buffer
= bscript
.compile(script
)
10295 return buffer
.length
> 1 &&
10296 buffer
[0] === OPS
.OP_RETURN
10298 check
.toJSON = function () { return 'null data output' }
10300 function encode (data
) {
10301 typeforce(types
.Buffer
, data
)
10303 return bscript
.compile([OPS
.OP_RETURN
, data
])
10306 function decode (buffer
) {
10307 typeforce(check
, buffer
)
10309 return buffer
.slice(2)
10320 },{"../script":54,"../types":80,"bitcoin-ops":42,"typeforce":112}],61:[function(require
,module
,exports
){
10321 arguments
[4][57][0].apply(exports
,arguments
)
10322 },{"./input":62,"./output":63,"dup":57}],62:[function(require
,module
,exports
){
10325 var bscript
= require('../../script')
10326 var typeforce
= require('typeforce')
10328 function check (script
) {
10329 var chunks
= bscript
.decompile(script
)
10331 return chunks
.length
=== 1 &&
10332 bscript
.isCanonicalSignature(chunks
[0])
10334 check
.toJSON = function () { return 'pubKey input' }
10336 function encodeStack (signature
) {
10337 typeforce(bscript
.isCanonicalSignature
, signature
)
10341 function encode (signature
) {
10342 return bscript
.compile(encodeStack(signature
))
10345 function decodeStack (stack
) {
10346 typeforce(typeforce
.Array
, stack
)
10347 typeforce(check
, stack
)
10351 function decode (buffer
) {
10352 var stack
= bscript
.decompile(buffer
)
10353 return decodeStack(stack
)
10359 decodeStack: decodeStack
,
10361 encodeStack: encodeStack
10364 },{"../../script":54,"typeforce":112}],63:[function(require
,module
,exports
){
10365 // {pubKey} OP_CHECKSIG
10367 var bscript
= require('../../script')
10368 var typeforce
= require('typeforce')
10369 var OPS
= require('bitcoin-ops')
10371 function check (script
) {
10372 var chunks
= bscript
.decompile(script
)
10374 return chunks
.length
=== 2 &&
10375 bscript
.isCanonicalPubKey(chunks
[0]) &&
10376 chunks
[1] === OPS
.OP_CHECKSIG
10378 check
.toJSON = function () { return 'pubKey output' }
10380 function encode (pubKey
) {
10381 typeforce(bscript
.isCanonicalPubKey
, pubKey
)
10383 return bscript
.compile([pubKey
, OPS
.OP_CHECKSIG
])
10386 function decode (buffer
) {
10387 var chunks
= bscript
.decompile(buffer
)
10388 typeforce(check
, chunks
)
10399 },{"../../script":54,"bitcoin-ops":42,"typeforce":112}],64:[function(require
,module
,exports
){
10400 arguments
[4][57][0].apply(exports
,arguments
)
10401 },{"./input":65,"./output":66,"dup":57}],65:[function(require
,module
,exports
){
10402 // {signature} {pubKey}
10404 var bscript
= require('../../script')
10405 var typeforce
= require('typeforce')
10407 function check (script
) {
10408 var chunks
= bscript
.decompile(script
)
10410 return chunks
.length
=== 2 &&
10411 bscript
.isCanonicalSignature(chunks
[0]) &&
10412 bscript
.isCanonicalPubKey(chunks
[1])
10414 check
.toJSON = function () { return 'pubKeyHash input' }
10416 function encodeStack (signature
, pubKey
) {
10418 signature: bscript
.isCanonicalSignature
,
10419 pubKey: bscript
.isCanonicalPubKey
10421 signature: signature
,
10425 return [signature
, pubKey
]
10428 function encode (signature
, pubKey
) {
10429 return bscript
.compile(encodeStack(signature
, pubKey
))
10432 function decodeStack (stack
) {
10433 typeforce(typeforce
.Array
, stack
)
10434 typeforce(check
, stack
)
10437 signature: stack
[0],
10442 function decode (buffer
) {
10443 var stack
= bscript
.decompile(buffer
)
10444 return decodeStack(stack
)
10450 decodeStack: decodeStack
,
10452 encodeStack: encodeStack
10455 },{"../../script":54,"typeforce":112}],66:[function(require
,module
,exports
){
10456 // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
10458 var bscript
= require('../../script')
10459 var types
= require('../../types')
10460 var typeforce
= require('typeforce')
10461 var OPS
= require('bitcoin-ops')
10463 function check (script
) {
10464 var buffer
= bscript
.compile(script
)
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
10473 check
.toJSON = function () { return 'pubKeyHash output' }
10475 function encode (pubKeyHash
) {
10476 typeforce(types
.Hash160bit
, pubKeyHash
)
10478 return bscript
.compile([
10482 OPS
.OP_EQUALVERIFY
,
10487 function decode (buffer
) {
10488 typeforce(check
, buffer
)
10490 return buffer
.slice(3, 23)
10499 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],67:[function(require
,module
,exports
){
10500 arguments
[4][57][0].apply(exports
,arguments
)
10501 },{"./input":68,"./output":69,"dup":57}],68:[function(require
,module
,exports
){
10502 // <scriptSig> {serialized scriptPubKey script}
10504 var Buffer
= require('safe-buffer').Buffer
10505 var bscript
= require('../../script')
10506 var typeforce
= require('typeforce')
10508 var p2ms
= require('../multisig/')
10509 var p2pk
= require('../pubkey/')
10510 var p2pkh
= require('../pubkeyhash/')
10511 var p2wpkho
= require('../witnesspubkeyhash/output')
10512 var p2wsho
= require('../witnessscripthash/output')
10514 function check (script
, allowIncomplete
) {
10515 var chunks
= bscript
.decompile(script
)
10516 if (chunks
.length
< 1) return false
10518 var lastChunk
= chunks
[chunks
.length
- 1]
10519 if (!Buffer
.isBuffer(lastChunk
)) return false
10521 var scriptSigChunks
= bscript
.decompile(bscript
.compile(chunks
.slice(0, -1)))
10522 var redeemScriptChunks
= bscript
.decompile(lastChunk
)
10524 // is redeemScript a valid script?
10525 if (redeemScriptChunks
.length
=== 0) return false
10527 // is redeemScriptSig push only?
10528 if (!bscript
.isPushOnly(scriptSigChunks
)) return false
10531 if (chunks
.length
=== 1) {
10532 return p2wsho
.check(redeemScriptChunks
) ||
10533 p2wpkho
.check(redeemScriptChunks
)
10537 if (p2pkh
.input
.check(scriptSigChunks
) &&
10538 p2pkh
.output
.check(redeemScriptChunks
)) return true
10540 if (p2ms
.input
.check(scriptSigChunks
, allowIncomplete
) &&
10541 p2ms
.output
.check(redeemScriptChunks
)) return true
10543 if (p2pk
.input
.check(scriptSigChunks
) &&
10544 p2pk
.output
.check(redeemScriptChunks
)) return true
10548 check
.toJSON = function () { return 'scriptHash input' }
10550 function encodeStack (redeemScriptStack
, redeemScript
) {
10551 var serializedScriptPubKey
= bscript
.compile(redeemScript
)
10553 return [].concat(redeemScriptStack
, serializedScriptPubKey
)
10556 function encode (redeemScriptSig
, redeemScript
) {
10557 var redeemScriptStack
= bscript
.decompile(redeemScriptSig
)
10559 return bscript
.compile(encodeStack(redeemScriptStack
, redeemScript
))
10562 function decodeStack (stack
) {
10563 typeforce(typeforce
.Array
, stack
)
10564 typeforce(check
, stack
)
10567 redeemScriptStack: stack
.slice(0, -1),
10568 redeemScript: stack
[stack
.length
- 1]
10572 function decode (buffer
) {
10573 var stack
= bscript
.decompile(buffer
)
10574 var result
= decodeStack(stack
)
10575 result
.redeemScriptSig
= bscript
.compile(result
.redeemScriptStack
)
10576 delete result
.redeemScriptStack
10583 decodeStack: decodeStack
,
10585 encodeStack: encodeStack
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
){
10589 // OP_HASH160 {scriptHash} OP_EQUAL
10591 var bscript
= require('../../script')
10592 var types
= require('../../types')
10593 var typeforce
= require('typeforce')
10594 var OPS
= require('bitcoin-ops')
10596 function check (script
) {
10597 var buffer
= bscript
.compile(script
)
10599 return buffer
.length
=== 23 &&
10600 buffer
[0] === OPS
.OP_HASH160
&&
10601 buffer
[1] === 0x14 &&
10602 buffer
[22] === OPS
.OP_EQUAL
10604 check
.toJSON = function () { return 'scriptHash output' }
10606 function encode (scriptHash
) {
10607 typeforce(types
.Hash160bit
, scriptHash
)
10609 return bscript
.compile([OPS
.OP_HASH160
, scriptHash
, OPS
.OP_EQUAL
])
10612 function decode (buffer
) {
10613 typeforce(check
, buffer
)
10615 return buffer
.slice(2, 22)
10624 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],70:[function(require
,module
,exports
){
10626 output: require('./output')
10629 },{"./output":71}],71:[function(require
,module
,exports
){
10630 // OP_RETURN {aa21a9ed} {commitment}
10632 var Buffer
= require('safe-buffer').Buffer
10633 var bscript
= require('../../script')
10634 var types
= require('../../types')
10635 var typeforce
= require('typeforce')
10636 var OPS
= require('bitcoin-ops')
10638 var HEADER
= Buffer
.from('aa21a9ed', 'hex')
10640 function check (script
) {
10641 var buffer
= bscript
.compile(script
)
10643 return buffer
.length
> 37 &&
10644 buffer
[0] === OPS
.OP_RETURN
&&
10645 buffer
[1] === 0x24 &&
10646 buffer
.slice(2, 6).equals(HEADER
)
10649 check
.toJSON = function () { return 'Witness commitment output' }
10651 function encode (commitment
) {
10652 typeforce(types
.Hash256bit
, commitment
)
10654 var buffer
= Buffer
.allocUnsafe(36)
10655 HEADER
.copy(buffer
, 0)
10656 commitment
.copy(buffer
, 4)
10658 return bscript
.compile([OPS
.OP_RETURN
, buffer
])
10661 function decode (buffer
) {
10662 typeforce(check
, buffer
)
10664 return bscript
.decompile(buffer
)[1].slice(4, 36)
10673 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],72:[function(require
,module
,exports
){
10674 arguments
[4][57][0].apply(exports
,arguments
)
10675 },{"./input":73,"./output":74,"dup":57}],73:[function(require
,module
,exports
){
10676 // {signature} {pubKey}
10678 var bscript
= require('../../script')
10679 var typeforce
= require('typeforce')
10681 function isCompressedCanonicalPubKey (pubKey
) {
10682 return bscript
.isCanonicalPubKey(pubKey
) && pubKey
.length
=== 33
10685 function check (script
) {
10686 var chunks
= bscript
.decompile(script
)
10688 return chunks
.length
=== 2 &&
10689 bscript
.isCanonicalSignature(chunks
[0]) &&
10690 isCompressedCanonicalPubKey(chunks
[1])
10692 check
.toJSON = function () { return 'witnessPubKeyHash input' }
10694 function encodeStack (signature
, pubKey
) {
10696 signature: bscript
.isCanonicalSignature
,
10697 pubKey: isCompressedCanonicalPubKey
10699 signature: signature
,
10703 return [signature
, pubKey
]
10706 function decodeStack (stack
) {
10707 typeforce(typeforce
.Array
, stack
)
10708 typeforce(check
, stack
)
10711 signature: stack
[0],
10718 decodeStack: decodeStack
,
10719 encodeStack: encodeStack
10722 },{"../../script":54,"typeforce":112}],74:[function(require
,module
,exports
){
10723 // OP_0 {pubKeyHash}
10725 var bscript
= require('../../script')
10726 var types
= require('../../types')
10727 var typeforce
= require('typeforce')
10728 var OPS
= require('bitcoin-ops')
10730 function check (script
) {
10731 var buffer
= bscript
.compile(script
)
10733 return buffer
.length
=== 22 &&
10734 buffer
[0] === OPS
.OP_0
&&
10737 check
.toJSON = function () { return 'Witness pubKeyHash output' }
10739 function encode (pubKeyHash
) {
10740 typeforce(types
.Hash160bit
, pubKeyHash
)
10742 return bscript
.compile([OPS
.OP_0
, pubKeyHash
])
10745 function decode (buffer
) {
10746 typeforce(check
, buffer
)
10748 return buffer
.slice(2)
10757 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],75:[function(require
,module
,exports
){
10758 arguments
[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}
10763 var bscript
= require('../../script')
10764 var types
= require('../../types')
10765 var typeforce
= require('typeforce')
10767 var p2ms
= require('../multisig/')
10768 var p2pk
= require('../pubkey/')
10769 var p2pkh
= require('../pubkeyhash/')
10771 function check (chunks
, allowIncomplete
) {
10772 typeforce(types
.Array
, chunks
)
10773 if (chunks
.length
< 1) return false
10775 var witnessScript
= chunks
[chunks
.length
- 1]
10776 if (!Buffer
.isBuffer(witnessScript
)) return false
10778 var witnessScriptChunks
= bscript
.decompile(witnessScript
)
10780 // is witnessScript a valid script?
10781 if (witnessScriptChunks
.length
=== 0) return false
10783 var witnessRawScriptSig
= bscript
.compile(chunks
.slice(0, -1))
10786 if (p2pkh
.input
.check(witnessRawScriptSig
) &&
10787 p2pkh
.output
.check(witnessScriptChunks
)) return true
10789 if (p2ms
.input
.check(witnessRawScriptSig
, allowIncomplete
) &&
10790 p2ms
.output
.check(witnessScriptChunks
)) return true
10792 if (p2pk
.input
.check(witnessRawScriptSig
) &&
10793 p2pk
.output
.check(witnessScriptChunks
)) return true
10797 check
.toJSON = function () { return 'witnessScriptHash input' }
10799 function encodeStack (witnessData
, witnessScript
) {
10801 witnessData: [types
.Buffer
],
10802 witnessScript: types
.Buffer
10804 witnessData: witnessData
,
10805 witnessScript: witnessScript
10808 return [].concat(witnessData
, witnessScript
)
10811 function decodeStack (stack
) {
10812 typeforce(typeforce
.Array
, stack
)
10813 typeforce(check
, stack
)
10815 witnessData: stack
.slice(0, -1),
10816 witnessScript: stack
[stack
.length
- 1]
10822 decodeStack: decodeStack
,
10823 encodeStack: encodeStack
10826 }).call(this,{"isBuffer":require("../../../../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
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
){
10828 // OP_0 {scriptHash}
10830 var bscript
= require('../../script')
10831 var types
= require('../../types')
10832 var typeforce
= require('typeforce')
10833 var OPS
= require('bitcoin-ops')
10835 function check (script
) {
10836 var buffer
= bscript
.compile(script
)
10838 return buffer
.length
=== 34 &&
10839 buffer
[0] === OPS
.OP_0
&&
10842 check
.toJSON = function () { return 'Witness scriptHash output' }
10844 function encode (scriptHash
) {
10845 typeforce(types
.Hash256bit
, scriptHash
)
10847 return bscript
.compile([OPS
.OP_0
, scriptHash
])
10850 function decode (buffer
) {
10851 typeforce(check
, buffer
)
10853 return buffer
.slice(2)
10862 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],78:[function(require
,module
,exports
){
10863 var Buffer
= require('safe-buffer').Buffer
10864 var bcrypto
= require('./crypto')
10865 var bscript
= require('./script')
10866 var bufferutils
= require('./bufferutils')
10867 var opcodes
= require('bitcoin-ops')
10868 var typeforce
= require('typeforce')
10869 var types
= require('./types')
10870 var varuint
= require('varuint-bitcoin')
10872 function varSliceSize (someScript
) {
10873 var length
= someScript
.length
10875 return varuint
.encodingLength(length
) + length
10878 function vectorSize (someVector
) {
10879 var length
= someVector
.length
10881 return varuint
.encodingLength(length
) + someVector
.reduce(function (sum
, witness
) {
10882 return sum
+ varSliceSize(witness
)
10886 function Transaction () {
10893 Transaction
.DEFAULT_SEQUENCE
= 0xffffffff
10894 Transaction
.SIGHASH_ALL
= 0x01
10895 Transaction
.SIGHASH_NONE
= 0x02
10896 Transaction
.SIGHASH_SINGLE
= 0x03
10897 Transaction
.SIGHASH_ANYONECANPAY
= 0x80
10898 Transaction
.ADVANCED_TRANSACTION_MARKER
= 0x00
10899 Transaction
.ADVANCED_TRANSACTION_FLAG
= 0x01
10901 var EMPTY_SCRIPT
= Buffer
.allocUnsafe(0)
10902 var EMPTY_WITNESS
= []
10903 var ZERO
= Buffer
.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
10904 var ONE
= Buffer
.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
10905 var VALUE_UINT64_MAX
= Buffer
.from('ffffffffffffffff', 'hex')
10906 var BLANK_OUTPUT
= {
10907 script: EMPTY_SCRIPT
,
10908 valueBuffer: VALUE_UINT64_MAX
10911 Transaction
.fromBuffer = function (buffer
, __noStrict
) {
10913 function readSlice (n
) {
10915 return buffer
.slice(offset
- n
, offset
)
10918 function readUInt32 () {
10919 var i
= buffer
.readUInt32LE(offset
)
10924 function readInt32 () {
10925 var i
= buffer
.readInt32LE(offset
)
10930 function readUInt64 () {
10931 var i
= bufferutils
.readUInt64LE(buffer
, offset
)
10936 function readVarInt () {
10937 var vi
= varuint
.decode(buffer
, offset
)
10938 offset
+= varuint
.decode
.bytes
10942 function readVarSlice () {
10943 return readSlice(readVarInt())
10946 function readVector () {
10947 var count
= readVarInt()
10949 for (var i
= 0; i
< count
; i
++) vector
.push(readVarSlice())
10953 var tx
= new Transaction()
10954 tx
.version
= readInt32()
10956 var marker
= buffer
.readUInt8(offset
)
10957 var flag
= buffer
.readUInt8(offset
+ 1)
10959 var hasWitnesses
= false
10960 if (marker
=== Transaction
.ADVANCED_TRANSACTION_MARKER
&&
10961 flag
=== Transaction
.ADVANCED_TRANSACTION_FLAG
) {
10963 hasWitnesses
= true
10966 var vinLen
= readVarInt()
10967 for (var i
= 0; i
< vinLen
; ++i
) {
10969 hash: readSlice(32),
10970 index: readUInt32(),
10971 script: readVarSlice(),
10972 sequence: readUInt32(),
10973 witness: EMPTY_WITNESS
10977 var voutLen
= readVarInt()
10978 for (i
= 0; i
< voutLen
; ++i
) {
10980 value: readUInt64(),
10981 script: readVarSlice()
10985 if (hasWitnesses
) {
10986 for (i
= 0; i
< vinLen
; ++i
) {
10987 tx
.ins
[i
].witness
= readVector()
10990 // was this pointless?
10991 if (!tx
.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
10994 tx
.locktime
= readUInt32()
10996 if (__noStrict
) return tx
10997 if (offset
!== buffer
.length
) throw new Error('Transaction has unexpected data')
11002 Transaction
.fromHex = function (hex
) {
11003 return Transaction
.fromBuffer(Buffer
.from(hex
, 'hex'))
11006 Transaction
.isCoinbaseHash = function (buffer
) {
11007 typeforce(types
.Hash256bit
, buffer
)
11008 for (var i
= 0; i
< 32; ++i
) {
11009 if (buffer
[i
] !== 0) return false
11014 Transaction
.prototype.isCoinbase = function () {
11015 return this.ins
.length
=== 1 && Transaction
.isCoinbaseHash(this.ins
[0].hash
)
11018 Transaction
.prototype.addInput = function (hash
, index
, sequence
, scriptSig
) {
11019 typeforce(types
.tuple(
11022 types
.maybe(types
.UInt32
),
11023 types
.maybe(types
.Buffer
)
11026 if (types
.Null(sequence
)) {
11027 sequence
= Transaction
.DEFAULT_SEQUENCE
11030 // Add the input and return the input's index
11031 return (this.ins
.push({
11034 script: scriptSig
|| EMPTY_SCRIPT
,
11035 sequence: sequence
,
11036 witness: EMPTY_WITNESS
11040 Transaction
.prototype.addOutput = function (scriptPubKey
, value
) {
11041 typeforce(types
.tuple(types
.Buffer
, types
.Satoshi
), arguments
)
11043 // Add the output and return the output's index
11044 return (this.outs
.push({
11045 script: scriptPubKey
,
11050 Transaction
.prototype.hasWitnesses = function () {
11051 return this.ins
.some(function (x
) {
11052 return x
.witness
.length
!== 0
11056 Transaction
.prototype.weight = function () {
11057 var base
= this.__byteLength(false)
11058 var total
= this.__byteLength(true)
11059 return base
* 3 + total
11062 Transaction
.prototype.virtualSize = function () {
11063 return Math
.ceil(this.weight() / 4)
11066 Transaction
.prototype.byteLength = function () {
11067 return this.__byteLength(true)
11070 Transaction
.prototype.__byteLength = function (__allowWitness
) {
11071 var hasWitnesses
= __allowWitness
&& this.hasWitnesses()
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)
11083 Transaction
.prototype.clone = function () {
11084 var newTx
= new Transaction()
11085 newTx
.version
= this.version
11086 newTx
.locktime
= this.locktime
11088 newTx
.ins
= this.ins
.map(function (txIn
) {
11092 script: txIn
.script
,
11093 sequence: txIn
.sequence
,
11094 witness: txIn
.witness
11098 newTx
.outs
= this.outs
.map(function (txOut
) {
11100 script: txOut
.script
,
11109 * Hash transaction for signing a specific input.
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.
11116 Transaction
.prototype.hashForSignature = function (inIndex
, prevOutScript
, hashType
) {
11117 typeforce(types
.tuple(types
.UInt32
, types
.Buffer
, /* types.UInt8 */ types
.Number
), arguments
)
11119 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
11120 if (inIndex
>= this.ins
.length
) return ONE
11122 // ignore OP_CODESEPARATOR
11123 var ourScript
= bscript
.compile(bscript
.decompile(prevOutScript
).filter(function (x
) {
11124 return x
!== opcodes
.OP_CODESEPARATOR
11127 var txTmp
= this.clone()
11129 // SIGHASH_NONE: ignore all outputs? (wildcard payee)
11130 if ((hashType
& 0x1f) === Transaction
.SIGHASH_NONE
) {
11133 // ignore sequence numbers (except at inIndex)
11134 txTmp
.ins
.forEach(function (input
, i
) {
11135 if (i
=== inIndex
) return
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
11145 // truncate outputs after
11146 txTmp
.outs
.length
= inIndex
+ 1
11148 // "blank" outputs before
11149 for (var i
= 0; i
< inIndex
; i
++) {
11150 txTmp
.outs
[i
] = BLANK_OUTPUT
11153 // ignore sequence numbers (except at inIndex)
11154 txTmp
.ins
.forEach(function (input
, y
) {
11155 if (y
=== inIndex
) return
11161 // SIGHASH_ANYONECANPAY: ignore inputs entirely?
11162 if (hashType
& Transaction
.SIGHASH_ANYONECANPAY
) {
11163 txTmp
.ins
= [txTmp
.ins
[inIndex
]]
11164 txTmp
.ins
[0].script
= ourScript
11166 // SIGHASH_ALL: only ignore input scripts
11168 // "blank" others input scripts
11169 txTmp
.ins
.forEach(function (input
) { input
.script
= EMPTY_SCRIPT
})
11170 txTmp
.ins
[inIndex
].script
= ourScript
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)
11178 return bcrypto
.hash256(buffer
)
11181 Transaction
.prototype.hashForWitnessV0 = function (inIndex
, prevOutScript
, value
, hashType
) {
11182 typeforce(types
.tuple(types
.UInt32
, types
.Buffer
, types
.Satoshi
, types
.UInt32
), arguments
)
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
11192 function writeVarSlice (slice
) { writeVarInt(slice
.length
); writeSlice(slice
) }
11194 var hashOutputs
= ZERO
11195 var hashPrevouts
= ZERO
11196 var hashSequence
= ZERO
11198 if (!(hashType
& Transaction
.SIGHASH_ANYONECANPAY
)) {
11199 tbuffer
= Buffer
.allocUnsafe(36 * this.ins
.length
)
11202 this.ins
.forEach(function (txIn
) {
11203 writeSlice(txIn
.hash
)
11204 writeUInt32(txIn
.index
)
11207 hashPrevouts
= bcrypto
.hash256(tbuffer
)
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
)
11216 this.ins
.forEach(function (txIn
) {
11217 writeUInt32(txIn
.sequence
)
11220 hashSequence
= bcrypto
.hash256(tbuffer
)
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
)
11229 tbuffer
= Buffer
.allocUnsafe(txOutsSize
)
11232 this.outs
.forEach(function (out
) {
11233 writeUInt64(out
.value
)
11234 writeVarSlice(out
.script
)
11237 hashOutputs
= bcrypto
.hash256(tbuffer
)
11238 } else if ((hashType
& 0x1f) === Transaction
.SIGHASH_SINGLE
&& inIndex
< this.outs
.length
) {
11239 var output
= this.outs
[inIndex
]
11241 tbuffer
= Buffer
.allocUnsafe(8 + varSliceSize(output
.script
))
11243 writeUInt64(output
.value
)
11244 writeVarSlice(output
.script
)
11246 hashOutputs
= bcrypto
.hash256(tbuffer
)
11249 tbuffer
= Buffer
.allocUnsafe(156 + varSliceSize(prevOutScript
))
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
)
11260 writeUInt32(input
.sequence
)
11261 writeSlice(hashOutputs
)
11262 writeUInt32(this.locktime
)
11263 writeUInt32(hashType
)
11264 return bcrypto
.hash256(tbuffer
)
11267 Transaction
.prototype.getHash = function () {
11268 return bcrypto
.hash256(this.__toBuffer(undefined, undefined, false))
11271 Transaction
.prototype.getId = function () {
11272 // transaction hash's are displayed in reverse order
11273 return this.getHash().reverse().toString('hex')
11276 Transaction
.prototype.toBuffer = function (buffer
, initialOffset
) {
11277 return this.__toBuffer(buffer
, initialOffset
, true)
11280 Transaction
.prototype.__toBuffer = function (buffer
, initialOffset
, __allowWitness
) {
11281 if (!buffer
) buffer
= Buffer
.allocUnsafe(this.__byteLength(__allowWitness
))
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
11293 function writeVarSlice (slice
) { writeVarInt(slice
.length
); writeSlice(slice
) }
11294 function writeVector (vector
) { writeVarInt(vector
.length
); vector
.forEach(writeVarSlice
) }
11296 writeInt32(this.version
)
11298 var hasWitnesses
= __allowWitness
&& this.hasWitnesses()
11300 if (hasWitnesses
) {
11301 writeUInt8(Transaction
.ADVANCED_TRANSACTION_MARKER
)
11302 writeUInt8(Transaction
.ADVANCED_TRANSACTION_FLAG
)
11305 writeVarInt(this.ins
.length
)
11307 this.ins
.forEach(function (txIn
) {
11308 writeSlice(txIn
.hash
)
11309 writeUInt32(txIn
.index
)
11310 writeVarSlice(txIn
.script
)
11311 writeUInt32(txIn
.sequence
)
11314 writeVarInt(this.outs
.length
)
11315 this.outs
.forEach(function (txOut
) {
11316 if (!txOut
.valueBuffer
) {
11317 writeUInt64(txOut
.value
)
11319 writeSlice(txOut
.valueBuffer
)
11322 writeVarSlice(txOut
.script
)
11325 if (hasWitnesses
) {
11326 this.ins
.forEach(function (input
) {
11327 writeVector(input
.witness
)
11331 writeUInt32(this.locktime
)
11333 // avoid slicing unless necessary
11334 if (initialOffset
!== undefined) return buffer
.slice(initialOffset
, offset
)
11338 Transaction
.prototype.toHex = function () {
11339 return this.toBuffer().toString('hex')
11342 Transaction
.prototype.setInputScript = function (index
, scriptSig
) {
11343 typeforce(types
.tuple(types
.Number
, types
.Buffer
), arguments
)
11345 this.ins
[index
].script
= scriptSig
11348 Transaction
.prototype.setWitness = function (index
, witness
) {
11349 typeforce(types
.tuple(types
.Number
, [types
.Buffer
]), arguments
)
11351 this.ins
[index
].witness
= witness
11354 module
.exports
= Transaction
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
){
11357 var Buffer
= require('safe-buffer').Buffer
11358 var baddress
= require('./address')
11359 var bcrypto
= require('./crypto')
11360 var bscript
= require('./script')
11361 var btemplates
= require('./templates')
11362 var networks
= require('./networks')
11363 var ops
= require('bitcoin-ops')
11364 var typeforce
= require('typeforce')
11365 var types
= require('./types')
11366 var scriptTypes
= btemplates
.types
11367 var SIGNABLE
= [btemplates
.types
.P2PKH
, btemplates
.types
.P2PK
, btemplates
.types
.MULTISIG
]
11368 var P2SH
= SIGNABLE
.concat([btemplates
.types
.P2WPKH
, btemplates
.types
.P2WSH
])
11370 var ECPair
= require('./ecpair')
11371 var ECSignature
= require('./ecsignature')
11372 var Transaction
= require('./transaction')
11374 function supportedType (type
) {
11375 return SIGNABLE
.indexOf(type
) !== -1
11378 function supportedP2SHType (type
) {
11379 return P2SH
.indexOf(type
) !== -1
11382 function extractChunks (type
, chunks
, script
) {
11384 var signatures
= []
11386 case scriptTypes
.P2PKH:
11387 // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')
11388 pubKeys
= chunks
.slice(1)
11389 signatures
= chunks
.slice(0, 1)
11392 case scriptTypes
.P2PK:
11393 pubKeys
[0] = script
? btemplates
.pubKey
.output
.decode(script
) : undefined
11394 signatures
= chunks
.slice(0, 1)
11397 case scriptTypes
.MULTISIG:
11399 var multisig
= btemplates
.multisig
.output
.decode(script
)
11400 pubKeys
= multisig
.pubKeys
11403 signatures
= chunks
.slice(1).map(function (chunk
) {
11404 return chunk
.length
=== 0 ? undefined : chunk
11411 signatures: signatures
11414 function expandInput (scriptSig
, witnessStack
) {
11415 if (scriptSig
.length
=== 0 && witnessStack
.length
=== 0) return {}
11423 var witnessScriptType
11424 var redeemScriptType
11425 var witness
= false
11431 var scriptSigChunks
= bscript
.decompile(scriptSig
)
11432 var sigType
= btemplates
.classifyInput(scriptSigChunks
, true)
11433 if (sigType
=== scriptTypes
.P2SH
) {
11435 redeemScript
= scriptSigChunks
[scriptSigChunks
.length
- 1]
11436 redeemScriptType
= btemplates
.classifyOutput(redeemScript
)
11437 prevOutScript
= btemplates
.scriptHash
.output
.encode(bcrypto
.hash160(redeemScript
))
11438 prevOutType
= scriptTypes
.P2SH
11439 script
= redeemScript
11442 var classifyWitness
= btemplates
.classifyWitness(witnessStack
, true)
11443 if (classifyWitness
=== scriptTypes
.P2WSH
) {
11444 witnessScript
= witnessStack
[witnessStack
.length
- 1]
11445 witnessScriptType
= btemplates
.classifyOutput(witnessScript
)
11448 if (scriptSig
.length
=== 0) {
11449 prevOutScript
= btemplates
.witnessScriptHash
.output
.encode(bcrypto
.sha256(witnessScript
))
11450 prevOutType
= scriptTypes
.P2WSH
11451 if (redeemScript
!== undefined) {
11452 throw new Error('Redeem script given when unnecessary')
11456 if (!redeemScript
) {
11457 throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty')
11459 witnessProgram
= btemplates
.witnessScriptHash
.output
.encode(bcrypto
.sha256(witnessScript
))
11460 if (!redeemScript
.equals(witnessProgram
)) {
11461 throw new Error('Redeem script didn\'t match witnessScript')
11465 if (!supportedType(btemplates
.classifyOutput(witnessScript
))) {
11466 throw new Error('unsupported witness script')
11469 script
= witnessScript
11470 scriptType
= witnessScriptType
11471 chunks
= witnessStack
.slice(0, -1)
11472 } else if (classifyWitness
=== scriptTypes
.P2WPKH
) {
11474 var key
= witnessStack
[witnessStack
.length
- 1]
11475 var keyHash
= bcrypto
.hash160(key
)
11476 if (scriptSig
.length
=== 0) {
11477 prevOutScript
= btemplates
.witnessPubKeyHash
.output
.encode(keyHash
)
11478 prevOutType
= scriptTypes
.P2WPKH
11479 if (typeof redeemScript
!== 'undefined') {
11480 throw new Error('Redeem script given when unnecessary')
11483 if (!redeemScript
) {
11484 throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty')
11486 witnessProgram
= btemplates
.witnessPubKeyHash
.output
.encode(keyHash
)
11487 if (!redeemScript
.equals(witnessProgram
)) {
11488 throw new Error('Redeem script did not have the right witness program')
11492 scriptType
= scriptTypes
.P2PKH
11493 chunks
= witnessStack
11494 } else if (redeemScript
) {
11495 if (!supportedP2SHType(redeemScriptType
)) {
11496 throw new Error('Bad redeemscript!')
11499 script
= redeemScript
11500 scriptType
= redeemScriptType
11501 chunks
= scriptSigChunks
.slice(0, -1)
11503 prevOutType
= scriptType
= btemplates
.classifyInput(scriptSig
)
11504 chunks
= scriptSigChunks
11507 var expanded
= extractChunks(scriptType
, chunks
, script
)
11510 pubKeys: expanded
.pubKeys
,
11511 signatures: expanded
.signatures
,
11512 prevOutScript: prevOutScript
,
11513 prevOutType: prevOutType
,
11514 signType: scriptType
,
11515 signScript: script
,
11516 witness: Boolean(witness
)
11520 result
.redeemScript
= redeemScript
11521 result
.redeemScriptType
= redeemScriptType
11525 result
.witnessScript
= witnessScript
11526 result
.witnessScriptType
= witnessScriptType
11532 // could be done in expandInput, but requires the original Transaction for hashForSignature
11533 function fixMultisigOrder (input
, transaction
, vin
) {
11534 if (input
.redeemScriptType
!== scriptTypes
.MULTISIG
|| !input
.redeemScript
) return
11535 if (input
.pubKeys
.length
=== input
.signatures
.length
) return
11537 var unmatched
= input
.signatures
.concat()
11539 input
.signatures
= input
.pubKeys
.map(function (pubKey
) {
11540 var keyPair
= ECPair
.fromPublicKeyBuffer(pubKey
)
11543 // check for a signature
11544 unmatched
.some(function (signature
, i
) {
11545 // skip if undefined || OP_0
11546 if (!signature
) return false
11548 // TODO: avoid O(n) hashForSignature
11549 var parsed
= ECSignature
.parseScriptSignature(signature
)
11550 var hash
= transaction
.hashForSignature(vin
, input
.redeemScript
, parsed
.hashType
)
11552 // skip if signature does not match pubKey
11553 if (!keyPair
.verify(hash
, parsed
.signature
)) return false
11555 // remove matched signature from unmatched
11556 unmatched
[i
] = undefined
11566 function expandOutput (script
, scriptType
, ourPubKey
) {
11567 typeforce(types
.Buffer
, script
)
11569 var scriptChunks
= bscript
.decompile(script
)
11571 scriptType
= btemplates
.classifyOutput(script
)
11576 switch (scriptType
) {
11577 // does our hash160(pubKey) match the output scripts?
11578 case scriptTypes
.P2PKH:
11579 if (!ourPubKey
) break
11581 var pkh1
= scriptChunks
[2]
11582 var pkh2
= bcrypto
.hash160(ourPubKey
)
11583 if (pkh1
.equals(pkh2
)) pubKeys
= [ourPubKey
]
11586 // does our hash160(pubKey) match the output scripts?
11587 case scriptTypes
.P2WPKH:
11588 if (!ourPubKey
) break
11590 var wpkh1
= scriptChunks
[1]
11591 var wpkh2
= bcrypto
.hash160(ourPubKey
)
11592 if (wpkh1
.equals(wpkh2
)) pubKeys
= [ourPubKey
]
11595 case scriptTypes
.P2PK:
11596 pubKeys
= scriptChunks
.slice(0, 1)
11599 case scriptTypes
.MULTISIG:
11600 pubKeys
= scriptChunks
.slice(1, -2)
11603 default: return { scriptType: scriptType
}
11608 scriptType: scriptType
,
11609 signatures: pubKeys
.map(function () { return undefined })
11613 function checkP2SHInput (input
, redeemScriptHash
) {
11614 if (input
.prevOutType
) {
11615 if (input
.prevOutType
!== scriptTypes
.P2SH
) throw new Error('PrevOutScript must be P2SH')
11617 var prevOutScriptScriptHash
= bscript
.decompile(input
.prevOutScript
)[1]
11618 if (!prevOutScriptScriptHash
.equals(redeemScriptHash
)) throw new Error('Inconsistent hash160(RedeemScript)')
11622 function checkP2WSHInput (input
, witnessScriptHash
) {
11623 if (input
.prevOutType
) {
11624 if (input
.prevOutType
!== scriptTypes
.P2WSH
) throw new Error('PrevOutScript must be P2WSH')
11626 var scriptHash
= bscript
.decompile(input
.prevOutScript
)[1]
11627 if (!scriptHash
.equals(witnessScriptHash
)) throw new Error('Inconsistent sha25(WitnessScript)')
11631 function prepareInput (input
, kpPubKey
, redeemScript
, witnessValue
, witnessScript
) {
11638 var redeemScriptHash
11640 var witness
= false
11643 var witnessScriptHash
11648 if (redeemScript
&& witnessScript
) {
11649 redeemScriptHash
= bcrypto
.hash160(redeemScript
)
11650 witnessScriptHash
= bcrypto
.sha256(witnessScript
)
11651 checkP2SHInput(input
, redeemScriptHash
)
11653 if (!redeemScript
.equals(btemplates
.witnessScriptHash
.output
.encode(witnessScriptHash
))) throw new Error('Witness script inconsistent with redeem script')
11655 expanded
= expandOutput(witnessScript
, undefined, kpPubKey
)
11656 if (!expanded
.pubKeys
) throw new Error('WitnessScript not supported "' + bscript
.toASM(redeemScript
) + '"')
11658 prevOutType
= btemplates
.types
.P2SH
11659 prevOutScript
= btemplates
.scriptHash
.output
.encode(redeemScriptHash
)
11660 p2sh
= witness
= p2wsh
= true
11661 p2shType
= btemplates
.types
.P2WSH
11662 signType
= witnessType
= expanded
.scriptType
11663 signScript
= witnessScript
11664 } else if (redeemScript
) {
11665 redeemScriptHash
= bcrypto
.hash160(redeemScript
)
11666 checkP2SHInput(input
, redeemScriptHash
)
11668 expanded
= expandOutput(redeemScript
, undefined, kpPubKey
)
11669 if (!expanded
.pubKeys
) throw new Error('RedeemScript not supported "' + bscript
.toASM(redeemScript
) + '"')
11671 prevOutType
= btemplates
.types
.P2SH
11672 prevOutScript
= btemplates
.scriptHash
.output
.encode(redeemScriptHash
)
11674 signType
= p2shType
= expanded
.scriptType
11675 signScript
= redeemScript
11676 witness
= signType
=== btemplates
.types
.P2WPKH
11677 } else if (witnessScript
) {
11678 witnessScriptHash
= bcrypto
.sha256(witnessScript
)
11679 checkP2WSHInput(input
, witnessScriptHash
)
11681 expanded
= expandOutput(witnessScript
, undefined, kpPubKey
)
11682 if (!expanded
.pubKeys
) throw new Error('WitnessScript not supported "' + bscript
.toASM(redeemScript
) + '"')
11684 prevOutType
= btemplates
.types
.P2WSH
11685 prevOutScript
= btemplates
.witnessScriptHash
.output
.encode(witnessScriptHash
)
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')
11696 prevOutType
= input
.prevOutType
11697 prevOutScript
= input
.prevOutScript
11698 expanded
= expandOutput(input
.prevOutScript
, input
.prevOutType
, kpPubKey
)
11699 if (!expanded
.pubKeys
) return
11701 witness
= (input
.prevOutType
=== scriptTypes
.P2WPKH
)
11702 signType
= prevOutType
11703 signScript
= prevOutScript
11705 prevOutScript
= btemplates
.pubKeyHash
.output
.encode(bcrypto
.hash160(kpPubKey
))
11706 expanded
= expandOutput(prevOutScript
, scriptTypes
.P2PKH
, kpPubKey
)
11708 prevOutType
= scriptTypes
.P2PKH
11710 signType
= prevOutType
11711 signScript
= prevOutScript
11714 if (signType
=== scriptTypes
.P2WPKH
) {
11715 signScript
= btemplates
.pubKeyHash
.output
.encode(btemplates
.witnessPubKeyHash
.output
.decode(signScript
))
11719 input
.redeemScript
= redeemScript
11720 input
.redeemScriptType
= p2shType
11724 input
.witnessScript
= witnessScript
11725 input
.witnessScriptType
= witnessType
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
11737 function buildStack (type
, signatures
, pubKeys
, allowIncomplete
) {
11738 if (type
=== scriptTypes
.P2PKH
) {
11739 if (signatures
.length
=== 1 && Buffer
.isBuffer(signatures
[0]) && pubKeys
.length
=== 1) return btemplates
.pubKeyHash
.input
.encodeStack(signatures
[0], pubKeys
[0])
11740 } else if (type
=== scriptTypes
.P2PK
) {
11741 if (signatures
.length
=== 1 && Buffer
.isBuffer(signatures
[0])) return btemplates
.pubKey
.input
.encodeStack(signatures
[0])
11742 } else if (type
=== scriptTypes
.MULTISIG
) {
11743 if (signatures
.length
> 0) {
11744 signatures
= signatures
.map(function (signature
) {
11745 return signature
|| ops
.OP_0
11747 if (!allowIncomplete
) {
11748 // remove blank signatures
11749 signatures
= signatures
.filter(function (x
) { return x
!== ops
.OP_0
})
11752 return btemplates
.multisig
.input
.encodeStack(signatures
)
11755 throw new Error('Not yet supported')
11758 if (!allowIncomplete
) throw new Error('Not enough signatures provided')
11762 function buildInput (input
, allowIncomplete
) {
11763 var scriptType
= input
.prevOutType
11767 if (supportedType(scriptType
)) {
11768 sig
= buildStack(scriptType
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
11772 if (scriptType
=== btemplates
.types
.P2SH
) {
11773 // We can remove this error later when we have a guarantee prepareInput
11774 // rejects unsignable scripts - it MUST be signable at this point.
11775 if (!allowIncomplete
&& !supportedP2SHType(input
.redeemScriptType
)) {
11776 throw new Error('Impossible to sign this type')
11779 if (supportedType(input
.redeemScriptType
)) {
11780 sig
= buildStack(input
.redeemScriptType
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
11783 // If it wasn't SIGNABLE, it's witness, defer to that
11784 if (input
.redeemScriptType
) {
11786 scriptType
= input
.redeemScriptType
11790 switch (scriptType
) {
11791 // P2WPKH is a special case of P2PKH
11792 case btemplates
.types
.P2WPKH:
11793 witness
= buildStack(btemplates
.types
.P2PKH
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
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')
11802 if (supportedType(input
.witnessScriptType
)) {
11803 witness
= buildStack(input
.witnessScriptType
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
11804 witness
.push(input
.witnessScript
)
11805 scriptType
= input
.witnessScriptType
11811 // append redeemScript if necessary
11813 sig
.push(input
.redeemScript
)
11818 script: bscript
.compile(sig
),
11823 function TransactionBuilder (network
, maximumFeeRate
) {
11824 this.prevTxMap
= {}
11825 this.network
= network
|| networks
.bitcoin
11827 // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
11828 this.maximumFeeRate
= maximumFeeRate
|| 2500
11831 this.tx
= new Transaction()
11834 TransactionBuilder
.prototype.setLockTime = function (locktime
) {
11835 typeforce(types
.UInt32
, locktime
)
11837 // if any signatures exist, throw
11838 if (this.inputs
.some(function (input
) {
11839 if (!input
.signatures
) return false
11841 return input
.signatures
.some(function (s
) { return s
})
11843 throw new Error('No, this would invalidate signatures')
11846 this.tx
.locktime
= locktime
11849 TransactionBuilder
.prototype.setVersion = function (version
) {
11850 typeforce(types
.UInt32
, version
)
11852 // XXX: this might eventually become more complex depending on what the versions represent
11853 this.tx
.version
= version
11856 TransactionBuilder
.fromTransaction = function (transaction
, network
) {
11857 var txb
= new TransactionBuilder(network
)
11859 // Copy transaction fields
11860 txb
.setVersion(transaction
.version
)
11861 txb
.setLockTime(transaction
.locktime
)
11863 // Copy outputs (done first to avoid signature invalidation)
11864 transaction
.outs
.forEach(function (txOut
) {
11865 txb
.addOutput(txOut
.script
, txOut
.value
)
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
11877 // fix some things not possible through the public API
11878 txb
.inputs
.forEach(function (input
, i
) {
11879 fixMultisigOrder(input
, transaction
, i
)
11885 TransactionBuilder
.prototype.addInput = function (txHash
, vout
, sequence
, prevOutScript
) {
11886 if (!this.__canModifyInputs()) {
11887 throw new Error('No, this would invalidate signatures')
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()
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
11903 txHash
= txHash
.getHash()
11906 return this.__addInputUnsafe(txHash
, vout
, {
11907 sequence: sequence
,
11908 prevOutScript: prevOutScript
,
11913 TransactionBuilder
.prototype.__addInputUnsafe = function (txHash
, vout
, options
) {
11914 if (Transaction
.isCoinbaseHash(txHash
)) {
11915 throw new Error('coinbase inputs not supported')
11918 var prevTxOut
= txHash
.toString('hex') + ':' + vout
11919 if (this.prevTxMap
[prevTxOut
] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut
)
11923 // derive what we can from the scriptSig
11924 if (options
.script
!== undefined) {
11925 input
= expandInput(options
.script
, options
.witness
|| [])
11928 // if an input value was given, retain it
11929 if (options
.value
!== undefined) {
11930 input
.value
= options
.value
11933 // derive what we can from the previous transactions output script
11934 if (!input
.prevOutScript
&& options
.prevOutScript
) {
11937 if (!input
.pubKeys
&& !input
.signatures
) {
11938 var expanded
= expandOutput(options
.prevOutScript
)
11940 if (expanded
.pubKeys
) {
11941 input
.pubKeys
= expanded
.pubKeys
11942 input
.signatures
= expanded
.signatures
11945 prevOutType
= expanded
.scriptType
11948 input
.prevOutScript
= options
.prevOutScript
11949 input
.prevOutType
= prevOutType
|| btemplates
.classifyOutput(options
.prevOutScript
)
11952 var vin
= this.tx
.addInput(txHash
, vout
, options
.sequence
, options
.scriptSig
)
11953 this.inputs
[vin
] = input
11954 this.prevTxMap
[prevTxOut
] = vin
11958 TransactionBuilder
.prototype.addOutput = function (scriptPubKey
, value
) {
11959 if (!this.__canModifyOutputs()) {
11960 throw new Error('No, this would invalidate signatures')
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
)
11968 return this.tx
.addOutput(scriptPubKey
, value
)
11971 TransactionBuilder
.prototype.build = function () {
11972 return this.__build(false)
11974 TransactionBuilder
.prototype.buildIncomplete = function () {
11975 return this.__build(true)
11978 TransactionBuilder
.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')
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
)
11991 // skip if no result
11992 if (!allowIncomplete
) {
11993 if (!supportedType(result
.type
) && result
.type
!== btemplates
.types
.P2WPKH
) {
11994 throw new Error(result
.type
+ ' not supported')
11998 tx
.setInputScript(i
, result
.script
)
11999 tx
.setWitness(i
, result
.witness
)
12002 if (!allowIncomplete
) {
12003 // do not rely on this, its merely a last resort
12004 if (this.__overMaximumFees(tx
.virtualSize())) {
12005 throw new Error('Transaction has absurd fees')
12012 function 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 &&
12020 input
.witness
=== false ||
12021 (input
.witness
=== true && input
.value
!== undefined)
12025 TransactionBuilder
.prototype.sign = function (vin
, keyPair
, redeemScript
, hashType
, witnessValue
, witnessScript
) {
12026 // TODO: remove keyPair.network matching in 4.0.0
12027 if (keyPair
.network
&& keyPair
.network
!== this.network
) throw new TypeError('Inconsistent network')
12028 if (!this.inputs
[vin
]) throw new Error('No input at index: ' + vin
)
12029 hashType
= hashType
|| Transaction
.SIGHASH_ALL
12031 var input
= this.inputs
[vin
]
12033 // if redeemScript was previously provided, enforce consistency
12034 if (input
.redeemScript
!== undefined &&
12036 !input
.redeemScript
.equals(redeemScript
)) {
12037 throw new Error('Inconsistent redeemScript')
12040 var kpPubKey
= keyPair
.publicKey
|| keyPair
.getPublicKeyBuffer()
12041 if (!canSign(input
)) {
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
12048 if (!canSign(input
)) prepareInput(input
, kpPubKey
, redeemScript
, witnessValue
, witnessScript
)
12049 if (!canSign(input
)) throw Error(input
.prevOutType
+ ' not supported')
12054 if (input
.witness
) {
12055 signatureHash
= this.tx
.hashForWitnessV0(vin
, input
.signScript
, input
.value
, hashType
)
12057 signatureHash
= this.tx
.hashForSignature(vin
, input
.signScript
, hashType
)
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')
12064 if (kpPubKey
.length
!== 33 &&
12065 input
.signType
=== scriptTypes
.P2WPKH
) throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH')
12067 var signature
= keyPair
.sign(signatureHash
)
12068 if (Buffer
.isBuffer(signature
)) signature
= ECSignature
.fromRSBuffer(signature
)
12070 input
.signatures
[i
] = signature
.toScriptSignature(hashType
)
12074 if (!signed
) throw new Error('Key pair cannot sign for this input')
12077 function signatureHashType (buffer
) {
12078 return buffer
.readUInt8(buffer
.length
- 1)
12081 TransactionBuilder
.prototype.__canModifyInputs = function () {
12082 return this.inputs
.every(function (input
) {
12084 if (input
.signatures
=== undefined) return true
12086 return input
.signatures
.every(function (signature
) {
12087 if (!signature
) return true
12088 var hashType
= signatureHashType(signature
)
12090 // if SIGHASH_ANYONECANPAY is set, signatures would not
12091 // be invalidated by more inputs
12092 return hashType
& Transaction
.SIGHASH_ANYONECANPAY
12097 TransactionBuilder
.prototype.__canModifyOutputs = function () {
12098 var nInputs
= this.tx
.ins
.length
12099 var nOutputs
= this.tx
.outs
.length
12101 return this.inputs
.every(function (input
) {
12102 if (input
.signatures
=== undefined) return true
12104 return input
.signatures
.every(function (signature
) {
12105 if (!signature
) return true
12106 var hashType
= signatureHashType(signature
)
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
12114 return nInputs
<= nOutputs
12120 TransactionBuilder
.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)
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
12130 return feeRate
> this.maximumFeeRate
12133 module
.exports
= TransactionBuilder
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
){
12136 var typeforce
= require('typeforce')
12138 var UINT31_MAX
= Math
.pow(2, 31) - 1
12139 function UInt31 (value
) {
12140 return typeforce
.UInt32(value
) && value
<= UINT31_MAX
12143 function BIP32Path (value
) {
12144 return typeforce
.String(value
) && value
.match(/^(m\/)?(\d+'?\/)*\d+'?$/)
12146 BIP32Path
.toJSON = function () { return 'BIP32 derivation path' }
12148 var SATOSHI_MAX
= 21 * 1e14
12149 function Satoshi (value
) {
12150 return typeforce
.UInt53(value
) && value
<= SATOSHI_MAX
12153 // external dependent types
12154 var BigInt
= typeforce
.quacksLike('BigInteger')
12155 var ECPoint
= typeforce
.quacksLike('Point')
12157 // exposed, external API
12158 var ECSignature
= typeforce
.compile({ r: BigInt
, s: BigInt
})
12159 var Network
= typeforce
.compile({
12160 messagePrefix: typeforce
.oneOf(typeforce
.Buffer
, typeforce
.String
),
12162 public: typeforce
.UInt32
,
12163 private: typeforce
.UInt32
12165 pubKeyHash: typeforce
.UInt8
,
12166 scriptHash: typeforce
.UInt8
,
12167 wif: typeforce
.UInt8
12170 // extend typeforce types with ours
12173 BIP32Path: BIP32Path
,
12174 Buffer256bit: typeforce
.BufferN(32),
12176 ECSignature: ECSignature
,
12177 Hash160bit: typeforce
.BufferN(20),
12178 Hash256bit: typeforce
.BufferN(32),
12184 for (var typeName
in typeforce
) {
12185 types
[typeName
] = typeforce
[typeName
]
12188 module
.exports
= types
12190 },{"typeforce":112}],81:[function(require
,module
,exports
){
12191 var basex
= require('base-x')
12192 var ALPHABET
= '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
12194 module
.exports
= basex(ALPHABET
)
12196 },{"base-x":35}],82:[function(require
,module
,exports
){
12199 var base58
= require('bs58')
12200 var Buffer
= require('safe-buffer').Buffer
12202 module
.exports = function (checksumFn
) {
12203 // Encode a buffer as a base58-check encoded string
12204 function encode (payload
) {
12205 var checksum
= checksumFn(payload
)
12207 return base58
.encode(Buffer
.concat([
12210 ], payload
.length
+ 4))
12213 function decodeRaw (buffer
) {
12214 var payload
= buffer
.slice(0, -4)
12215 var checksum
= buffer
.slice(-4)
12216 var newChecksum
= checksumFn(payload
)
12218 if (checksum
[0] ^ newChecksum
[0] |
12219 checksum
[1] ^ newChecksum
[1] |
12220 checksum
[2] ^ newChecksum
[2] |
12221 checksum
[3] ^ newChecksum
[3]) return
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
12231 return decodeRaw(buffer
)
12234 function decode (string
) {
12235 var buffer
= base58
.decode(string
)
12236 var payload
= decodeRaw(buffer
, checksumFn
)
12237 if (!payload
) throw new Error('Invalid checksum')
12244 decodeUnsafe: decodeUnsafe
12248 },{"bs58":81,"safe-buffer":101}],83:[function(require
,module
,exports
){
12251 var createHash
= require('create-hash')
12252 var bs58checkBase
= require('./base')
12254 // SHA256(SHA256(buffer))
12255 function sha256x2 (buffer
) {
12256 var tmp
= createHash('sha256').update(buffer
).digest()
12257 return createHash('sha256').update(tmp
).digest()
12260 module
.exports
= bs58checkBase(sha256x2
)
12262 },{"./base":82,"create-hash":85}],84:[function(require
,module
,exports
){
12263 var Buffer
= require('safe-buffer').Buffer
12264 var Transform
= require('stream').Transform
12265 var StringDecoder
= require('string_decoder').StringDecoder
12266 var inherits
= require('inherits')
12268 function CipherBase (hashMode
) {
12269 Transform
.call(this)
12270 this.hashMode
= typeof hashMode
=== 'string'
12271 if (this.hashMode
) {
12272 this[hashMode
] = this._finalOrDigest
12274 this.final
= this._finalOrDigest
12277 this.__final
= this._final
12280 this._decoder
= null
12281 this._encoding
= null
12283 inherits(CipherBase
, Transform
)
12285 CipherBase
.prototype.update = function (data
, inputEnc
, outputEnc
) {
12286 if (typeof data
=== 'string') {
12287 data
= Buffer
.from(data
, inputEnc
)
12290 var outData
= this._update(data
)
12291 if (this.hashMode
) return this
12294 outData
= this._toString(outData
, outputEnc
)
12300 CipherBase
.prototype.setAutoPadding = function () {}
12301 CipherBase
.prototype.getAuthTag = function () {
12302 throw new Error('trying to get auth tag in unsupported state')
12305 CipherBase
.prototype.setAuthTag = function () {
12306 throw new Error('trying to set auth tag in unsupported state')
12309 CipherBase
.prototype.setAAD = function () {
12310 throw new Error('trying to set aad in unsupported state')
12313 CipherBase
.prototype._transform = function (data
, _
, next
) {
12316 if (this.hashMode
) {
12319 this.push(this._update(data
))
12327 CipherBase
.prototype._flush = function (done
) {
12330 this.push(this.__final())
12337 CipherBase
.prototype._finalOrDigest = function (outputEnc
) {
12338 var outData
= this.__final() || Buffer
.alloc(0)
12340 outData
= this._toString(outData
, outputEnc
, true)
12345 CipherBase
.prototype._toString = function (value
, enc
, fin
) {
12346 if (!this._decoder
) {
12347 this._decoder
= new StringDecoder(enc
)
12348 this._encoding
= enc
12351 if (this._encoding
!== enc
) throw new Error('can\'t switch encodings')
12353 var out
= this._decoder
.write(value
)
12355 out
+= this._decoder
.end()
12361 module
.exports
= CipherBase
12363 },{"inherits":96,"safe-buffer":101,"stream":28,"string_decoder":29}],85:[function(require
,module
,exports
){
12364 (function (Buffer
){
12366 var inherits
= require('inherits')
12367 var md5
= require('./md5')
12368 var RIPEMD160
= require('ripemd160')
12369 var sha
= require('sha.js')
12371 var Base
= require('cipher-base')
12373 function HashNoConstructor (hash
) {
12374 Base
.call(this, 'digest')
12380 inherits(HashNoConstructor
, Base
)
12382 HashNoConstructor
.prototype._update = function (data
) {
12383 this.buffers
.push(data
)
12386 HashNoConstructor
.prototype._final = function () {
12387 var buf
= Buffer
.concat(this.buffers
)
12388 var r
= this._hash(buf
)
12389 this.buffers
= null
12394 function Hash (hash
) {
12395 Base
.call(this, 'digest')
12400 inherits(Hash
, Base
)
12402 Hash
.prototype._update = function (data
) {
12403 this._hash
.update(data
)
12406 Hash
.prototype._final = function () {
12407 return this._hash
.digest()
12410 module
.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())
12415 return new Hash(sha(alg
))
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
){
12423 var zeroBuffer
= new Buffer(intSize
)
12429 function toArray (buf
) {
12430 if ((buf
.length
% intSize
) !== 0) {
12431 var len
= buf
.length
+ (intSize
- (buf
.length
% intSize
))
12432 buf
= Buffer
.concat([buf
, zeroBuffer
], len
)
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
)
12443 module
.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)
12452 }).call(this,require("buffer").Buffer
)
12453 },{"buffer":5}],87:[function(require
,module
,exports
){
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.
12464 var makeHash
= require('./make-hash')
12467 * Calculate the MD5 of an array of little-endian words, and a bit length
12469 function core_md5 (x
, len
) {
12470 /* append padding */
12471 x
[len
>> 5] |= 0x80 << ((len
) % 32)
12472 x
[(((len
+ 64) >>> 9) << 4) + 14] = len
12476 var c
= -1732584194
12479 for (var i
= 0; i
< x
.length
; i
+= 16) {
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)
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)
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)
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)
12553 a
= safe_add(a
, olda
)
12554 b
= safe_add(b
, oldb
)
12555 c
= safe_add(c
, oldc
)
12556 d
= safe_add(d
, oldd
)
12559 return [a
, b
, c
, d
]
12563 * These functions implement the four basic operations the algorithm uses.
12565 function 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
)
12569 function md5_ff (a
, b
, c
, d
, x
, s
, t
) {
12570 return md5_cmn((b
& c
) | ((~b
) & d
), a
, b
, x
, s
, t
)
12573 function md5_gg (a
, b
, c
, d
, x
, s
, t
) {
12574 return md5_cmn((b
& d
) | (c
& (~d
)), a
, b
, x
, s
, t
)
12577 function md5_hh (a
, b
, c
, d
, x
, s
, t
) {
12578 return md5_cmn(b
^ c
^ d
, a
, b
, x
, s
, t
)
12581 function md5_ii (a
, b
, c
, d
, x
, s
, t
) {
12582 return md5_cmn(c
^ (b
| (~d
)), a
, b
, x
, s
, t
)
12586 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
12587 * to work around bugs in some JS interpreters.
12589 function 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)
12596 * Bitwise rotate a 32-bit number to the left.
12598 function bit_rol (num
, cnt
) {
12599 return (num
<< cnt
) | (num
>>> (32 - cnt
))
12602 module
.exports
= function md5 (buf
) {
12603 return makeHash(buf
, core_md5
)
12606 },{"./make-hash":86}],88:[function(require
,module
,exports
){
12608 var inherits
= require('inherits')
12609 var Legacy
= require('./legacy')
12610 var Base
= require('cipher-base')
12611 var Buffer
= require('safe-buffer').Buffer
12612 var md5
= require('create-hash/md5')
12613 var RIPEMD160
= require('ripemd160')
12615 var sha
= require('sha.js')
12617 var ZEROS
= Buffer
.alloc(128)
12619 function Hmac (alg
, key
) {
12620 Base
.call(this, 'digest')
12621 if (typeof key
=== 'string') {
12622 key
= Buffer
.from(key
)
12625 var blocksize
= (alg
=== 'sha512' || alg
=== 'sha384') ? 128 : 64
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
)
12636 var ipad
= this._ipad
= Buffer
.allocUnsafe(blocksize
)
12637 var opad
= this._opad
= Buffer
.allocUnsafe(blocksize
)
12639 for (var i
= 0; i
< blocksize
; i
++) {
12640 ipad
[i
] = key
[i
] ^ 0x36
12641 opad
[i
] = key
[i
] ^ 0x5C
12643 this._hash
= alg
=== 'rmd160' ? new RIPEMD160() : sha(alg
)
12644 this._hash
.update(ipad
)
12647 inherits(Hmac
, Base
)
12649 Hmac
.prototype._update = function (data
) {
12650 this._hash
.update(data
)
12653 Hmac
.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()
12659 module
.exports
= function createHmac (alg
, key
) {
12660 alg
= alg
.toLowerCase()
12661 if (alg
=== 'rmd160' || alg
=== 'ripemd160') {
12662 return new Hmac('rmd160', key
)
12664 if (alg
=== 'md5') {
12665 return new Legacy(md5
, key
)
12667 return new Hmac(alg
, key
)
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
){
12672 var inherits
= require('inherits')
12673 var Buffer
= require('safe-buffer').Buffer
12675 var Base
= require('cipher-base')
12677 var ZEROS
= Buffer
.alloc(128)
12680 function Hmac (alg
, key
) {
12681 Base
.call(this, 'digest')
12682 if (typeof key
=== 'string') {
12683 key
= Buffer
.from(key
)
12689 if (key
.length
> blocksize
) {
12691 } else if (key
.length
< blocksize
) {
12692 key
= Buffer
.concat([key
, ZEROS
], blocksize
)
12695 var ipad
= this._ipad
= Buffer
.allocUnsafe(blocksize
)
12696 var opad
= this._opad
= Buffer
.allocUnsafe(blocksize
)
12698 for (var i
= 0; i
< blocksize
; i
++) {
12699 ipad
[i
] = key
[i
] ^ 0x36
12700 opad
[i
] = key
[i
] ^ 0x5C
12703 this._hash
= [ipad
]
12706 inherits(Hmac
, Base
)
12708 Hmac
.prototype._update = function (data
) {
12709 this._hash
.push(data
)
12712 Hmac
.prototype._final = function () {
12713 var h
= this._alg(Buffer
.concat(this._hash
))
12714 return this._alg(Buffer
.concat([this._opad
, h
]))
12716 module
.exports
= Hmac
12718 },{"cipher-base":84,"inherits":96,"safe-buffer":101}],90:[function(require
,module
,exports
){
12719 var assert
= require('assert')
12720 var BigInteger
= require('bigi')
12722 var Point
= require('./point')
12724 function Curve (p
, a
, b
, Gx
, Gy
, n
, h
) {
12728 this.G
= Point
.fromAffine(this, Gx
, Gy
)
12732 this.infinity
= new Point(this, null, null, BigInteger
.ZERO
)
12735 this.pOverFour
= p
.add(BigInteger
.ONE
).shiftRight(2)
12737 // determine size of p in bytes
12738 this.pLength
= Math
.floor((this.p
.bitLength() + 7) / 8)
12741 Curve
.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
12746 if (beta
.isEven() ^ !isOdd
) {
12747 y
= this.p
.subtract(y
) // -y % p
12750 return Point
.fromAffine(this, x
, y
)
12753 Curve
.prototype.isInfinity = function (Q
) {
12754 if (Q
=== this.infinity
) return true
12756 return Q
.z
.signum() === 0 && Q
.y
.signum() !== 0
12759 Curve
.prototype.isOnCurve = function (Q
) {
12760 if (this.isInfinity(Q
)) return true
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
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
)
12779 * Validate an elliptic curve point.
12781 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
12783 Curve
.prototype.validate = function (Q
) {
12785 assert(!this.isInfinity(Q
), 'Point is at infinity')
12786 assert(this.isOnCurve(Q
), 'Point is not on the curve')
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')
12795 module
.exports
= Curve
12797 },{"./point":94,"assert":1,"bigi":39}],91:[function(require
,module
,exports
){
12800 "p": "fffffffdffffffffffffffffffffffff",
12801 "a": "fffffffdfffffffffffffffffffffffc",
12802 "b": "e87579c11079f43dd824993c2cee5ed3",
12803 "n": "fffffffe0000000075a30d1b9038a115",
12805 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
12806 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
12809 "p": "fffffffffffffffffffffffffffffffeffffac73",
12812 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
12814 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
12815 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
12818 "p": "ffffffffffffffffffffffffffffffff7fffffff",
12819 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
12820 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
12821 "n": "0100000000000000000001f4c8f927aed3ca752257",
12823 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
12824 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
12827 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
12830 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
12832 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
12833 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
12836 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
12837 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
12838 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
12839 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
12841 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
12842 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
12845 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
12848 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
12850 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
12851 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
12854 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
12855 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
12856 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
12857 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
12859 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
12860 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
12864 },{}],92:[function(require
,module
,exports
){
12865 var Point
= require('./point')
12866 var Curve
= require('./curve')
12868 var getCurveByName
= require('./names')
12873 getCurveByName: getCurveByName
12876 },{"./curve":90,"./names":93,"./point":94}],93:[function(require
,module
,exports
){
12877 var BigInteger
= require('bigi')
12879 var curves
= require('./curves.json')
12880 var Curve
= require('./curve')
12882 function getCurveByName (name
) {
12883 var curve
= curves
[name
]
12884 if (!curve
) return null
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)
12894 return new Curve(p
, a
, b
, Gx
, Gy
, n
, h
)
12897 module
.exports
= getCurveByName
12899 },{"./curve":90,"./curves.json":91,"bigi":39}],94:[function(require
,module
,exports
){
12900 var assert
= require('assert')
12901 var Buffer
= require('safe-buffer').Buffer
12902 var BigInteger
= require('bigi')
12904 var THREE
= BigInteger
.valueOf(3)
12906 function Point (curve
, x
, y
, z
) {
12907 assert
.notStrictEqual(z
, undefined, 'Missing Z coordinate')
12915 this.compressed
= true
12918 Object
.defineProperty(Point
.prototype, 'zInv', {
12920 if (this._zInv
=== null) {
12921 this._zInv
= this.z
.modInverse(this.curve
.p
)
12928 Object
.defineProperty(Point
.prototype, 'affineX', {
12930 return this.x
.multiply(this.zInv
).mod(this.curve
.p
)
12934 Object
.defineProperty(Point
.prototype, 'affineY', {
12936 return this.y
.multiply(this.zInv
).mod(this.curve
.p
)
12940 Point
.fromAffine = function (curve
, x
, y
) {
12941 return new Point(curve
, x
, y
, BigInteger
.ONE
)
12944 Point
.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)
12949 // u = Y2 * Z1 - Y1 * Z2
12950 var u
= other
.y
.multiply(this.z
).subtract(this.y
.multiply(other
.z
)).mod(this.curve
.p
)
12952 if (u
.signum() !== 0) return false
12954 // v = X2 * Z1 - X1 * Z2
12955 var v
= other
.x
.multiply(this.z
).subtract(this.x
.multiply(other
.z
)).mod(this.curve
.p
)
12957 return v
.signum() === 0
12960 Point
.prototype.negate = function () {
12961 var y
= this.curve
.p
.subtract(this.y
)
12963 return new Point(this.curve
, this.x
, y
, this.z
)
12966 Point
.prototype.add = function (b
) {
12967 if (this.curve
.isInfinity(this)) return b
12968 if (this.curve
.isInfinity(b
)) return this
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
)
12980 if (v
.signum() === 0) {
12981 if (u
.signum() === 0) {
12982 return this.twice() // this == b, so double
12985 return this.curve
.infinity
// this = -b, so infinity
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
)
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
)
13000 return new Point(this.curve
, x3
, y3
, z3
)
13003 Point
.prototype.twice = function () {
13004 if (this.curve
.isInfinity(this)) return this
13005 if (this.y
.signum() === 0) return this.curve
.infinity
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
13014 // w = 3 * x1^2 + a * z1^2
13015 var w
= x1
.square().multiply(THREE
)
13017 if (a
.signum() !== 0) {
13018 w
= w
.add(this.z
.square().multiply(a
))
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
)
13029 return new Point(this.curve
, x3
, y3
, z3
)
13032 // Simple NAF (Non-Adjacent Form) multiplication algorithm
13033 // TODO: modularize the multiplication algorithm
13034 Point
.prototype.multiply = function (k
) {
13035 if (this.curve
.isInfinity(this)) return this
13036 if (k
.signum() === 0) return this.curve
.infinity
13039 var h
= e
.multiply(THREE
)
13041 var neg
= this.negate()
13044 for (var i
= h
.bitLength() - 2; i
> 0; --i
) {
13045 var hBit
= h
.testBit(i
)
13046 var eBit
= e
.testBit(i
)
13050 if (hBit
!== eBit
) {
13051 R
= R
.add(hBit
? this : neg
)
13058 // Compute this*j + x*k (simultaneous multiplication)
13059 Point
.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
)
13065 var jBit
= j
.testBit(i
)
13066 var kBit
= k
.testBit(i
)
13085 Point
.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'
13089 var x
= this.affineX
13090 var y
= this.affineY
13091 var byteLength
= this.curve
.pLength
13096 buffer
= Buffer
.allocUnsafe(1 + byteLength
)
13097 buffer
.writeUInt8(y
.isEven() ? 0x02 : 0x03, 0)
13101 buffer
= Buffer
.allocUnsafe(1 + byteLength
+ byteLength
)
13102 buffer
.writeUInt8(0x04, 0)
13104 y
.toBuffer(byteLength
).copy(buffer
, 1 + byteLength
)
13107 x
.toBuffer(byteLength
).copy(buffer
, 1)
13112 Point
.decodeFrom = function (curve
, buffer
) {
13113 var type
= buffer
.readUInt8(0)
13114 var compressed
= (type
!== 4)
13116 var byteLength
= Math
.floor((curve
.p
.bitLength() + 7) / 8)
13117 var x
= BigInteger
.fromBuffer(buffer
.slice(1, 1 + byteLength
))
13121 assert
.equal(buffer
.length
, byteLength
+ 1, 'Invalid sequence length')
13122 assert(type
=== 0x02 || type
=== 0x03, 'Invalid sequence tag')
13124 var isOdd
= (type
=== 0x03)
13125 Q
= curve
.pointFromX(isOdd
, x
)
13127 assert
.equal(buffer
.length
, 1 + byteLength
+ byteLength
, 'Invalid sequence length')
13129 var y
= BigInteger
.fromBuffer(buffer
.slice(1 + byteLength
))
13130 Q
= Point
.fromAffine(curve
, x
, y
)
13133 Q
.compressed
= compressed
13137 Point
.prototype.toString = function () {
13138 if (this.curve
.isInfinity(this)) return '(INFINITY)'
13140 return '(' + this.affineX
.toString() + ',' + this.affineY
.toString() + ')'
13143 module
.exports
= Point
13145 },{"assert":1,"bigi":39,"safe-buffer":101}],95:[function(require
,module
,exports
){
13146 (function (Buffer
){
13148 var Transform
= require('stream').Transform
13149 var inherits
= require('inherits')
13151 function HashBase (blockSize
) {
13152 Transform
.call(this)
13154 this._block
= new Buffer(blockSize
)
13155 this._blockSize
= blockSize
13156 this._blockOffset
= 0
13157 this._length
= [0, 0, 0, 0]
13159 this._finalized
= false
13162 inherits(HashBase
, Transform
)
13164 HashBase
.prototype._transform = function (chunk
, encoding
, callback
) {
13167 if (encoding
!== 'buffer') chunk
= new Buffer(chunk
, encoding
)
13176 HashBase
.prototype._flush = function (callback
) {
13179 this.push(this._digest())
13187 HashBase
.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')
13193 var block
= this._block
13195 while (this._blockOffset
+ data
.length
- offset
>= this._blockSize
) {
13196 for (var i
= this._blockOffset
; i
< this._blockSize
;) block
[i
++] = data
[offset
++]
13198 this._blockOffset
= 0
13200 while (offset
< data
.length
) block
[this._blockOffset
++] = data
[offset
++]
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
13212 HashBase
.prototype._update = function (data
) {
13213 throw new Error('_update is not implemented')
13216 HashBase
.prototype.digest = function (encoding
) {
13217 if (this._finalized
) throw new Error('Digest already called')
13218 this._finalized
= true
13220 var digest
= this._digest()
13221 if (encoding
!== undefined) digest
= digest
.toString(encoding
)
13225 HashBase
.prototype._digest = function () {
13226 throw new Error('_digest is not implemented')
13229 module
.exports
= HashBase
13231 }).call(this,require("buffer").Buffer
)
13232 },{"buffer":5,"inherits":96,"stream":28}],96:[function(require
,module
,exports
){
13233 arguments
[4][9][0].apply(exports
,arguments
)
13234 },{"dup":9}],97:[function(require
,module
,exports
){
13235 (function (Buffer
){
13236 // constant-space merkle root calculation algorithm
13237 module
.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')
13241 var length
= values
.length
13242 var results
= values
.concat()
13244 while (length
> 1) {
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
])
13252 results
[j
] = digestFn(data
)
13261 }).call(this,require("buffer").Buffer
)
13262 },{"buffer":5}],98:[function(require
,module
,exports
){
13263 var OPS
= require('bitcoin-ops')
13265 function encodingLength (i
) {
13266 return i
< OPS
.OP_PUSHDATA1
? 1
13272 function encode (buffer
, number
, offset
) {
13273 var size
= encodingLength(number
)
13277 buffer
.writeUInt8(number
, offset
)
13280 } else if (size
=== 2) {
13281 buffer
.writeUInt8(OPS
.OP_PUSHDATA1
, offset
)
13282 buffer
.writeUInt8(number
, offset
+ 1)
13285 } else if (size
=== 3) {
13286 buffer
.writeUInt8(OPS
.OP_PUSHDATA2
, offset
)
13287 buffer
.writeUInt16LE(number
, offset
+ 1)
13291 buffer
.writeUInt8(OPS
.OP_PUSHDATA4
, offset
)
13292 buffer
.writeUInt32LE(number
, offset
+ 1)
13298 function decode (buffer
, offset
) {
13299 var opcode
= buffer
.readUInt8(offset
)
13303 if (opcode
< OPS
.OP_PUSHDATA1
) {
13308 } else if (opcode
=== OPS
.OP_PUSHDATA1
) {
13309 if (offset
+ 2 > buffer
.length
) return null
13310 number
= buffer
.readUInt8(offset
+ 1)
13314 } else if (opcode
=== OPS
.OP_PUSHDATA2
) {
13315 if (offset
+ 3 > buffer
.length
) return null
13316 number
= buffer
.readUInt16LE(offset
+ 1)
13321 if (offset
+ 5 > buffer
.length
) return null
13322 if (opcode
!== OPS
.OP_PUSHDATA4
) throw new Error('Unexpected opcode')
13324 number
= buffer
.readUInt32LE(offset
+ 1)
13336 encodingLength: encodingLength
,
13341 },{"bitcoin-ops":42}],99:[function(require
,module
,exports
){
13342 (function (process
,global
){
13345 function oldBrowser () {
13346 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
13349 var Buffer
= require('safe-buffer').Buffer
13350 var crypto
= global
.crypto
|| global
.msCrypto
13352 if (crypto
&& crypto
.getRandomValues
) {
13353 module
.exports
= randomBytes
13355 module
.exports
= oldBrowser
13358 function 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
)
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
)
13370 // XXX: phantomjs doesn't like a buffer being passed here
13371 var bytes
= Buffer
.from(rawBytes
.buffer
)
13373 if (typeof cb
=== 'function') {
13374 return process
.nextTick(function () {
13382 }).call(this,require('_process'),typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
13383 },{"_process":13,"safe-buffer":101}],100:[function(require
,module
,exports
){
13384 (function (Buffer
){
13386 var inherits
= require('inherits')
13387 var HashBase
= require('hash-base')
13389 function RIPEMD160 () {
13390 HashBase
.call(this, 64)
13393 this._a
= 0x67452301
13394 this._b
= 0xefcdab89
13395 this._c
= 0x98badcfe
13396 this._d
= 0x10325476
13397 this._e
= 0xc3d2e1f0
13400 inherits(RIPEMD160
, HashBase
)
13402 RIPEMD160
.prototype._update = function () {
13403 var m
= new Array(16)
13404 for (var i
= 0; i
< 16; ++i
) m
[i
] = this._block
.readInt32LE(i
* 4)
13412 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
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)
13432 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
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)
13452 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
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)
13472 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
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)
13492 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
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)
13518 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
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)
13538 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
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)
13558 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
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)
13578 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
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)
13598 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
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)
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
13627 RIPEMD160
.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)
13633 this._blockOffset
= 0
13636 this._block
.fill(0, this._blockOffset
, 56)
13637 this._block
.writeUInt32LE(this._length
[0], 56)
13638 this._block
.writeUInt32LE(this._length
[1], 60)
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)
13651 function rotl (x
, n
) {
13652 return (x
<< n
) | (x
>>> (32 - n
))
13655 function fn1 (a
, b
, c
, d
, e
, m
, k
, s
) {
13656 return (rotl((a
+ (b
^ c
^ d
) + m
+ k
) | 0, s
) + e
) | 0
13659 function fn2 (a
, b
, c
, d
, e
, m
, k
, s
) {
13660 return (rotl((a
+ ((b
& c
) | ((~b
) & d
)) + m
+ k
) | 0, s
) + e
) | 0
13663 function fn3 (a
, b
, c
, d
, e
, m
, k
, s
) {
13664 return (rotl((a
+ ((b
| (~c
)) ^ d
) + m
+ k
) | 0, s
) + e
) | 0
13667 function fn4 (a
, b
, c
, d
, e
, m
, k
, s
) {
13668 return (rotl((a
+ ((b
& d
) | (c
& (~d
))) + m
+ k
) | 0, s
) + e
) | 0
13671 function fn5 (a
, b
, c
, d
, e
, m
, k
, s
) {
13672 return (rotl((a
+ (b
^ (c
| (~d
))) + m
+ k
) | 0, s
) + e
) | 0
13675 module
.exports
= RIPEMD160
13677 }).call(this,require("buffer").Buffer
)
13678 },{"buffer":5,"hash-base":95,"inherits":96}],101:[function(require
,module
,exports
){
13679 /* eslint-disable node/no-deprecated-api */
13680 var buffer
= require('buffer')
13681 var Buffer
= buffer
.Buffer
13683 // alternative to using Object.keys for old browsers
13684 function copyProps (src
, dst
) {
13685 for (var key
in src
) {
13686 dst
[key
] = src
[key
]
13689 if (Buffer
.from && Buffer
.alloc
&& Buffer
.allocUnsafe
&& Buffer
.allocUnsafeSlow
) {
13690 module
.exports
= buffer
13692 // Copy properties from require('buffer')
13693 copyProps(buffer
, exports
)
13694 exports
.Buffer
= SafeBuffer
13697 function SafeBuffer (arg
, encodingOrOffset
, length
) {
13698 return Buffer(arg
, encodingOrOffset
, length
)
13701 // Copy static methods from Buffer
13702 copyProps(Buffer
, SafeBuffer
)
13704 SafeBuffer
.from = function (arg
, encodingOrOffset
, length
) {
13705 if (typeof arg
=== 'number') {
13706 throw new TypeError('Argument must not be a number')
13708 return Buffer(arg
, encodingOrOffset
, length
)
13711 SafeBuffer
.alloc = function (size
, fill
, encoding
) {
13712 if (typeof size
!== 'number') {
13713 throw new TypeError('Argument must be a number')
13715 var buf
= Buffer(size
)
13716 if (fill
!== undefined) {
13717 if (typeof encoding
=== 'string') {
13718 buf
.fill(fill
, encoding
)
13728 SafeBuffer
.allocUnsafe = function (size
) {
13729 if (typeof size
!== 'number') {
13730 throw new TypeError('Argument must be a number')
13732 return Buffer(size
)
13735 SafeBuffer
.allocUnsafeSlow = function (size
) {
13736 if (typeof size
!== 'number') {
13737 throw new TypeError('Argument must be a number')
13739 return buffer
.SlowBuffer(size
)
13742 },{"buffer":5}],102:[function(require
,module
,exports
){
13743 var Buffer
= require('safe-buffer').Buffer
13745 // prototype class for hash functions
13746 function Hash (blockSize
, finalSize
) {
13747 this._block
= Buffer
.alloc(blockSize
)
13748 this._finalSize
= finalSize
13749 this._blockSize
= blockSize
13753 Hash
.prototype.update = function (data
, enc
) {
13754 if (typeof data
=== 'string') {
13755 enc
= enc
|| 'utf8'
13756 data
= Buffer
.from(data
, enc
)
13759 var block
= this._block
13760 var blockSize
= this._blockSize
13761 var length
= data
.length
13762 var accum
= this._len
13764 for (var offset
= 0; offset
< length
;) {
13765 var assigned
= accum
% blockSize
13766 var remainder
= Math
.min(length
- offset
, blockSize
- assigned
)
13768 for (var i
= 0; i
< remainder
; i
++) {
13769 block
[assigned
+ i
] = data
[offset
+ i
]
13773 offset
+= remainder
13775 if ((accum
% blockSize
) === 0) {
13776 this._update(block
)
13780 this._len
+= length
13784 Hash
.prototype.digest = function (enc
) {
13785 var rem
= this._len
% this._blockSize
13787 this._block
[rem
] = 0x80
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)
13793 if (rem
>= this._finalSize
) {
13794 this._update(this._block
)
13795 this._block
.fill(0)
13798 var bits
= this._len
* 8
13801 if (bits
<= 0xffffffff) {
13802 this._block
.writeUInt32BE(bits
, this._blockSize
- 4)
13806 var lowBits
= (bits
& 0xffffffff) >>> 0
13807 var highBits
= (bits
- lowBits
) / 0x100000000
13809 this._block
.writeUInt32BE(highBits
, this._blockSize
- 8)
13810 this._block
.writeUInt32BE(lowBits
, this._blockSize
- 4)
13813 this._update(this._block
)
13814 var hash
= this._hash()
13816 return enc
? hash
.toString(enc
) : hash
13819 Hash
.prototype._update = function () {
13820 throw new Error('_update must be implemented by subclass')
13823 module
.exports
= Hash
13825 },{"safe-buffer":101}],103:[function(require
,module
,exports
){
13826 var exports
= module
.exports
= function SHA (algorithm
) {
13827 algorithm
= algorithm
.toLowerCase()
13829 var Algorithm
= exports
[algorithm
]
13830 if (!Algorithm
) throw new Error(algorithm
+ ' is not supported (we accept pull requests)')
13832 return new Algorithm()
13835 exports
.sha
= require('./sha')
13836 exports
.sha1
= require('./sha1')
13837 exports
.sha224
= require('./sha224')
13838 exports
.sha256
= require('./sha256')
13839 exports
.sha384
= require('./sha384')
13840 exports
.sha512
= require('./sha512')
13842 },{"./sha":104,"./sha1":105,"./sha224":106,"./sha256":107,"./sha384":108,"./sha512":109}],104:[function(require
,module
,exports
){
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.
13851 var inherits
= require('inherits')
13852 var Hash
= require('./hash')
13853 var Buffer
= require('safe-buffer').Buffer
13856 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13859 var W
= new Array(80)
13865 Hash
.call(this, 64, 56)
13868 inherits(Sha
, Hash
)
13870 Sha
.prototype.init = function () {
13871 this._a
= 0x67452301
13872 this._b
= 0xefcdab89
13873 this._c
= 0x98badcfe
13874 this._d
= 0x10325476
13875 this._e
= 0xc3d2e1f0
13880 function rotl5 (num
) {
13881 return (num
<< 5) | (num
>>> 27)
13884 function rotl30 (num
) {
13885 return (num
<< 30) | (num
>>> 2)
13888 function 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
)
13894 Sha
.prototype._update = function (M
) {
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
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]
13906 for (var j
= 0; j
< 80; ++j
) {
13908 var t
= (rotl5(a
) + ft(s
, b
, c
, d
) + e
+ W
[j
] + K
[s
]) | 0
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
13924 Sha
.prototype._hash = function () {
13925 var H
= Buffer
.allocUnsafe(20)
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)
13936 module
.exports
= Sha
13938 },{"./hash":102,"inherits":96,"safe-buffer":101}],105:[function(require
,module
,exports
){
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.
13948 var inherits
= require('inherits')
13949 var Hash
= require('./hash')
13950 var Buffer
= require('safe-buffer').Buffer
13953 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13956 var W
= new Array(80)
13962 Hash
.call(this, 64, 56)
13965 inherits(Sha1
, Hash
)
13967 Sha1
.prototype.init = function () {
13968 this._a
= 0x67452301
13969 this._b
= 0xefcdab89
13970 this._c
= 0x98badcfe
13971 this._d
= 0x10325476
13972 this._e
= 0xc3d2e1f0
13977 function rotl1 (num
) {
13978 return (num
<< 1) | (num
>>> 31)
13981 function rotl5 (num
) {
13982 return (num
<< 5) | (num
>>> 27)
13985 function rotl30 (num
) {
13986 return (num
<< 30) | (num
>>> 2)
13989 function 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
)
13995 Sha1
.prototype._update = function (M
) {
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
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])
14007 for (var j
= 0; j
< 80; ++j
) {
14009 var t
= (rotl5(a
) + ft(s
, b
, c
, d
) + e
+ W
[j
] + K
[s
]) | 0
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
14025 Sha1
.prototype._hash = function () {
14026 var H
= Buffer
.allocUnsafe(20)
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)
14037 module
.exports
= Sha1
14039 },{"./hash":102,"inherits":96,"safe-buffer":101}],106:[function(require
,module
,exports
){
14041 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14043 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14044 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14048 var inherits
= require('inherits')
14049 var Sha256
= require('./sha256')
14050 var Hash
= require('./hash')
14051 var Buffer
= require('safe-buffer').Buffer
14053 var W
= new Array(64)
14055 function Sha224 () {
14058 this._w
= W
// new Array(64)
14060 Hash
.call(this, 64, 56)
14063 inherits(Sha224
, Sha256
)
14065 Sha224
.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
14078 Sha224
.prototype._hash = function () {
14079 var H
= Buffer
.allocUnsafe(28)
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)
14092 module
.exports
= Sha224
14094 },{"./hash":102,"./sha256":107,"inherits":96,"safe-buffer":101}],107:[function(require
,module
,exports
){
14096 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14098 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14099 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14103 var inherits
= require('inherits')
14104 var Hash
= require('./hash')
14105 var Buffer
= require('safe-buffer').Buffer
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
14126 var W
= new Array(64)
14128 function Sha256 () {
14131 this._w
= W
// new Array(64)
14133 Hash
.call(this, 64, 56)
14136 inherits(Sha256
, Hash
)
14138 Sha256
.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
14151 function ch (x
, y
, z
) {
14152 return z
^ (x
& (y
^ z
))
14155 function maj (x
, y
, z
) {
14156 return (x
& y
) | (z
& (x
| y
))
14159 function sigma0 (x
) {
14160 return (x
>>> 2 | x
<< 30) ^ (x
>>> 13 | x
<< 19) ^ (x
>>> 22 | x
<< 10)
14163 function sigma1 (x
) {
14164 return (x
>>> 6 | x
<< 26) ^ (x
>>> 11 | x
<< 21) ^ (x
>>> 25 | x
<< 7)
14167 function gamma0 (x
) {
14168 return (x
>>> 7 | x
<< 25) ^ (x
>>> 18 | x
<< 14) ^ (x
>>> 3)
14171 function gamma1 (x
) {
14172 return (x
>>> 17 | x
<< 15) ^ (x
>>> 19 | x
<< 13) ^ (x
>>> 10)
14175 Sha256
.prototype._update = function (M
) {
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
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
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
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
14214 Sha256
.prototype._hash = function () {
14215 var H
= Buffer
.allocUnsafe(32)
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)
14229 module
.exports
= Sha256
14231 },{"./hash":102,"inherits":96,"safe-buffer":101}],108:[function(require
,module
,exports
){
14232 var inherits
= require('inherits')
14233 var SHA512
= require('./sha512')
14234 var Hash
= require('./hash')
14235 var Buffer
= require('safe-buffer').Buffer
14237 var W
= new Array(160)
14239 function Sha384 () {
14243 Hash
.call(this, 128, 112)
14246 inherits(Sha384
, SHA512
)
14248 Sha384
.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
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
14270 Sha384
.prototype._hash = function () {
14271 var H
= Buffer
.allocUnsafe(48)
14273 function writeInt64BE (h
, l
, offset
) {
14274 H
.writeInt32BE(h
, offset
)
14275 H
.writeInt32BE(l
, offset
+ 4)
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)
14288 module
.exports
= Sha384
14290 },{"./hash":102,"./sha512":109,"inherits":96,"safe-buffer":101}],109:[function(require
,module
,exports
){
14291 var inherits
= require('inherits')
14292 var Hash
= require('./hash')
14293 var Buffer
= require('safe-buffer').Buffer
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
14338 var W
= new Array(160)
14340 function Sha512 () {
14344 Hash
.call(this, 128, 112)
14347 inherits(Sha512
, Hash
)
14349 Sha512
.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
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
14371 function Ch (x
, y
, z
) {
14372 return z
^ (x
& (y
^ z
))
14375 function maj (x
, y
, z
) {
14376 return (x
& y
) | (z
& (x
| y
))
14379 function sigma0 (x
, xl
) {
14380 return (x
>>> 28 | xl
<< 4) ^ (xl
>>> 2 | x
<< 30) ^ (xl
>>> 7 | x
<< 25)
14383 function sigma1 (x
, xl
) {
14384 return (x
>>> 14 | xl
<< 18) ^ (x
>>> 18 | xl
<< 14) ^ (xl
>>> 9 | x
<< 23)
14387 function Gamma0 (x
, xl
) {
14388 return (x
>>> 1 | xl
<< 31) ^ (x
>>> 8 | xl
<< 24) ^ (x
>>> 7)
14391 function Gamma0l (x
, xl
) {
14392 return (x
>>> 1 | xl
<< 31) ^ (x
>>> 8 | xl
<< 24) ^ (x
>>> 7 | xl
<< 25)
14395 function Gamma1 (x
, xl
) {
14396 return (x
>>> 19 | xl
<< 13) ^ (xl
>>> 29 | x
<< 3) ^ (x
>>> 6)
14399 function Gamma1l (x
, xl
) {
14400 return (x
>>> 19 | xl
<< 13) ^ (xl
>>> 29 | x
<< 3) ^ (x
>>> 6 | xl
<< 26)
14403 function getCarry (a
, b
) {
14404 return (a
>>> 0) < (b
>>> 0) ? 1 : 0
14407 Sha512
.prototype._update = function (M
) {
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
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
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)
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
)
14439 xl
= W
[i
- 2 * 2 + 1]
14440 var gamma1
= Gamma1(xh
, xl
)
14441 var gamma1l
= Gamma1l(xl
, xh
)
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]
14447 var Wi16h
= W
[i
- 16 * 2]
14448 var Wi16l
= W
[i
- 16 * 2 + 1]
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
14461 for (var j
= 0; j
< 160; j
+= 2) {
14465 var majh
= maj(ah
, bh
, ch
)
14466 var majl
= maj(al
, bl
, cl
)
14468 var sigma0h
= sigma0(ah
, al
)
14469 var sigma0l
= sigma0(al
, ah
)
14470 var sigma1h
= sigma1(eh
, el
)
14471 var sigma1l
= sigma1(el
, eh
)
14473 // t1 = h + sigma1 + ch + K[j] + W[j]
14477 var chh
= Ch(eh
, fh
, gh
)
14478 var chl
= Ch(el
, fl
, gl
)
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
14489 // t2 = sigma0 + maj
14490 var t2l
= (sigma0l
+ majl
) | 0
14491 var t2h
= (sigma0h
+ majh
+ getCarry(t2l
, sigma0l
)) | 0
14499 el
= (dl
+ t1l
) | 0
14500 eh
= (dh
+ t1h
+ getCarry(el
, dl
)) | 0
14507 al
= (t1l
+ t2l
) | 0
14508 ah
= (t1h
+ t2h
+ getCarry(al
, t1l
)) | 0
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
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
14530 Sha512
.prototype._hash = function () {
14531 var H
= Buffer
.allocUnsafe(64)
14533 function writeInt64BE (h
, l
, offset
) {
14534 H
.writeInt32BE(h
, offset
)
14535 H
.writeInt32BE(l
, offset
+ 4)
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)
14550 module
.exports
= Sha512
14552 },{"./hash":102,"inherits":96,"safe-buffer":101}],110:[function(require
,module
,exports
){
14553 var native = require('./native')
14555 function getTypeName (fn
) {
14556 return fn
.name
|| fn
.toString().match(/function (.*?)\s
*\(/)[1]
14559 function getValueTypeName (value
) {
14560 return native.Nil(value
) ? '' : getTypeName(value
.constructor)
14563 function getValue (value
) {
14564 if (native.Function(value
)) return ''
14565 if (native.String(value
)) return JSON
.stringify(value
)
14566 if (value
&& native.Object(value
)) return ''
14570 function 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'
14575 return type
!== undefined ? type : ''
14578 function tfErrorString (type
, value
, valueTypeName
) {
14579 var valueJson
= getValue(value
)
14581 return 'Expected ' + tfJSON(type
) + ', got' +
14582 (valueTypeName
!== '' ? ' ' + valueTypeName : '') +
14583 (valueJson
!== '' ? ' ' + valueJson : '')
14586 function TfTypeError (type
, value
, valueTypeName
) {
14587 valueTypeName
= valueTypeName
|| getValueTypeName(value
)
14588 this.message
= tfErrorString(type
, value
, valueTypeName
)
14590 Error
.captureStackTrace(this, TfTypeError
)
14592 this.__value
= value
14593 this.__valueTypeName
= valueTypeName
14596 TfTypeError
.prototype = Object
.create(Error
.prototype)
14597 TfTypeError
.prototype.constructor = TfTypeError
14599 function tfPropertyErrorString (type
, label
, name
, value
, valueTypeName
) {
14600 var description
= '" of type '
14601 if (label
=== 'key') description
= '" with key type '
14603 return tfErrorString('property "' + tfJSON(name
) + description
+ tfJSON(type
), value
, valueTypeName
)
14606 function TfPropertyTypeError (type
, property
, label
, value
, valueTypeName
) {
14608 valueTypeName
= valueTypeName
|| getValueTypeName(value
)
14609 this.message
= tfPropertyErrorString(type
, label
, property
, value
, valueTypeName
)
14611 this.message
= 'Unexpected property "' + property
+ '"'
14614 Error
.captureStackTrace(this, TfTypeError
)
14615 this.__label
= label
14616 this.__property
= property
14618 this.__value
= value
14619 this.__valueTypeName
= valueTypeName
14622 TfPropertyTypeError
.prototype = Object
.create(Error
.prototype)
14623 TfPropertyTypeError
.prototype.constructor = TfTypeError
14625 function tfCustomError (expected
, actual
) {
14626 return new TfTypeError(expected
, {}, actual
)
14629 function tfSubError (e
, property
, label
) {
14631 if (e
instanceof TfPropertyTypeError
) {
14632 property
= property
+ '.' + e
.__property
14634 e
= new TfPropertyTypeError(
14635 e
.__type
, property
, e
.__label
, e
.__value
, e
.__valueTypeName
14639 } else if (e
instanceof TfTypeError
) {
14640 e
= new TfPropertyTypeError(
14641 e
.__type
, property
, label
, e
.__value
, e
.__valueTypeName
14645 Error
.captureStackTrace(e
)
14650 TfTypeError: TfTypeError
,
14651 TfPropertyTypeError: TfPropertyTypeError
,
14652 tfCustomError: tfCustomError
,
14653 tfSubError: tfSubError
,
14655 getValueTypeName: getValueTypeName
14658 },{"./native":113}],111:[function(require
,module
,exports
){
14659 (function (Buffer
){
14660 var NATIVE
= require('./native')
14661 var ERRORS
= require('./errors')
14663 function _Buffer (value
) {
14664 return Buffer
.isBuffer(value
)
14667 function Hex (value
) {
14668 return typeof value
=== 'string' && /^([0-9a-f]{2})+$/i.test(value
)
14671 function _LengthN (type
, length
) {
14672 var name
= type
.toJSON()
14674 function Length (value
) {
14675 if (!type(value
)) return false
14676 if (value
.length
=== length
) return true
14678 throw ERRORS
.tfCustomError(name
+ '(Length: ' + length
+ ')', name
+ '(Length: ' + value
.length
+ ')')
14680 Length
.toJSON = function () { return name
}
14685 var _ArrayN
= _LengthN
.bind(null, NATIVE
.Array
)
14686 var _BufferN
= _LengthN
.bind(null, _Buffer
)
14687 var _HexN
= _LengthN
.bind(null, Hex
)
14688 var _StringN
= _LengthN
.bind(null, NATIVE
.String
)
14690 var UINT53_MAX
= Math
.pow(2, 53) - 1
14692 function Finite (value
) {
14693 return typeof value
=== 'number' && isFinite(value
)
14695 function Int8 (value
) { return ((value
<< 24) >> 24) === value
}
14696 function Int16 (value
) { return ((value
<< 16) >> 16) === value
}
14697 function Int32 (value
) { return (value
| 0) === value
}
14698 function UInt8 (value
) { return (value
& 0xff) === value
}
14699 function UInt16 (value
) { return (value
& 0xffff) === value
}
14700 function UInt32 (value
) { return (value
>>> 0) === value
}
14701 function UInt53 (value
) {
14702 return typeof value
=== 'number' &&
14704 value
<= UINT53_MAX
&&
14705 Math
.floor(value
) === value
14725 for (var typeName
in types
) {
14726 types
[typeName
].toJSON = function (t
) {
14728 }.bind(null, typeName
)
14731 module
.exports
= types
14733 }).call(this,{"isBuffer":require("../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
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
){
14735 var ERRORS
= require('./errors')
14736 var NATIVE
= require('./native')
14739 var tfJSON
= ERRORS
.tfJSON
14740 var TfTypeError
= ERRORS
.TfTypeError
14741 var TfPropertyTypeError
= ERRORS
.TfPropertyTypeError
14742 var tfSubError
= ERRORS
.tfSubError
14743 var getValueTypeName
= ERRORS
.getValueTypeName
14746 arrayOf: function arrayOf (type
) {
14747 type
= compile(type
)
14749 function _arrayOf (array
, strict
) {
14750 if (!NATIVE
.Array(array
)) return false
14751 if (NATIVE
.Nil(array
)) return false
14753 return array
.every(function (value
, i
) {
14755 return typeforce(type
, value
, strict
)
14757 throw tfSubError(e
, i
)
14761 _arrayOf
.toJSON = function () { return '[' + tfJSON(type
) + ']' }
14766 maybe: function maybe (type
) {
14767 type
= compile(type
)
14769 function _maybe (value
, strict
) {
14770 return NATIVE
.Nil(value
) || type(value
, strict
, maybe
)
14772 _maybe
.toJSON = function () { return '?' + tfJSON(type
) }
14777 map: function map (propertyType
, propertyKeyType
) {
14778 propertyType
= compile(propertyType
)
14779 if (propertyKeyType
) propertyKeyType
= compile(propertyKeyType
)
14781 function _map (value
, strict
) {
14782 if (!NATIVE
.Object(value
)) return false
14783 if (NATIVE
.Nil(value
)) return false
14785 for (var propertyName
in value
) {
14787 if (propertyKeyType
) {
14788 typeforce(propertyKeyType
, propertyName
, strict
)
14791 throw tfSubError(e
, propertyName
, 'key')
14795 var propertyValue
= value
[propertyName
]
14796 typeforce(propertyType
, propertyValue
, strict
)
14798 throw tfSubError(e
, propertyName
)
14805 if (propertyKeyType
) {
14806 _map
.toJSON = function () {
14807 return '{' + tfJSON(propertyKeyType
) + ': ' + tfJSON(propertyType
) + '}'
14810 _map
.toJSON = function () { return '{' + tfJSON(propertyType
) + '}' }
14816 object: function object (uncompiled
) {
14819 for (var typePropertyName
in uncompiled
) {
14820 type
[typePropertyName
] = compile(uncompiled
[typePropertyName
])
14823 function _object (value
, strict
) {
14824 if (!NATIVE
.Object(value
)) return false
14825 if (NATIVE
.Nil(value
)) return false
14830 for (propertyName
in type
) {
14831 var propertyType
= type
[propertyName
]
14832 var propertyValue
= value
[propertyName
]
14834 typeforce(propertyType
, propertyValue
, strict
)
14837 throw tfSubError(e
, propertyName
)
14841 for (propertyName
in value
) {
14842 if (type
[propertyName
]) continue
14844 throw new TfPropertyTypeError(undefined, propertyName
)
14850 _object
.toJSON = function () { return tfJSON(type
) }
14855 oneOf: function oneOf () {
14856 var types
= [].slice
.call(arguments
).map(compile
)
14858 function _oneOf (value
, strict
) {
14859 return types
.some(function (type
) {
14861 return typeforce(type
, value
, strict
)
14867 _oneOf
.toJSON = function () { return types
.map(tfJSON
).join('|') }
14872 quacksLike: function quacksLike (type
) {
14873 function _quacksLike (value
) {
14874 return type
=== getValueTypeName(value
)
14876 _quacksLike
.toJSON = function () { return type
}
14881 tuple: function tuple () {
14882 var types
= [].slice
.call(arguments
).map(compile
)
14884 function _tuple (values
, strict
) {
14885 if (NATIVE
.Nil(values
)) return false
14886 if (NATIVE
.Nil(values
.length
)) return false
14887 if (strict
&& (values
.length
!== types
.length
)) return false
14889 return types
.every(function (type
, i
) {
14891 return typeforce(type
, values
[i
], strict
)
14893 throw tfSubError(e
, i
)
14897 _tuple
.toJSON = function () { return '(' + types
.map(tfJSON
).join(', ') + ')' }
14902 value: function value (expected
) {
14903 function _value (actual
) {
14904 return actual
=== expected
14906 _value
.toJSON = function () { return expected
}
14912 function compile (type
) {
14913 if (NATIVE
.String(type
)) {
14914 if (type
[0] === '?') return TYPES
.maybe(type
.slice(1))
14916 return NATIVE
[type
] || TYPES
.quacksLike(type
)
14917 } else if (type
&& NATIVE
.Object(type
)) {
14918 if (NATIVE
.Array(type
)) return TYPES
.arrayOf(type
[0])
14920 return TYPES
.object(type
)
14921 } else if (NATIVE
.Function(type
)) {
14925 return TYPES
.value(type
)
14928 function typeforce (type
, value
, strict
, surrogate
) {
14929 if (NATIVE
.Function(type
)) {
14930 if (type(value
, strict
)) return true
14932 throw new TfTypeError(surrogate
|| type
, value
)
14936 return typeforce(compile(type
), value
, strict
)
14939 // assign types to typeforce function
14940 for (var typeName
in NATIVE
) {
14941 typeforce
[typeName
] = NATIVE
[typeName
]
14944 for (typeName
in TYPES
) {
14945 typeforce
[typeName
] = TYPES
[typeName
]
14948 var EXTRA
= require('./extra')
14949 for (typeName
in EXTRA
) {
14950 typeforce
[typeName
] = EXTRA
[typeName
]
14954 function __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
)
14959 typeforce(type
, value
, strict
)
14967 typeforce
.async
= __async
14968 typeforce
.compile
= compile
14969 typeforce
.TfTypeError
= TfTypeError
14970 typeforce
.TfPropertyTypeError
= TfPropertyTypeError
14972 module
.exports
= typeforce
14974 },{"./errors":110,"./extra":111,"./native":113}],113:[function(require
,module
,exports
){
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 }
14987 types
.Null
= types
.Nil
14989 for (var typeName
in types
) {
14990 types
[typeName
].toJSON = function (t
) {
14992 }.bind(null, typeName
)
14995 module
.exports
= types
14997 },{}],114:[function(require
,module
,exports
){
14999 var Buffer
= require('safe-buffer').Buffer
15001 // Number.MAX_SAFE_INTEGER
15002 var MAX_SAFE_INTEGER
= 9007199254740991
15004 function checkUInt53 (n
) {
15005 if (n
< 0 || n
> MAX_SAFE_INTEGER
|| n
% 1 !== 0) throw new RangeError('value out of range')
15008 function encode (number
, buffer
, offset
) {
15009 checkUInt53(number
)
15011 if (!buffer
) buffer
= Buffer
.allocUnsafe(encodingLength(number
))
15012 if (!Buffer
.isBuffer(buffer
)) throw new TypeError('buffer must be a Buffer instance')
15013 if (!offset
) offset
= 0
15016 if (number
< 0xfd) {
15017 buffer
.writeUInt8(number
, offset
)
15021 } else if (number
<= 0xffff) {
15022 buffer
.writeUInt8(0xfd, offset
)
15023 buffer
.writeUInt16LE(number
, offset
+ 1)
15027 } else if (number
<= 0xffffffff) {
15028 buffer
.writeUInt8(0xfe, offset
)
15029 buffer
.writeUInt32LE(number
, offset
+ 1)
15034 buffer
.writeUInt8(0xff, offset
)
15035 buffer
.writeUInt32LE(number
>>> 0, offset
+ 1)
15036 buffer
.writeUInt32LE((number
/ 0x100000000) | 0, offset
+ 5)
15043 function decode (buffer
, offset
) {
15044 if (!Buffer
.isBuffer(buffer
)) throw new TypeError('buffer must be a Buffer instance')
15045 if (!offset
) offset
= 0
15047 var first
= buffer
.readUInt8(offset
)
15050 if (first
< 0xfd) {
15055 } else if (first
=== 0xfd) {
15057 return buffer
.readUInt16LE(offset
+ 1)
15060 } else if (first
=== 0xfe) {
15062 return buffer
.readUInt32LE(offset
+ 1)
15067 var lo
= buffer
.readUInt32LE(offset
+ 1)
15068 var hi
= buffer
.readUInt32LE(offset
+ 5)
15069 var number
= hi
* 0x0100000000 + lo
15070 checkUInt53(number
)
15076 function encodingLength (number
) {
15077 checkUInt53(number
)
15081 : number
<= 0xffff ? 3
15082 : number
<= 0xffffffff ? 5
15087 module
.exports
= { encode: encode
, decode: decode
, encodingLength: encodingLength
}
15089 },{"safe-buffer":101}],115:[function(require
,module
,exports
){
15090 (function (Buffer
){
15091 var bs58check
= require('bs58check')
15093 function decodeRaw (buffer
, version
) {
15094 // check version only if defined
15095 if (version
!== undefined && buffer
[0] !== version
) throw new Error('Invalid network version')
15098 if (buffer
.length
=== 33) {
15100 version: buffer
[0],
15101 privateKey: buffer
.slice(1, 33),
15107 if (buffer
.length
!== 34) throw new Error('Invalid WIF length')
15109 // invalid compression flag
15110 if (buffer
[33] !== 0x01) throw new Error('Invalid compression flag')
15113 version: buffer
[0],
15114 privateKey: buffer
.slice(1, 33),
15119 function encodeRaw (version
, privateKey
, compressed
) {
15120 var result
= new Buffer(compressed
? 34 : 33)
15122 result
.writeUInt8(version
, 0)
15123 privateKey
.copy(result
, 1)
15132 function decode (string
, version
) {
15133 return decodeRaw(bs58check
.decode(string
), version
)
15136 function encode (version
, privateKey
, compressed
) {
15137 if (typeof version
=== 'number') return bs58check
.encode(encodeRaw(version
, privateKey
, compressed
))
15139 return bs58check
.encode(
15142 version
.privateKey
,
15150 decodeRaw: decodeRaw
,
15152 encodeRaw: encodeRaw
15155 }).call(this,require("buffer").Buffer
)
15156 },{"bs58check":83,"buffer":5}]},{},[34])(34)