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
) {
8666 typeforce(types
.tuple(types
.Hash160bit
, types
.UInt8
), arguments
)
8668 var payload
= Buffer
.allocUnsafe(21)
8669 payload
.writeUInt8(version
, 0)
8670 hash
.copy(payload
, 1)
8672 return bs58check
.encode(payload
)
8675 typeforce(types
.tuple(types
.Hash160bit
, types
.UInt16
), arguments
)
8677 var payload
= Buffer
.allocUnsafe(22)
8678 payload
.writeUInt16BE(version
, 0)
8679 hash
.copy(payload
, 2)
8681 return bs58check
.encode(payload
)
8685 function toBech32 (data
, version
, prefix
) {
8686 var words
= bech32
.toWords(data
)
8687 words
.unshift(version
)
8689 return bech32
.encode(prefix
, words
)
8692 function fromOutputScript (outputScript
, network
) {
8693 network
= network
|| networks
.bitcoin
8695 if (btemplates
.pubKeyHash
.output
.check(outputScript
)) return toBase58Check(bscript
.compile(outputScript
).slice(3, 23), network
.pubKeyHash
)
8696 if (btemplates
.scriptHash
.output
.check(outputScript
)) return toBase58Check(bscript
.compile(outputScript
).slice(2, 22), network
.scriptHash
)
8697 if (btemplates
.witnessPubKeyHash
.output
.check(outputScript
)) return toBech32(bscript
.compile(outputScript
).slice(2, 22), 0, network
.bech32
)
8698 if (btemplates
.witnessScriptHash
.output
.check(outputScript
)) return toBech32(bscript
.compile(outputScript
).slice(2, 34), 0, network
.bech32
)
8700 throw new Error(bscript
.toASM(outputScript
) + ' has no matching Address')
8703 function toOutputScript (address
, network
) {
8704 network
= network
|| networks
.bitcoin
8708 decode
= fromBase58Check(address
)
8712 if (decode
.version
=== network
.pubKeyHash
) return btemplates
.pubKeyHash
.output
.encode(decode
.hash
)
8713 if (decode
.version
=== network
.scriptHash
) return btemplates
.scriptHash
.output
.encode(decode
.hash
)
8716 decode
= fromBech32(address
)
8720 if (decode
.prefix
!== network
.bech32
) throw new Error(address
+ ' has an invalid prefix')
8721 if (decode
.version
=== 0) {
8722 if (decode
.data
.length
=== 20) return btemplates
.witnessPubKeyHash
.output
.encode(decode
.data
)
8723 if (decode
.data
.length
=== 32) return btemplates
.witnessScriptHash
.output
.encode(decode
.data
)
8728 throw new Error(address
+ ' has no matching Script')
8732 fromBase58Check: fromBase58Check
,
8733 fromBech32: fromBech32
,
8734 fromOutputScript: fromOutputScript
,
8735 toBase58Check: toBase58Check
,
8737 toOutputScript: toOutputScript
8740 },{"./networks":53,"./script":54,"./templates":56,"./types":80,"bech32":36,"bs58check":83,"safe-buffer":101,"typeforce":112}],45:[function(require
,module
,exports
){
8741 var Buffer
= require('safe-buffer').Buffer
8742 var bcrypto
= require('./crypto')
8743 var fastMerkleRoot
= require('merkle-lib/fastRoot')
8744 var typeforce
= require('typeforce')
8745 var types
= require('./types')
8746 var varuint
= require('varuint-bitcoin')
8748 var Transaction
= require('./transaction')
8752 this.prevHash
= null
8753 this.merkleRoot
= null
8759 Block
.fromBuffer = function (buffer
) {
8760 if (buffer
.length
< 80) throw new Error('Buffer too small (< 80 bytes)')
8763 function readSlice (n
) {
8765 return buffer
.slice(offset
- n
, offset
)
8768 function readUInt32 () {
8769 var i
= buffer
.readUInt32LE(offset
)
8774 function readInt32 () {
8775 var i
= buffer
.readInt32LE(offset
)
8780 var block
= new Block()
8781 block
.version
= readInt32()
8782 block
.prevHash
= readSlice(32)
8783 block
.merkleRoot
= readSlice(32)
8784 block
.timestamp
= readUInt32()
8785 block
.bits
= readUInt32()
8786 block
.nonce
= readUInt32()
8788 if (buffer
.length
=== 80) return block
8790 function readVarInt () {
8791 var vi
= varuint
.decode(buffer
, offset
)
8792 offset
+= varuint
.decode
.bytes
8796 function readTransaction () {
8797 var tx
= Transaction
.fromBuffer(buffer
.slice(offset
), true)
8798 offset
+= tx
.byteLength()
8802 var nTransactions
= readVarInt()
8803 block
.transactions
= []
8805 for (var i
= 0; i
< nTransactions
; ++i
) {
8806 var tx
= readTransaction()
8807 block
.transactions
.push(tx
)
8813 Block
.prototype.byteLength = function (headersOnly
) {
8814 if (headersOnly
|| !this.transactions
) return 80
8816 return 80 + varuint
.encodingLength(this.transactions
.length
) + this.transactions
.reduce(function (a
, x
) {
8817 return a
+ x
.byteLength()
8821 Block
.fromHex = function (hex
) {
8822 return Block
.fromBuffer(Buffer
.from(hex
, 'hex'))
8825 Block
.prototype.getHash = function () {
8826 return bcrypto
.hash256(this.toBuffer(true))
8829 Block
.prototype.getId = function () {
8830 return this.getHash().reverse().toString('hex')
8833 Block
.prototype.getUTCDate = function () {
8834 var date
= new Date(0) // epoch
8835 date
.setUTCSeconds(this.timestamp
)
8840 // TODO: buffer, offset compatibility
8841 Block
.prototype.toBuffer = function (headersOnly
) {
8842 var buffer
= Buffer
.allocUnsafe(this.byteLength(headersOnly
))
8845 function writeSlice (slice
) {
8846 slice
.copy(buffer
, offset
)
8847 offset
+= slice
.length
8850 function writeInt32 (i
) {
8851 buffer
.writeInt32LE(i
, offset
)
8854 function writeUInt32 (i
) {
8855 buffer
.writeUInt32LE(i
, offset
)
8859 writeInt32(this.version
)
8860 writeSlice(this.prevHash
)
8861 writeSlice(this.merkleRoot
)
8862 writeUInt32(this.timestamp
)
8863 writeUInt32(this.bits
)
8864 writeUInt32(this.nonce
)
8866 if (headersOnly
|| !this.transactions
) return buffer
8868 varuint
.encode(this.transactions
.length
, buffer
, offset
)
8869 offset
+= varuint
.encode
.bytes
8871 this.transactions
.forEach(function (tx
) {
8872 var txSize
= tx
.byteLength() // TODO: extract from toBuffer?
8873 tx
.toBuffer(buffer
, offset
)
8880 Block
.prototype.toHex = function (headersOnly
) {
8881 return this.toBuffer(headersOnly
).toString('hex')
8884 Block
.calculateTarget = function (bits
) {
8885 var exponent
= ((bits
& 0xff000000) >> 24) - 3
8886 var mantissa
= bits
& 0x007fffff
8887 var target
= Buffer
.alloc(32, 0)
8888 target
.writeUInt32BE(mantissa
, 28 - exponent
)
8892 Block
.calculateMerkleRoot = function (transactions
) {
8893 typeforce([{ getHash: types
.Function
}], transactions
)
8894 if (transactions
.length
=== 0) throw TypeError('Cannot compute merkle root for zero transactions')
8896 var hashes
= transactions
.map(function (transaction
) {
8897 return transaction
.getHash()
8900 return fastMerkleRoot(hashes
, bcrypto
.hash256
)
8903 Block
.prototype.checkMerkleRoot = function () {
8904 if (!this.transactions
) return false
8906 var actualMerkleRoot
= Block
.calculateMerkleRoot(this.transactions
)
8907 return this.merkleRoot
.compare(actualMerkleRoot
) === 0
8910 Block
.prototype.checkProofOfWork = function () {
8911 var hash
= this.getHash().reverse()
8912 var target
= Block
.calculateTarget(this.bits
)
8914 return hash
.compare(target
) <= 0
8917 module
.exports
= Block
8919 },{"./crypto":47,"./transaction":78,"./types":80,"merkle-lib/fastRoot":97,"safe-buffer":101,"typeforce":112,"varuint-bitcoin":114}],46:[function(require
,module
,exports
){
8920 var pushdata
= require('pushdata-bitcoin')
8921 var varuint
= require('varuint-bitcoin')
8923 // https://github.com/feross/buffer/blob/master/index.js#L1127
8924 function verifuint (value
, max
) {
8925 if (typeof value
!== 'number') throw new Error('cannot write a non-number as a number')
8926 if (value
< 0) throw new Error('specified a negative value for writing an unsigned value')
8927 if (value
> max
) throw new Error('RangeError: value out of range')
8928 if (Math
.floor(value
) !== value
) throw new Error('value has a fractional component')
8931 function readUInt64LE (buffer
, offset
) {
8932 var a
= buffer
.readUInt32LE(offset
)
8933 var b
= buffer
.readUInt32LE(offset
+ 4)
8936 verifuint(b
+ a
, 0x001fffffffffffff)
8941 function writeUInt64LE (buffer
, value
, offset
) {
8942 verifuint(value
, 0x001fffffffffffff)
8944 buffer
.writeInt32LE(value
& -1, offset
)
8945 buffer
.writeUInt32LE(Math
.floor(value
/ 0x100000000), offset
+ 4)
8949 // TODO: remove in 4.0.0?
8950 function readVarInt (buffer
, offset
) {
8951 var result
= varuint
.decode(buffer
, offset
)
8955 size: varuint
.decode
.bytes
8959 // TODO: remove in 4.0.0?
8960 function writeVarInt (buffer
, number
, offset
) {
8961 varuint
.encode(number
, buffer
, offset
)
8962 return varuint
.encode
.bytes
8966 pushDataSize: pushdata
.encodingLength
,
8967 readPushDataInt: pushdata
.decode
,
8968 readUInt64LE: readUInt64LE
,
8969 readVarInt: readVarInt
,
8970 varIntBuffer: varuint
.encode
,
8971 varIntSize: varuint
.encodingLength
,
8972 writePushDataInt: pushdata
.encode
,
8973 writeUInt64LE: writeUInt64LE
,
8974 writeVarInt: writeVarInt
8977 },{"pushdata-bitcoin":98,"varuint-bitcoin":114}],47:[function(require
,module
,exports
){
8978 var createHash
= require('create-hash')
8980 function ripemd160 (buffer
) {
8981 return createHash('rmd160').update(buffer
).digest()
8984 function sha1 (buffer
) {
8985 return createHash('sha1').update(buffer
).digest()
8988 function sha256 (buffer
) {
8989 return createHash('sha256').update(buffer
).digest()
8992 function hash160 (buffer
) {
8993 return ripemd160(sha256(buffer
))
8996 function hash256 (buffer
) {
8997 return sha256(sha256(buffer
))
9003 ripemd160: ripemd160
,
9008 },{"create-hash":85}],48:[function(require
,module
,exports
){
9009 var Buffer
= require('safe-buffer').Buffer
9010 var createHmac
= require('create-hmac')
9011 var typeforce
= require('typeforce')
9012 var types
= require('./types')
9014 var BigInteger
= require('bigi')
9015 var ECSignature
= require('./ecsignature')
9017 var ZERO
= Buffer
.alloc(1, 0)
9018 var ONE
= Buffer
.alloc(1, 1)
9020 var ecurve
= require('ecurve')
9021 var secp256k1
= ecurve
.getCurveByName('secp256k1')
9023 // https://tools.ietf.org/html/rfc6979#section-3.2
9024 function deterministicGenerateK (hash
, x
, checkSig
) {
9025 typeforce(types
.tuple(
9031 // Step A, ignored as hash already provided
9034 var k
= Buffer
.alloc(32, 0)
9035 var v
= Buffer
.alloc(32, 1)
9038 k
= createHmac('sha256', k
)
9046 v
= createHmac('sha256', k
).update(v
).digest()
9049 k
= createHmac('sha256', k
)
9057 v
= createHmac('sha256', k
).update(v
).digest()
9059 // Step H1/H2a, ignored as tlen === qlen (256 bit)
9061 v
= createHmac('sha256', k
).update(v
).digest()
9063 var T
= BigInteger
.fromBuffer(v
)
9065 // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA
9066 while (T
.signum() <= 0 || T
.compareTo(secp256k1
.n
) >= 0 || !checkSig(T
)) {
9067 k
= createHmac('sha256', k
)
9072 v
= createHmac('sha256', k
).update(v
).digest()
9074 // Step H1/H2a, again, ignored as tlen === qlen (256 bit)
9076 v
= createHmac('sha256', k
).update(v
).digest()
9077 T
= BigInteger
.fromBuffer(v
)
9083 var N_OVER_TWO
= secp256k1
.n
.shiftRight(1)
9085 function sign (hash
, d
) {
9086 typeforce(types
.tuple(types
.Hash256bit
, types
.BigInt
), arguments
)
9088 var x
= d
.toBuffer(32)
9089 var e
= BigInteger
.fromBuffer(hash
)
9094 deterministicGenerateK(hash
, x
, function (k
) {
9095 var Q
= G
.multiply(k
)
9097 if (secp256k1
.isInfinity(Q
)) return false
9099 r
= Q
.affineX
.mod(n
)
9100 if (r
.signum() === 0) return false
9102 s
= k
.modInverse(n
).multiply(e
.add(d
.multiply(r
))).mod(n
)
9103 if (s
.signum() === 0) return false
9108 // enforce low S values, see bip62: 'low s values in signatures'
9109 if (s
.compareTo(N_OVER_TWO
) > 0) {
9113 return new ECSignature(r
, s
)
9116 function verify (hash
, signature
, Q
) {
9117 typeforce(types
.tuple(
9129 // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1]
9130 if (r
.signum() <= 0 || r
.compareTo(n
) >= 0) return false
9131 if (s
.signum() <= 0 || s
.compareTo(n
) >= 0) return false
9133 // 1.4.2 H = Hash(M), already done by the user
9135 var e
= BigInteger
.fromBuffer(hash
)
9138 var sInv
= s
.modInverse(n
)
9140 // 1.4.4 Compute u1 = es^−1 mod n
9141 // u2 = rs^−1 mod n
9142 var u1
= e
.multiply(sInv
).mod(n
)
9143 var u2
= r
.multiply(sInv
).mod(n
)
9145 // 1.4.5 Compute R = (xR, yR)
9147 var R
= G
.multiplyTwo(u1
, Q
, u2
)
9149 // 1.4.5 (cont.) Enforce R is not at infinity
9150 if (secp256k1
.isInfinity(R
)) return false
9152 // 1.4.6 Convert the field element R.x to an integer
9155 // 1.4.7 Set v = xR mod n
9158 // 1.4.8 If v = r, output "valid", and if v != r, output "invalid"
9163 deterministicGenerateK: deterministicGenerateK
,
9171 },{"./ecsignature":50,"./types":80,"bigi":39,"create-hmac":88,"ecurve":92,"safe-buffer":101,"typeforce":112}],49:[function(require
,module
,exports
){
9172 var baddress
= require('./address')
9173 var bcrypto
= require('./crypto')
9174 var ecdsa
= require('./ecdsa')
9175 var randomBytes
= require('randombytes')
9176 var typeforce
= require('typeforce')
9177 var types
= require('./types')
9178 var wif
= require('wif')
9180 var NETWORKS
= require('./networks')
9181 var BigInteger
= require('bigi')
9183 var ecurve
= require('ecurve')
9184 var secp256k1
= ecdsa
.__curve
9186 function ECPair (d
, Q
, options
) {
9189 compressed: types
.maybe(types
.Boolean
),
9190 network: types
.maybe(types
.Network
)
9194 options
= options
|| {}
9197 if (d
.signum() <= 0) throw new Error('Private key must be greater than 0')
9198 if (d
.compareTo(secp256k1
.n
) >= 0) throw new Error('Private key must be less than the curve order')
9199 if (Q
) throw new TypeError('Unexpected publicKey parameter')
9203 typeforce(types
.ECPoint
, Q
)
9208 this.compressed
= options
.compressed
=== undefined ? true : options
.compressed
9209 this.network
= options
.network
|| NETWORKS
.bitcoin
9212 Object
.defineProperty(ECPair
.prototype, 'Q', {
9214 if (!this.__Q
&& this.d
) {
9215 this.__Q
= secp256k1
.G
.multiply(this.d
)
9222 ECPair
.fromPublicKeyBuffer = function (buffer
, network
) {
9223 var Q
= ecurve
.Point
.decodeFrom(secp256k1
, buffer
)
9225 return new ECPair(null, Q
, {
9226 compressed: Q
.compressed
,
9231 ECPair
.fromWIF = function (string
, network
) {
9232 var decoded
= wif
.decode(string
)
9233 var version
= decoded
.version
9235 // list of networks?
9236 if (types
.Array(network
)) {
9237 network
= network
.filter(function (x
) {
9238 return version
=== x
.wif
9241 if (!network
) throw new Error('Unknown network version')
9243 // otherwise, assume a network object (or default to bitcoin)
9245 network
= network
|| NETWORKS
.bitcoin
9247 if (version
!== network
.wif
) throw new Error('Invalid network version')
9250 var d
= BigInteger
.fromBuffer(decoded
.privateKey
)
9252 return new ECPair(d
, null, {
9253 compressed: decoded
.compressed
,
9258 ECPair
.makeRandom = function (options
) {
9259 options
= options
|| {}
9261 var rng
= options
.rng
|| randomBytes
9265 var buffer
= rng(32)
9266 typeforce(types
.Buffer256bit
, buffer
)
9268 d
= BigInteger
.fromBuffer(buffer
)
9269 } while (d
.signum() <= 0 || d
.compareTo(secp256k1
.n
) >= 0)
9271 return new ECPair(d
, null, options
)
9274 ECPair
.prototype.getAddress = function () {
9275 return baddress
.toBase58Check(bcrypto
.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash
)
9278 ECPair
.prototype.getNetwork = function () {
9282 ECPair
.prototype.getPublicKeyBuffer = function () {
9283 return this.Q
.getEncoded(this.compressed
)
9286 ECPair
.prototype.sign = function (hash
) {
9287 if (!this.d
) throw new Error('Missing private key')
9289 return ecdsa
.sign(hash
, this.d
)
9292 ECPair
.prototype.toWIF = function () {
9293 if (!this.d
) throw new Error('Missing private key')
9295 return wif
.encode(this.network
.wif
, this.d
.toBuffer(32), this.compressed
)
9298 ECPair
.prototype.verify = function (hash
, signature
) {
9299 return ecdsa
.verify(hash
, signature
, this.Q
)
9302 module
.exports
= ECPair
9304 },{"./address":44,"./crypto":47,"./ecdsa":48,"./networks":53,"./types":80,"bigi":39,"ecurve":92,"randombytes":99,"typeforce":112,"wif":115}],50:[function(require
,module
,exports
){
9306 var bip66
= require('bip66')
9307 var typeforce
= require('typeforce')
9308 var types
= require('./types')
9310 var BigInteger
= require('bigi')
9312 function ECSignature (r
, s
) {
9313 typeforce(types
.tuple(types
.BigInt
, types
.BigInt
), arguments
)
9319 ECSignature
.parseCompact = function (buffer
) {
9320 typeforce(types
.BufferN(65), buffer
)
9322 var flagByte
= buffer
.readUInt8(0) - 27
9323 if (flagByte
!== (flagByte
& 7)) throw new Error('Invalid signature parameter')
9325 var compressed
= !!(flagByte
& 4)
9326 var recoveryParam
= flagByte
& 3
9327 var signature
= ECSignature
.fromRSBuffer(buffer
.slice(1))
9330 compressed: compressed
,
9332 signature: signature
9336 ECSignature
.fromRSBuffer = function (buffer
) {
9337 typeforce(types
.BufferN(64), buffer
)
9339 var r
= BigInteger
.fromBuffer(buffer
.slice(0, 32))
9340 var s
= BigInteger
.fromBuffer(buffer
.slice(32, 64))
9341 return new ECSignature(r
, s
)
9344 ECSignature
.fromDER = function (buffer
) {
9345 var decode
= bip66
.decode(buffer
)
9346 var r
= BigInteger
.fromDERInteger(decode
.r
)
9347 var s
= BigInteger
.fromDERInteger(decode
.s
)
9349 return new ECSignature(r
, s
)
9352 // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed)
9353 ECSignature
.parseScriptSignature = function (buffer
) {
9354 var hashType
= buffer
.readUInt8(buffer
.length
- 1)
9355 var hashTypeMod
= hashType
& ~0x80
9357 if (hashTypeMod
<= 0x00 || hashTypeMod
>= 0x04) throw new Error('Invalid hashType ' + hashType
)
9360 signature: ECSignature
.fromDER(buffer
.slice(0, -1)),
9365 ECSignature
.prototype.toCompact = function (i
, compressed
) {
9372 var buffer
= Buffer
.alloc(65)
9373 buffer
.writeUInt8(i
, 0)
9374 this.toRSBuffer(buffer
, 1)
9378 ECSignature
.prototype.toDER = function () {
9379 var r
= Buffer
.from(this.r
.toDERInteger())
9380 var s
= Buffer
.from(this.s
.toDERInteger())
9382 return bip66
.encode(r
, s
)
9385 ECSignature
.prototype.toRSBuffer = function (buffer
, offset
) {
9386 buffer
= buffer
|| Buffer
.alloc(64)
9387 this.r
.toBuffer(32).copy(buffer
, offset
)
9388 this.s
.toBuffer(32).copy(buffer
, offset
+ 32)
9392 ECSignature
.prototype.toScriptSignature = function (hashType
) {
9393 var hashTypeMod
= hashType
& ~0x80
9394 if (hashTypeMod
<= 0 || hashTypeMod
>= 4) throw new Error('Invalid hashType ' + hashType
)
9396 var hashTypeBuffer
= Buffer
.alloc(1)
9397 hashTypeBuffer
.writeUInt8(hashType
, 0)
9399 return Buffer
.concat([this.toDER(), hashTypeBuffer
])
9402 module
.exports
= ECSignature
9404 }).call(this,require("buffer").Buffer
)
9405 },{"./types":80,"bigi":39,"bip66":41,"buffer":5,"typeforce":112}],51:[function(require
,module
,exports
){
9406 var Buffer
= require('safe-buffer').Buffer
9407 var base58check
= require('bs58check')
9408 var bcrypto
= require('./crypto')
9409 var createHmac
= require('create-hmac')
9410 var typeforce
= require('typeforce')
9411 var types
= require('./types')
9412 var NETWORKS
= require('./networks')
9414 var BigInteger
= require('bigi')
9415 var ECPair
= require('./ecpair')
9417 var ecurve
= require('ecurve')
9418 var curve
= ecurve
.getCurveByName('secp256k1')
9420 function HDNode (keyPair
, chainCode
) {
9421 typeforce(types
.tuple('ECPair', types
.Buffer256bit
), arguments
)
9423 if (!keyPair
.compressed
) throw new TypeError('BIP32 only allows compressed keyPairs')
9425 this.keyPair
= keyPair
9426 this.chainCode
= chainCode
9429 this.parentFingerprint
= 0x00000000
9432 HDNode
.HIGHEST_BIT
= 0x80000000
9434 HDNode
.MASTER_SECRET
= Buffer
.from('Bitcoin seed', 'utf8')
9436 HDNode
.fromSeedBuffer = function (seed
, network
) {
9437 typeforce(types
.tuple(types
.Buffer
, types
.maybe(types
.Network
)), arguments
)
9439 if (seed
.length
< 16) throw new TypeError('Seed should be at least 128 bits')
9440 if (seed
.length
> 64) throw new TypeError('Seed should be at most 512 bits')
9442 var I
= createHmac('sha512', HDNode
.MASTER_SECRET
).update(seed
).digest()
9443 var IL
= I
.slice(0, 32)
9444 var IR
= I
.slice(32)
9446 // In case IL is 0 or >= n, the master key is invalid
9447 // This is handled by the ECPair constructor
9448 var pIL
= BigInteger
.fromBuffer(IL
)
9449 var keyPair
= new ECPair(pIL
, null, {
9453 return new HDNode(keyPair
, IR
)
9456 HDNode
.fromSeedHex = function (hex
, network
) {
9457 return HDNode
.fromSeedBuffer(Buffer
.from(hex
, 'hex'), network
)
9460 HDNode
.fromBase58 = function (string
, networks
) {
9461 var buffer
= base58check
.decode(string
)
9462 if (buffer
.length
!== 78) throw new Error('Invalid buffer length')
9464 // 4 bytes: version bytes
9465 var version
= buffer
.readUInt32BE(0)
9468 // list of networks?
9469 if (Array
.isArray(networks
)) {
9470 network
= networks
.filter(function (x
) {
9471 return version
=== x
.bip32
.private ||
9472 version
=== x
.bip32
.public
9475 if (!network
) throw new Error('Unknown network version')
9477 // otherwise, assume a network object (or default to bitcoin)
9479 network
= networks
|| NETWORKS
.bitcoin
9482 if (version
!== network
.bip32
.private &&
9483 version
!== network
.bip32
.public) throw new Error('Invalid network version')
9485 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ...
9486 var depth
= buffer
[4]
9488 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9489 var parentFingerprint
= buffer
.readUInt32BE(5)
9491 if (parentFingerprint
!== 0x00000000) throw new Error('Invalid parent fingerprint')
9494 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9495 // This is encoded in MSB order. (0x00000000 if master key)
9496 var index
= buffer
.readUInt32BE(9)
9497 if (depth
=== 0 && index
!== 0) throw new Error('Invalid index')
9499 // 32 bytes: the chain code
9500 var chainCode
= buffer
.slice(13, 45)
9503 // 33 bytes: private key data (0x00 + k)
9504 if (version
=== network
.bip32
.private) {
9505 if (buffer
.readUInt8(45) !== 0x00) throw new Error('Invalid private key')
9507 var d
= BigInteger
.fromBuffer(buffer
.slice(46, 78))
9508 keyPair
= new ECPair(d
, null, { network: network
})
9510 // 33 bytes: public key data (0x02 + X or 0x03 + X)
9512 var Q
= ecurve
.Point
.decodeFrom(curve
, buffer
.slice(45, 78))
9513 // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw
9515 // Verify that the X coordinate in the public point corresponds to a point on the curve.
9516 // If not, the extended public key is invalid.
9519 keyPair
= new ECPair(null, Q
, { network: network
})
9522 var hd
= new HDNode(keyPair
, chainCode
)
9525 hd
.parentFingerprint
= parentFingerprint
9530 HDNode
.prototype.getAddress = function () {
9531 return this.keyPair
.getAddress()
9534 HDNode
.prototype.getIdentifier = function () {
9535 return bcrypto
.hash160(this.keyPair
.getPublicKeyBuffer())
9538 HDNode
.prototype.getFingerprint = function () {
9539 return this.getIdentifier().slice(0, 4)
9542 HDNode
.prototype.getNetwork = function () {
9543 return this.keyPair
.getNetwork()
9546 HDNode
.prototype.getPublicKeyBuffer = function () {
9547 return this.keyPair
.getPublicKeyBuffer()
9550 HDNode
.prototype.neutered = function () {
9551 var neuteredKeyPair
= new ECPair(null, this.keyPair
.Q
, {
9552 network: this.keyPair
.network
9555 var neutered
= new HDNode(neuteredKeyPair
, this.chainCode
)
9556 neutered
.depth
= this.depth
9557 neutered
.index
= this.index
9558 neutered
.parentFingerprint
= this.parentFingerprint
9563 HDNode
.prototype.sign = function (hash
) {
9564 return this.keyPair
.sign(hash
)
9567 HDNode
.prototype.verify = function (hash
, signature
) {
9568 return this.keyPair
.verify(hash
, signature
)
9571 HDNode
.prototype.toBase58 = function (__isPrivate
) {
9572 if (__isPrivate
!== undefined) throw new TypeError('Unsupported argument in 2.0.0')
9575 var network
= this.keyPair
.network
9576 var version
= (!this.isNeutered()) ? network
.bip32
.private : network
.bip32
.public
9577 var buffer
= Buffer
.allocUnsafe(78)
9579 // 4 bytes: version bytes
9580 buffer
.writeUInt32BE(version
, 0)
9582 // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ....
9583 buffer
.writeUInt8(this.depth
, 4)
9585 // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key)
9586 buffer
.writeUInt32BE(this.parentFingerprint
, 5)
9588 // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized.
9589 // This is encoded in big endian. (0x00000000 if master key)
9590 buffer
.writeUInt32BE(this.index
, 9)
9592 // 32 bytes: the chain code
9593 this.chainCode
.copy(buffer
, 13)
9595 // 33 bytes: the public key or private key data
9596 if (!this.isNeutered()) {
9597 // 0x00 + k for private keys
9598 buffer
.writeUInt8(0, 45)
9599 this.keyPair
.d
.toBuffer(32).copy(buffer
, 46)
9601 // 33 bytes: the public key
9603 // X9.62 encoding for public keys
9604 this.keyPair
.getPublicKeyBuffer().copy(buffer
, 45)
9607 return base58check
.encode(buffer
)
9610 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions
9611 HDNode
.prototype.derive = function (index
) {
9612 typeforce(types
.UInt32
, index
)
9614 var isHardened
= index
>= HDNode
.HIGHEST_BIT
9615 var data
= Buffer
.allocUnsafe(37)
9619 if (this.isNeutered()) throw new TypeError('Could not derive hardened child key')
9621 // data = 0x00 || ser256(kpar) || ser32(index)
9623 this.keyPair
.d
.toBuffer(32).copy(data
, 1)
9624 data
.writeUInt32BE(index
, 33)
9628 // data = serP(point(kpar)) || ser32(index)
9629 // = serP(Kpar) || ser32(index)
9630 this.keyPair
.getPublicKeyBuffer().copy(data
, 0)
9631 data
.writeUInt32BE(index
, 33)
9634 var I
= createHmac('sha512', this.chainCode
).update(data
).digest()
9635 var IL
= I
.slice(0, 32)
9636 var IR
= I
.slice(32)
9638 var pIL
= BigInteger
.fromBuffer(IL
)
9640 // In case parse256(IL) >= n, proceed with the next value for i
9641 if (pIL
.compareTo(curve
.n
) >= 0) {
9642 return this.derive(index
+ 1)
9645 // Private parent key -> private child key
9647 if (!this.isNeutered()) {
9648 // ki = parse256(IL) + kpar (mod n)
9649 var ki
= pIL
.add(this.keyPair
.d
).mod(curve
.n
)
9651 // In case ki == 0, proceed with the next value for i
9652 if (ki
.signum() === 0) {
9653 return this.derive(index
+ 1)
9656 derivedKeyPair
= new ECPair(ki
, null, {
9657 network: this.keyPair
.network
9660 // Public parent key -> public child key
9662 // Ki = point(parse256(IL)) + Kpar
9664 var Ki
= curve
.G
.multiply(pIL
).add(this.keyPair
.Q
)
9666 // In case Ki is the point at infinity, proceed with the next value for i
9667 if (curve
.isInfinity(Ki
)) {
9668 return this.derive(index
+ 1)
9671 derivedKeyPair
= new ECPair(null, Ki
, {
9672 network: this.keyPair
.network
9676 var hd
= new HDNode(derivedKeyPair
, IR
)
9677 hd
.depth
= this.depth
+ 1
9679 hd
.parentFingerprint
= this.getFingerprint().readUInt32BE(0)
9684 HDNode
.prototype.deriveHardened = function (index
) {
9685 typeforce(types
.UInt31
, index
)
9687 // Only derives hardened private keys by default
9688 return this.derive(index
+ HDNode
.HIGHEST_BIT
)
9691 // Private === not neutered
9692 // Public === neutered
9693 HDNode
.prototype.isNeutered = function () {
9694 return !(this.keyPair
.d
)
9697 HDNode
.prototype.derivePath = function (path
) {
9698 typeforce(types
.BIP32Path
, path
)
9700 var splitPath
= path
.split('/')
9701 if (splitPath
[0] === 'm') {
9702 if (this.parentFingerprint
) {
9703 throw new Error('Not a master node')
9706 splitPath
= splitPath
.slice(1)
9709 return splitPath
.reduce(function (prevHd
, indexStr
) {
9711 if (indexStr
.slice(-1) === "'") {
9712 index
= parseInt(indexStr
.slice(0, -1), 10)
9713 return prevHd
.deriveHardened(index
)
9715 index
= parseInt(indexStr
, 10)
9716 return prevHd
.derive(index
)
9721 module
.exports
= HDNode
9723 },{"./crypto":47,"./ecpair":49,"./networks":53,"./types":80,"bigi":39,"bs58check":83,"create-hmac":88,"ecurve":92,"safe-buffer":101,"typeforce":112}],52:[function(require
,module
,exports
){
9724 var script
= require('./script')
9726 var templates
= require('./templates')
9727 for (var key
in templates
) {
9728 script
[key
] = templates
[key
]
9732 bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0
9734 Block: require('./block'),
9735 ECPair: require('./ecpair'),
9736 ECSignature: require('./ecsignature'),
9737 HDNode: require('./hdnode'),
9738 Transaction: require('./transaction'),
9739 TransactionBuilder: require('./transaction_builder'),
9741 address: require('./address'),
9742 crypto: require('./crypto'),
9743 networks: require('./networks'),
9744 opcodes: require('bitcoin-ops'),
9748 },{"./address":44,"./block":45,"./bufferutils":46,"./crypto":47,"./ecpair":49,"./ecsignature":50,"./hdnode":51,"./networks":53,"./script":54,"./templates":56,"./transaction":78,"./transaction_builder":79,"bitcoin-ops":42}],53:[function(require
,module
,exports
){
9749 // https://en.bitcoin.it/wiki/List_of_address_prefixes
9750 // Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731
9754 messagePrefix: '\x18Bitcoin Signed Message:\n',
9765 messagePrefix: '\x18Bitcoin Signed Message:\n',
9776 messagePrefix: '\x19Litecoin Signed Message:\n',
9787 },{}],54:[function(require
,module
,exports
){
9788 var Buffer
= require('safe-buffer').Buffer
9789 var bip66
= require('bip66')
9790 var pushdata
= require('pushdata-bitcoin')
9791 var typeforce
= require('typeforce')
9792 var types
= require('./types')
9793 var scriptNumber
= require('./script_number')
9795 var OPS
= require('bitcoin-ops')
9796 var REVERSE_OPS
= require('bitcoin-ops/map')
9797 var OP_INT_BASE
= OPS
.OP_RESERVED
// OP_1 - 1
9799 function isOPInt (value
) {
9800 return types
.Number(value
) &&
9801 ((value
=== OPS
.OP_0
) ||
9802 (value
>= OPS
.OP_1
&& value
<= OPS
.OP_16
) ||
9803 (value
=== OPS
.OP_1NEGATE
))
9806 function isPushOnlyChunk (value
) {
9807 return types
.Buffer(value
) || isOPInt(value
)
9810 function isPushOnly (value
) {
9811 return types
.Array(value
) && value
.every(isPushOnlyChunk
)
9814 function asMinimalOP (buffer
) {
9815 if (buffer
.length
=== 0) return OPS
.OP_0
9816 if (buffer
.length
!== 1) return
9817 if (buffer
[0] >= 1 && buffer
[0] <= 16) return OP_INT_BASE
+ buffer
[0]
9818 if (buffer
[0] === 0x81) return OPS
.OP_1NEGATE
9821 function compile (chunks
) {
9823 if (Buffer
.isBuffer(chunks
)) return chunks
9825 typeforce(types
.Array
, chunks
)
9827 var bufferSize
= chunks
.reduce(function (accum
, chunk
) {
9829 if (Buffer
.isBuffer(chunk
)) {
9830 // adhere to BIP62.3, minimal push policy
9831 if (chunk
.length
=== 1 && asMinimalOP(chunk
) !== undefined) {
9835 return accum
+ pushdata
.encodingLength(chunk
.length
) + chunk
.length
9842 var buffer
= Buffer
.allocUnsafe(bufferSize
)
9845 chunks
.forEach(function (chunk
) {
9847 if (Buffer
.isBuffer(chunk
)) {
9848 // adhere to BIP62.3, minimal push policy
9849 var opcode
= asMinimalOP(chunk
)
9850 if (opcode
!== undefined) {
9851 buffer
.writeUInt8(opcode
, offset
)
9856 offset
+= pushdata
.encode(buffer
, chunk
.length
, offset
)
9857 chunk
.copy(buffer
, offset
)
9858 offset
+= chunk
.length
9862 buffer
.writeUInt8(chunk
, offset
)
9867 if (offset
!== buffer
.length
) throw new Error('Could not decode chunks')
9871 function decompile (buffer
) {
9873 if (types
.Array(buffer
)) return buffer
9875 typeforce(types
.Buffer
, buffer
)
9880 while (i
< buffer
.length
) {
9881 var opcode
= buffer
[i
]
9884 if ((opcode
> OPS
.OP_0
) && (opcode
<= OPS
.OP_PUSHDATA4
)) {
9885 var d
= pushdata
.decode(buffer
, i
)
9887 // did reading a pushDataInt fail? empty script
9888 if (d
=== null) return []
9891 // attempt to read too much data? empty script
9892 if (i
+ d
.number
> buffer
.length
) return []
9894 var data
= buffer
.slice(i
, i
+ d
.number
)
9897 // decompile minimally
9898 var op
= asMinimalOP(data
)
9899 if (op
!== undefined) {
9916 function toASM (chunks
) {
9917 if (Buffer
.isBuffer(chunks
)) {
9918 chunks
= decompile(chunks
)
9921 return chunks
.map(function (chunk
) {
9923 if (Buffer
.isBuffer(chunk
)) {
9924 var op
= asMinimalOP(chunk
)
9925 if (op
=== undefined) return chunk
.toString('hex')
9930 return REVERSE_OPS
[chunk
]
9934 function fromASM (asm
) {
9935 typeforce(types
.String
, asm
)
9937 return compile(asm
.split(' ').map(function (chunkStr
) {
9939 if (OPS
[chunkStr
] !== undefined) return OPS
[chunkStr
]
9940 typeforce(types
.Hex
, chunkStr
)
9943 return Buffer
.from(chunkStr
, 'hex')
9947 function toStack (chunks
) {
9948 chunks
= decompile(chunks
)
9949 typeforce(isPushOnly
, chunks
)
9951 return chunks
.map(function (op
) {
9952 if (Buffer
.isBuffer(op
)) return op
9953 if (op
=== OPS
.OP_0
) return Buffer
.allocUnsafe(0)
9955 return scriptNumber
.encode(op
- OP_INT_BASE
)
9959 function isCanonicalPubKey (buffer
) {
9960 if (!Buffer
.isBuffer(buffer
)) return false
9961 if (buffer
.length
< 33) return false
9963 switch (buffer
[0]) {
9966 return buffer
.length
=== 33
9968 return buffer
.length
=== 65
9974 function isDefinedHashType (hashType
) {
9975 var hashTypeMod
= hashType
& ~0x80
9977 // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE
9978 return hashTypeMod
> 0x00 && hashTypeMod
< 0x04
9981 function isCanonicalSignature (buffer
) {
9982 if (!Buffer
.isBuffer(buffer
)) return false
9983 if (!isDefinedHashType(buffer
[buffer
.length
- 1])) return false
9985 return bip66
.check(buffer
.slice(0, -1))
9990 decompile: decompile
,
9995 number: require('./script_number'),
9997 isCanonicalPubKey: isCanonicalPubKey
,
9998 isCanonicalSignature: isCanonicalSignature
,
9999 isPushOnly: isPushOnly
,
10000 isDefinedHashType: isDefinedHashType
10003 },{"./script_number":55,"./types":80,"bip66":41,"bitcoin-ops":42,"bitcoin-ops/map":43,"pushdata-bitcoin":98,"safe-buffer":101,"typeforce":112}],55:[function(require
,module
,exports
){
10004 var Buffer
= require('safe-buffer').Buffer
10006 function decode (buffer
, maxLength
, minimal
) {
10007 maxLength
= maxLength
|| 4
10008 minimal
= minimal
=== undefined ? true : minimal
10010 var length
= buffer
.length
10011 if (length
=== 0) return 0
10012 if (length
> maxLength
) throw new TypeError('Script number overflow')
10014 if ((buffer
[length
- 1] & 0x7f) === 0) {
10015 if (length
<= 1 || (buffer
[length
- 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number')
10020 if (length
=== 5) {
10021 var a
= buffer
.readUInt32LE(0)
10022 var b
= buffer
.readUInt8(4)
10024 if (b
& 0x80) return -(((b
& ~0x80) * 0x100000000) + a
)
10025 return (b
* 0x100000000) + a
10030 // 32-bit / 24-bit / 16-bit / 8-bit
10031 for (var i
= 0; i
< length
; ++i
) {
10032 result
|= buffer
[i
] << (8 * i
)
10035 if (buffer
[length
- 1] & 0x80) return -(result
& ~(0x80 << (8 * (length
- 1))))
10039 function scriptNumSize (i
) {
10040 return i
> 0x7fffffff ? 5
10048 function encode (number
) {
10049 var value
= Math
.abs(number
)
10050 var size
= scriptNumSize(value
)
10051 var buffer
= Buffer
.allocUnsafe(size
)
10052 var negative
= number
< 0
10054 for (var i
= 0; i
< size
; ++i
) {
10055 buffer
.writeUInt8(value
& 0xff, i
)
10059 if (buffer
[size
- 1] & 0x80) {
10060 buffer
.writeUInt8(negative
? 0x80 : 0x00, size
- 1)
10061 } else if (negative
) {
10062 buffer
[size
- 1] |= 0x80
10073 },{"safe-buffer":101}],56:[function(require
,module
,exports
){
10074 var decompile
= require('../script').decompile
10075 var multisig
= require('./multisig')
10076 var nullData
= require('./nulldata')
10077 var pubKey
= require('./pubkey')
10078 var pubKeyHash
= require('./pubkeyhash')
10079 var scriptHash
= require('./scripthash')
10080 var witnessPubKeyHash
= require('./witnesspubkeyhash')
10081 var witnessScriptHash
= require('./witnessscripthash')
10082 var witnessCommitment
= require('./witnesscommitment')
10085 MULTISIG: 'multisig',
10086 NONSTANDARD: 'nonstandard',
10087 NULLDATA: 'nulldata',
10089 P2PKH: 'pubkeyhash',
10090 P2SH: 'scripthash',
10091 P2WPKH: 'witnesspubkeyhash',
10092 P2WSH: 'witnessscripthash',
10093 WITNESS_COMMITMENT: 'witnesscommitment'
10096 function classifyOutput (script
) {
10097 if (witnessPubKeyHash
.output
.check(script
)) return types
.P2WPKH
10098 if (witnessScriptHash
.output
.check(script
)) return types
.P2WSH
10099 if (pubKeyHash
.output
.check(script
)) return types
.P2PKH
10100 if (scriptHash
.output
.check(script
)) return types
.P2SH
10102 // XXX: optimization, below functions .decompile before use
10103 var chunks
= decompile(script
)
10104 if (multisig
.output
.check(chunks
)) return types
.MULTISIG
10105 if (pubKey
.output
.check(chunks
)) return types
.P2PK
10106 if (witnessCommitment
.output
.check(chunks
)) return types
.WITNESS_COMMITMENT
10107 if (nullData
.output
.check(chunks
)) return types
.NULLDATA
10109 return types
.NONSTANDARD
10112 function classifyInput (script
, allowIncomplete
) {
10113 // XXX: optimization, below functions .decompile before use
10114 var chunks
= decompile(script
)
10116 if (pubKeyHash
.input
.check(chunks
)) return types
.P2PKH
10117 if (scriptHash
.input
.check(chunks
, allowIncomplete
)) return types
.P2SH
10118 if (multisig
.input
.check(chunks
, allowIncomplete
)) return types
.MULTISIG
10119 if (pubKey
.input
.check(chunks
)) return types
.P2PK
10121 return types
.NONSTANDARD
10124 function classifyWitness (script
, allowIncomplete
) {
10125 // XXX: optimization, below functions .decompile before use
10126 var chunks
= decompile(script
)
10128 if (witnessPubKeyHash
.input
.check(chunks
)) return types
.P2WPKH
10129 if (witnessScriptHash
.input
.check(chunks
, allowIncomplete
)) return types
.P2WSH
10131 return types
.NONSTANDARD
10135 classifyInput: classifyInput
,
10136 classifyOutput: classifyOutput
,
10137 classifyWitness: classifyWitness
,
10138 multisig: multisig
,
10139 nullData: nullData
,
10141 pubKeyHash: pubKeyHash
,
10142 scriptHash: scriptHash
,
10143 witnessPubKeyHash: witnessPubKeyHash
,
10144 witnessScriptHash: witnessScriptHash
,
10145 witnessCommitment: witnessCommitment
,
10149 },{"../script":54,"./multisig":57,"./nulldata":60,"./pubkey":61,"./pubkeyhash":64,"./scripthash":67,"./witnesscommitment":70,"./witnesspubkeyhash":72,"./witnessscripthash":75}],57:[function(require
,module
,exports
){
10151 input: require('./input'),
10152 output: require('./output')
10155 },{"./input":58,"./output":59}],58:[function(require
,module
,exports
){
10156 // OP_0 [signatures ...]
10158 var Buffer
= require('safe-buffer').Buffer
10159 var bscript
= require('../../script')
10160 var p2mso
= require('./output')
10161 var typeforce
= require('typeforce')
10162 var OPS
= require('bitcoin-ops')
10164 function partialSignature (value
) {
10165 return value
=== OPS
.OP_0
|| bscript
.isCanonicalSignature(value
)
10168 function check (script
, allowIncomplete
) {
10169 var chunks
= bscript
.decompile(script
)
10170 if (chunks
.length
< 2) return false
10171 if (chunks
[0] !== OPS
.OP_0
) return false
10173 if (allowIncomplete
) {
10174 return chunks
.slice(1).every(partialSignature
)
10177 return chunks
.slice(1).every(bscript
.isCanonicalSignature
)
10179 check
.toJSON = function () { return 'multisig input' }
10181 var EMPTY_BUFFER
= Buffer
.allocUnsafe(0)
10183 function encodeStack (signatures
, scriptPubKey
) {
10184 typeforce([partialSignature
], signatures
)
10186 if (scriptPubKey
) {
10187 var scriptData
= p2mso
.decode(scriptPubKey
)
10189 if (signatures
.length
< scriptData
.m
) {
10190 throw new TypeError('Not enough signatures provided')
10193 if (signatures
.length
> scriptData
.pubKeys
.length
) {
10194 throw new TypeError('Too many signatures provided')
10198 return [].concat(EMPTY_BUFFER
, signatures
.map(function (sig
) {
10199 if (sig
=== OPS
.OP_0
) {
10200 return EMPTY_BUFFER
10206 function encode (signatures
, scriptPubKey
) {
10207 return bscript
.compile(encodeStack(signatures
, scriptPubKey
))
10210 function decodeStack (stack
, allowIncomplete
) {
10211 typeforce(typeforce
.Array
, stack
)
10212 typeforce(check
, stack
, allowIncomplete
)
10213 return stack
.slice(1)
10216 function decode (buffer
, allowIncomplete
) {
10217 var stack
= bscript
.decompile(buffer
)
10218 return decodeStack(stack
, allowIncomplete
)
10224 decodeStack: decodeStack
,
10226 encodeStack: encodeStack
10229 },{"../../script":54,"./output":59,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],59:[function(require
,module
,exports
){
10230 // m [pubKeys ...] n OP_CHECKMULTISIG
10232 var bscript
= require('../../script')
10233 var types
= require('../../types')
10234 var typeforce
= require('typeforce')
10235 var OPS
= require('bitcoin-ops')
10236 var OP_INT_BASE
= OPS
.OP_RESERVED
// OP_1 - 1
10238 function check (script
, allowIncomplete
) {
10239 var chunks
= bscript
.decompile(script
)
10241 if (chunks
.length
< 4) return false
10242 if (chunks
[chunks
.length
- 1] !== OPS
.OP_CHECKMULTISIG
) return false
10243 if (!types
.Number(chunks
[0])) return false
10244 if (!types
.Number(chunks
[chunks
.length
- 2])) return false
10245 var m
= chunks
[0] - OP_INT_BASE
10246 var n
= chunks
[chunks
.length
- 2] - OP_INT_BASE
10248 if (m
<= 0) return false
10249 if (n
> 16) return false
10250 if (m
> n
) return false
10251 if (n
!== chunks
.length
- 3) return false
10252 if (allowIncomplete
) return true
10254 var keys
= chunks
.slice(1, -2)
10255 return keys
.every(bscript
.isCanonicalPubKey
)
10257 check
.toJSON = function () { return 'multi-sig output' }
10259 function encode (m
, pubKeys
) {
10262 pubKeys: [bscript
.isCanonicalPubKey
]
10268 var n
= pubKeys
.length
10269 if (n
< m
) throw new TypeError('Not enough pubKeys provided')
10271 return bscript
.compile([].concat(
10275 OPS
.OP_CHECKMULTISIG
10279 function decode (buffer
, allowIncomplete
) {
10280 var chunks
= bscript
.decompile(buffer
)
10281 typeforce(check
, chunks
, allowIncomplete
)
10284 m: chunks
[0] - OP_INT_BASE
,
10285 pubKeys: chunks
.slice(1, -2)
10295 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],60:[function(require
,module
,exports
){
10296 // OP_RETURN {data}
10298 var bscript
= require('../script')
10299 var types
= require('../types')
10300 var typeforce
= require('typeforce')
10301 var OPS
= require('bitcoin-ops')
10303 function check (script
) {
10304 var buffer
= bscript
.compile(script
)
10306 return buffer
.length
> 1 &&
10307 buffer
[0] === OPS
.OP_RETURN
10309 check
.toJSON = function () { return 'null data output' }
10311 function encode (data
) {
10312 typeforce(types
.Buffer
, data
)
10314 return bscript
.compile([OPS
.OP_RETURN
, data
])
10317 function decode (buffer
) {
10318 typeforce(check
, buffer
)
10320 return buffer
.slice(2)
10331 },{"../script":54,"../types":80,"bitcoin-ops":42,"typeforce":112}],61:[function(require
,module
,exports
){
10332 arguments
[4][57][0].apply(exports
,arguments
)
10333 },{"./input":62,"./output":63,"dup":57}],62:[function(require
,module
,exports
){
10336 var bscript
= require('../../script')
10337 var typeforce
= require('typeforce')
10339 function check (script
) {
10340 var chunks
= bscript
.decompile(script
)
10342 return chunks
.length
=== 1 &&
10343 bscript
.isCanonicalSignature(chunks
[0])
10345 check
.toJSON = function () { return 'pubKey input' }
10347 function encodeStack (signature
) {
10348 typeforce(bscript
.isCanonicalSignature
, signature
)
10352 function encode (signature
) {
10353 return bscript
.compile(encodeStack(signature
))
10356 function decodeStack (stack
) {
10357 typeforce(typeforce
.Array
, stack
)
10358 typeforce(check
, stack
)
10362 function decode (buffer
) {
10363 var stack
= bscript
.decompile(buffer
)
10364 return decodeStack(stack
)
10370 decodeStack: decodeStack
,
10372 encodeStack: encodeStack
10375 },{"../../script":54,"typeforce":112}],63:[function(require
,module
,exports
){
10376 // {pubKey} OP_CHECKSIG
10378 var bscript
= require('../../script')
10379 var typeforce
= require('typeforce')
10380 var OPS
= require('bitcoin-ops')
10382 function check (script
) {
10383 var chunks
= bscript
.decompile(script
)
10385 return chunks
.length
=== 2 &&
10386 bscript
.isCanonicalPubKey(chunks
[0]) &&
10387 chunks
[1] === OPS
.OP_CHECKSIG
10389 check
.toJSON = function () { return 'pubKey output' }
10391 function encode (pubKey
) {
10392 typeforce(bscript
.isCanonicalPubKey
, pubKey
)
10394 return bscript
.compile([pubKey
, OPS
.OP_CHECKSIG
])
10397 function decode (buffer
) {
10398 var chunks
= bscript
.decompile(buffer
)
10399 typeforce(check
, chunks
)
10410 },{"../../script":54,"bitcoin-ops":42,"typeforce":112}],64:[function(require
,module
,exports
){
10411 arguments
[4][57][0].apply(exports
,arguments
)
10412 },{"./input":65,"./output":66,"dup":57}],65:[function(require
,module
,exports
){
10413 // {signature} {pubKey}
10415 var bscript
= require('../../script')
10416 var typeforce
= require('typeforce')
10418 function check (script
) {
10419 var chunks
= bscript
.decompile(script
)
10421 return chunks
.length
=== 2 &&
10422 bscript
.isCanonicalSignature(chunks
[0]) &&
10423 bscript
.isCanonicalPubKey(chunks
[1])
10425 check
.toJSON = function () { return 'pubKeyHash input' }
10427 function encodeStack (signature
, pubKey
) {
10429 signature: bscript
.isCanonicalSignature
,
10430 pubKey: bscript
.isCanonicalPubKey
10432 signature: signature
,
10436 return [signature
, pubKey
]
10439 function encode (signature
, pubKey
) {
10440 return bscript
.compile(encodeStack(signature
, pubKey
))
10443 function decodeStack (stack
) {
10444 typeforce(typeforce
.Array
, stack
)
10445 typeforce(check
, stack
)
10448 signature: stack
[0],
10453 function decode (buffer
) {
10454 var stack
= bscript
.decompile(buffer
)
10455 return decodeStack(stack
)
10461 decodeStack: decodeStack
,
10463 encodeStack: encodeStack
10466 },{"../../script":54,"typeforce":112}],66:[function(require
,module
,exports
){
10467 // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG
10469 var bscript
= require('../../script')
10470 var types
= require('../../types')
10471 var typeforce
= require('typeforce')
10472 var OPS
= require('bitcoin-ops')
10474 function check (script
) {
10475 var buffer
= bscript
.compile(script
)
10477 return buffer
.length
=== 25 &&
10478 buffer
[0] === OPS
.OP_DUP
&&
10479 buffer
[1] === OPS
.OP_HASH160
&&
10480 buffer
[2] === 0x14 &&
10481 buffer
[23] === OPS
.OP_EQUALVERIFY
&&
10482 buffer
[24] === OPS
.OP_CHECKSIG
10484 check
.toJSON = function () { return 'pubKeyHash output' }
10486 function encode (pubKeyHash
) {
10487 typeforce(types
.Hash160bit
, pubKeyHash
)
10489 return bscript
.compile([
10493 OPS
.OP_EQUALVERIFY
,
10498 function decode (buffer
) {
10499 typeforce(check
, buffer
)
10501 return buffer
.slice(3, 23)
10510 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],67:[function(require
,module
,exports
){
10511 arguments
[4][57][0].apply(exports
,arguments
)
10512 },{"./input":68,"./output":69,"dup":57}],68:[function(require
,module
,exports
){
10513 // <scriptSig> {serialized scriptPubKey script}
10515 var Buffer
= require('safe-buffer').Buffer
10516 var bscript
= require('../../script')
10517 var typeforce
= require('typeforce')
10519 var p2ms
= require('../multisig/')
10520 var p2pk
= require('../pubkey/')
10521 var p2pkh
= require('../pubkeyhash/')
10522 var p2wpkho
= require('../witnesspubkeyhash/output')
10523 var p2wsho
= require('../witnessscripthash/output')
10525 function check (script
, allowIncomplete
) {
10526 var chunks
= bscript
.decompile(script
)
10527 if (chunks
.length
< 1) return false
10529 var lastChunk
= chunks
[chunks
.length
- 1]
10530 if (!Buffer
.isBuffer(lastChunk
)) return false
10532 var scriptSigChunks
= bscript
.decompile(bscript
.compile(chunks
.slice(0, -1)))
10533 var redeemScriptChunks
= bscript
.decompile(lastChunk
)
10535 // is redeemScript a valid script?
10536 if (redeemScriptChunks
.length
=== 0) return false
10538 // is redeemScriptSig push only?
10539 if (!bscript
.isPushOnly(scriptSigChunks
)) return false
10542 if (chunks
.length
=== 1) {
10543 return p2wsho
.check(redeemScriptChunks
) ||
10544 p2wpkho
.check(redeemScriptChunks
)
10548 if (p2pkh
.input
.check(scriptSigChunks
) &&
10549 p2pkh
.output
.check(redeemScriptChunks
)) return true
10551 if (p2ms
.input
.check(scriptSigChunks
, allowIncomplete
) &&
10552 p2ms
.output
.check(redeemScriptChunks
)) return true
10554 if (p2pk
.input
.check(scriptSigChunks
) &&
10555 p2pk
.output
.check(redeemScriptChunks
)) return true
10559 check
.toJSON = function () { return 'scriptHash input' }
10561 function encodeStack (redeemScriptStack
, redeemScript
) {
10562 var serializedScriptPubKey
= bscript
.compile(redeemScript
)
10564 return [].concat(redeemScriptStack
, serializedScriptPubKey
)
10567 function encode (redeemScriptSig
, redeemScript
) {
10568 var redeemScriptStack
= bscript
.decompile(redeemScriptSig
)
10570 return bscript
.compile(encodeStack(redeemScriptStack
, redeemScript
))
10573 function decodeStack (stack
) {
10574 typeforce(typeforce
.Array
, stack
)
10575 typeforce(check
, stack
)
10578 redeemScriptStack: stack
.slice(0, -1),
10579 redeemScript: stack
[stack
.length
- 1]
10583 function decode (buffer
) {
10584 var stack
= bscript
.decompile(buffer
)
10585 var result
= decodeStack(stack
)
10586 result
.redeemScriptSig
= bscript
.compile(result
.redeemScriptStack
)
10587 delete result
.redeemScriptStack
10594 decodeStack: decodeStack
,
10596 encodeStack: encodeStack
10599 },{"../../script":54,"../multisig/":57,"../pubkey/":61,"../pubkeyhash/":64,"../witnesspubkeyhash/output":74,"../witnessscripthash/output":77,"safe-buffer":101,"typeforce":112}],69:[function(require
,module
,exports
){
10600 // OP_HASH160 {scriptHash} OP_EQUAL
10602 var bscript
= require('../../script')
10603 var types
= require('../../types')
10604 var typeforce
= require('typeforce')
10605 var OPS
= require('bitcoin-ops')
10607 function check (script
) {
10608 var buffer
= bscript
.compile(script
)
10610 return buffer
.length
=== 23 &&
10611 buffer
[0] === OPS
.OP_HASH160
&&
10612 buffer
[1] === 0x14 &&
10613 buffer
[22] === OPS
.OP_EQUAL
10615 check
.toJSON = function () { return 'scriptHash output' }
10617 function encode (scriptHash
) {
10618 typeforce(types
.Hash160bit
, scriptHash
)
10620 return bscript
.compile([OPS
.OP_HASH160
, scriptHash
, OPS
.OP_EQUAL
])
10623 function decode (buffer
) {
10624 typeforce(check
, buffer
)
10626 return buffer
.slice(2, 22)
10635 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],70:[function(require
,module
,exports
){
10637 output: require('./output')
10640 },{"./output":71}],71:[function(require
,module
,exports
){
10641 // OP_RETURN {aa21a9ed} {commitment}
10643 var Buffer
= require('safe-buffer').Buffer
10644 var bscript
= require('../../script')
10645 var types
= require('../../types')
10646 var typeforce
= require('typeforce')
10647 var OPS
= require('bitcoin-ops')
10649 var HEADER
= Buffer
.from('aa21a9ed', 'hex')
10651 function check (script
) {
10652 var buffer
= bscript
.compile(script
)
10654 return buffer
.length
> 37 &&
10655 buffer
[0] === OPS
.OP_RETURN
&&
10656 buffer
[1] === 0x24 &&
10657 buffer
.slice(2, 6).equals(HEADER
)
10660 check
.toJSON = function () { return 'Witness commitment output' }
10662 function encode (commitment
) {
10663 typeforce(types
.Hash256bit
, commitment
)
10665 var buffer
= Buffer
.allocUnsafe(36)
10666 HEADER
.copy(buffer
, 0)
10667 commitment
.copy(buffer
, 4)
10669 return bscript
.compile([OPS
.OP_RETURN
, buffer
])
10672 function decode (buffer
) {
10673 typeforce(check
, buffer
)
10675 return bscript
.decompile(buffer
)[1].slice(4, 36)
10684 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],72:[function(require
,module
,exports
){
10685 arguments
[4][57][0].apply(exports
,arguments
)
10686 },{"./input":73,"./output":74,"dup":57}],73:[function(require
,module
,exports
){
10687 // {signature} {pubKey}
10689 var bscript
= require('../../script')
10690 var typeforce
= require('typeforce')
10692 function isCompressedCanonicalPubKey (pubKey
) {
10693 return bscript
.isCanonicalPubKey(pubKey
) && pubKey
.length
=== 33
10696 function check (script
) {
10697 var chunks
= bscript
.decompile(script
)
10699 return chunks
.length
=== 2 &&
10700 bscript
.isCanonicalSignature(chunks
[0]) &&
10701 isCompressedCanonicalPubKey(chunks
[1])
10703 check
.toJSON = function () { return 'witnessPubKeyHash input' }
10705 function encodeStack (signature
, pubKey
) {
10707 signature: bscript
.isCanonicalSignature
,
10708 pubKey: isCompressedCanonicalPubKey
10710 signature: signature
,
10714 return [signature
, pubKey
]
10717 function decodeStack (stack
) {
10718 typeforce(typeforce
.Array
, stack
)
10719 typeforce(check
, stack
)
10722 signature: stack
[0],
10729 decodeStack: decodeStack
,
10730 encodeStack: encodeStack
10733 },{"../../script":54,"typeforce":112}],74:[function(require
,module
,exports
){
10734 // OP_0 {pubKeyHash}
10736 var bscript
= require('../../script')
10737 var types
= require('../../types')
10738 var typeforce
= require('typeforce')
10739 var OPS
= require('bitcoin-ops')
10741 function check (script
) {
10742 var buffer
= bscript
.compile(script
)
10744 return buffer
.length
=== 22 &&
10745 buffer
[0] === OPS
.OP_0
&&
10748 check
.toJSON = function () { return 'Witness pubKeyHash output' }
10750 function encode (pubKeyHash
) {
10751 typeforce(types
.Hash160bit
, pubKeyHash
)
10753 return bscript
.compile([OPS
.OP_0
, pubKeyHash
])
10756 function decode (buffer
) {
10757 typeforce(check
, buffer
)
10759 return buffer
.slice(2)
10768 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],75:[function(require
,module
,exports
){
10769 arguments
[4][57][0].apply(exports
,arguments
)
10770 },{"./input":76,"./output":77,"dup":57}],76:[function(require
,module
,exports
){
10771 (function (Buffer
){
10772 // <scriptSig> {serialized scriptPubKey script}
10774 var bscript
= require('../../script')
10775 var types
= require('../../types')
10776 var typeforce
= require('typeforce')
10778 var p2ms
= require('../multisig/')
10779 var p2pk
= require('../pubkey/')
10780 var p2pkh
= require('../pubkeyhash/')
10782 function check (chunks
, allowIncomplete
) {
10783 typeforce(types
.Array
, chunks
)
10784 if (chunks
.length
< 1) return false
10786 var witnessScript
= chunks
[chunks
.length
- 1]
10787 if (!Buffer
.isBuffer(witnessScript
)) return false
10789 var witnessScriptChunks
= bscript
.decompile(witnessScript
)
10791 // is witnessScript a valid script?
10792 if (witnessScriptChunks
.length
=== 0) return false
10794 var witnessRawScriptSig
= bscript
.compile(chunks
.slice(0, -1))
10797 if (p2pkh
.input
.check(witnessRawScriptSig
) &&
10798 p2pkh
.output
.check(witnessScriptChunks
)) return true
10800 if (p2ms
.input
.check(witnessRawScriptSig
, allowIncomplete
) &&
10801 p2ms
.output
.check(witnessScriptChunks
)) return true
10803 if (p2pk
.input
.check(witnessRawScriptSig
) &&
10804 p2pk
.output
.check(witnessScriptChunks
)) return true
10808 check
.toJSON = function () { return 'witnessScriptHash input' }
10810 function encodeStack (witnessData
, witnessScript
) {
10812 witnessData: [types
.Buffer
],
10813 witnessScript: types
.Buffer
10815 witnessData: witnessData
,
10816 witnessScript: witnessScript
10819 return [].concat(witnessData
, witnessScript
)
10822 function decodeStack (stack
) {
10823 typeforce(typeforce
.Array
, stack
)
10824 typeforce(check
, stack
)
10826 witnessData: stack
.slice(0, -1),
10827 witnessScript: stack
[stack
.length
- 1]
10833 decodeStack: decodeStack
,
10834 encodeStack: encodeStack
10837 }).call(this,{"isBuffer":require("../../../../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
10838 },{"../../../../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":10,"../../script":54,"../../types":80,"../multisig/":57,"../pubkey/":61,"../pubkeyhash/":64,"typeforce":112}],77:[function(require
,module
,exports
){
10839 // OP_0 {scriptHash}
10841 var bscript
= require('../../script')
10842 var types
= require('../../types')
10843 var typeforce
= require('typeforce')
10844 var OPS
= require('bitcoin-ops')
10846 function check (script
) {
10847 var buffer
= bscript
.compile(script
)
10849 return buffer
.length
=== 34 &&
10850 buffer
[0] === OPS
.OP_0
&&
10853 check
.toJSON = function () { return 'Witness scriptHash output' }
10855 function encode (scriptHash
) {
10856 typeforce(types
.Hash256bit
, scriptHash
)
10858 return bscript
.compile([OPS
.OP_0
, scriptHash
])
10861 function decode (buffer
) {
10862 typeforce(check
, buffer
)
10864 return buffer
.slice(2)
10873 },{"../../script":54,"../../types":80,"bitcoin-ops":42,"typeforce":112}],78:[function(require
,module
,exports
){
10874 var Buffer
= require('safe-buffer').Buffer
10875 var bcrypto
= require('./crypto')
10876 var bscript
= require('./script')
10877 var bufferutils
= require('./bufferutils')
10878 var opcodes
= require('bitcoin-ops')
10879 var typeforce
= require('typeforce')
10880 var types
= require('./types')
10881 var varuint
= require('varuint-bitcoin')
10883 function varSliceSize (someScript
) {
10884 var length
= someScript
.length
10886 return varuint
.encodingLength(length
) + length
10889 function vectorSize (someVector
) {
10890 var length
= someVector
.length
10892 return varuint
.encodingLength(length
) + someVector
.reduce(function (sum
, witness
) {
10893 return sum
+ varSliceSize(witness
)
10897 function Transaction () {
10904 Transaction
.DEFAULT_SEQUENCE
= 0xffffffff
10905 Transaction
.SIGHASH_ALL
= 0x01
10906 Transaction
.SIGHASH_NONE
= 0x02
10907 Transaction
.SIGHASH_SINGLE
= 0x03
10908 Transaction
.SIGHASH_ANYONECANPAY
= 0x80
10909 Transaction
.ADVANCED_TRANSACTION_MARKER
= 0x00
10910 Transaction
.ADVANCED_TRANSACTION_FLAG
= 0x01
10912 var EMPTY_SCRIPT
= Buffer
.allocUnsafe(0)
10913 var EMPTY_WITNESS
= []
10914 var ZERO
= Buffer
.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
10915 var ONE
= Buffer
.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex')
10916 var VALUE_UINT64_MAX
= Buffer
.from('ffffffffffffffff', 'hex')
10917 var BLANK_OUTPUT
= {
10918 script: EMPTY_SCRIPT
,
10919 valueBuffer: VALUE_UINT64_MAX
10922 Transaction
.fromBuffer = function (buffer
, __noStrict
) {
10924 function readSlice (n
) {
10926 return buffer
.slice(offset
- n
, offset
)
10929 function readUInt32 () {
10930 var i
= buffer
.readUInt32LE(offset
)
10935 function readInt32 () {
10936 var i
= buffer
.readInt32LE(offset
)
10941 function readUInt64 () {
10942 var i
= bufferutils
.readUInt64LE(buffer
, offset
)
10947 function readVarInt () {
10948 var vi
= varuint
.decode(buffer
, offset
)
10949 offset
+= varuint
.decode
.bytes
10953 function readVarSlice () {
10954 return readSlice(readVarInt())
10957 function readVector () {
10958 var count
= readVarInt()
10960 for (var i
= 0; i
< count
; i
++) vector
.push(readVarSlice())
10964 var tx
= new Transaction()
10965 tx
.version
= readInt32()
10967 var marker
= buffer
.readUInt8(offset
)
10968 var flag
= buffer
.readUInt8(offset
+ 1)
10970 var hasWitnesses
= false
10971 if (marker
=== Transaction
.ADVANCED_TRANSACTION_MARKER
&&
10972 flag
=== Transaction
.ADVANCED_TRANSACTION_FLAG
) {
10974 hasWitnesses
= true
10977 var vinLen
= readVarInt()
10978 for (var i
= 0; i
< vinLen
; ++i
) {
10980 hash: readSlice(32),
10981 index: readUInt32(),
10982 script: readVarSlice(),
10983 sequence: readUInt32(),
10984 witness: EMPTY_WITNESS
10988 var voutLen
= readVarInt()
10989 for (i
= 0; i
< voutLen
; ++i
) {
10991 value: readUInt64(),
10992 script: readVarSlice()
10996 if (hasWitnesses
) {
10997 for (i
= 0; i
< vinLen
; ++i
) {
10998 tx
.ins
[i
].witness
= readVector()
11001 // was this pointless?
11002 if (!tx
.hasWitnesses()) throw new Error('Transaction has superfluous witness data')
11005 tx
.locktime
= readUInt32()
11007 if (__noStrict
) return tx
11008 if (offset
!== buffer
.length
) throw new Error('Transaction has unexpected data')
11013 Transaction
.fromHex = function (hex
) {
11014 return Transaction
.fromBuffer(Buffer
.from(hex
, 'hex'))
11017 Transaction
.isCoinbaseHash = function (buffer
) {
11018 typeforce(types
.Hash256bit
, buffer
)
11019 for (var i
= 0; i
< 32; ++i
) {
11020 if (buffer
[i
] !== 0) return false
11025 Transaction
.prototype.isCoinbase = function () {
11026 return this.ins
.length
=== 1 && Transaction
.isCoinbaseHash(this.ins
[0].hash
)
11029 Transaction
.prototype.addInput = function (hash
, index
, sequence
, scriptSig
) {
11030 typeforce(types
.tuple(
11033 types
.maybe(types
.UInt32
),
11034 types
.maybe(types
.Buffer
)
11037 if (types
.Null(sequence
)) {
11038 sequence
= Transaction
.DEFAULT_SEQUENCE
11041 // Add the input and return the input's index
11042 return (this.ins
.push({
11045 script: scriptSig
|| EMPTY_SCRIPT
,
11046 sequence: sequence
,
11047 witness: EMPTY_WITNESS
11051 Transaction
.prototype.addOutput = function (scriptPubKey
, value
) {
11052 typeforce(types
.tuple(types
.Buffer
, types
.Satoshi
), arguments
)
11054 // Add the output and return the output's index
11055 return (this.outs
.push({
11056 script: scriptPubKey
,
11061 Transaction
.prototype.hasWitnesses = function () {
11062 return this.ins
.some(function (x
) {
11063 return x
.witness
.length
!== 0
11067 Transaction
.prototype.weight = function () {
11068 var base
= this.__byteLength(false)
11069 var total
= this.__byteLength(true)
11070 return base
* 3 + total
11073 Transaction
.prototype.virtualSize = function () {
11074 return Math
.ceil(this.weight() / 4)
11077 Transaction
.prototype.byteLength = function () {
11078 return this.__byteLength(true)
11081 Transaction
.prototype.__byteLength = function (__allowWitness
) {
11082 var hasWitnesses
= __allowWitness
&& this.hasWitnesses()
11085 (hasWitnesses
? 10 : 8) +
11086 varuint
.encodingLength(this.ins
.length
) +
11087 varuint
.encodingLength(this.outs
.length
) +
11088 this.ins
.reduce(function (sum
, input
) { return sum
+ 40 + varSliceSize(input
.script
) }, 0) +
11089 this.outs
.reduce(function (sum
, output
) { return sum
+ 8 + varSliceSize(output
.script
) }, 0) +
11090 (hasWitnesses
? this.ins
.reduce(function (sum
, input
) { return sum
+ vectorSize(input
.witness
) }, 0) : 0)
11094 Transaction
.prototype.clone = function () {
11095 var newTx
= new Transaction()
11096 newTx
.version
= this.version
11097 newTx
.locktime
= this.locktime
11099 newTx
.ins
= this.ins
.map(function (txIn
) {
11103 script: txIn
.script
,
11104 sequence: txIn
.sequence
,
11105 witness: txIn
.witness
11109 newTx
.outs
= this.outs
.map(function (txOut
) {
11111 script: txOut
.script
,
11120 * Hash transaction for signing a specific input.
11122 * Bitcoin uses a different hash for each signed transaction input.
11123 * This method copies the transaction, makes the necessary changes based on the
11124 * hashType, and then hashes the result.
11125 * This hash can then be used to sign the provided transaction input.
11127 Transaction
.prototype.hashForSignature = function (inIndex
, prevOutScript
, hashType
) {
11128 typeforce(types
.tuple(types
.UInt32
, types
.Buffer
, /* types.UInt8 */ types
.Number
), arguments
)
11130 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29
11131 if (inIndex
>= this.ins
.length
) return ONE
11133 // ignore OP_CODESEPARATOR
11134 var ourScript
= bscript
.compile(bscript
.decompile(prevOutScript
).filter(function (x
) {
11135 return x
!== opcodes
.OP_CODESEPARATOR
11138 var txTmp
= this.clone()
11140 // SIGHASH_NONE: ignore all outputs? (wildcard payee)
11141 if ((hashType
& 0x1f) === Transaction
.SIGHASH_NONE
) {
11144 // ignore sequence numbers (except at inIndex)
11145 txTmp
.ins
.forEach(function (input
, i
) {
11146 if (i
=== inIndex
) return
11151 // SIGHASH_SINGLE: ignore all outputs, except at the same index?
11152 } else if ((hashType
& 0x1f) === Transaction
.SIGHASH_SINGLE
) {
11153 // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60
11154 if (inIndex
>= this.outs
.length
) return ONE
11156 // truncate outputs after
11157 txTmp
.outs
.length
= inIndex
+ 1
11159 // "blank" outputs before
11160 for (var i
= 0; i
< inIndex
; i
++) {
11161 txTmp
.outs
[i
] = BLANK_OUTPUT
11164 // ignore sequence numbers (except at inIndex)
11165 txTmp
.ins
.forEach(function (input
, y
) {
11166 if (y
=== inIndex
) return
11172 // SIGHASH_ANYONECANPAY: ignore inputs entirely?
11173 if (hashType
& Transaction
.SIGHASH_ANYONECANPAY
) {
11174 txTmp
.ins
= [txTmp
.ins
[inIndex
]]
11175 txTmp
.ins
[0].script
= ourScript
11177 // SIGHASH_ALL: only ignore input scripts
11179 // "blank" others input scripts
11180 txTmp
.ins
.forEach(function (input
) { input
.script
= EMPTY_SCRIPT
})
11181 txTmp
.ins
[inIndex
].script
= ourScript
11184 // serialize and hash
11185 var buffer
= Buffer
.allocUnsafe(txTmp
.__byteLength(false) + 4)
11186 buffer
.writeInt32LE(hashType
, buffer
.length
- 4)
11187 txTmp
.__toBuffer(buffer
, 0, false)
11189 return bcrypto
.hash256(buffer
)
11192 Transaction
.prototype.hashForWitnessV0 = function (inIndex
, prevOutScript
, value
, hashType
) {
11193 typeforce(types
.tuple(types
.UInt32
, types
.Buffer
, types
.Satoshi
, types
.UInt32
), arguments
)
11195 var tbuffer
, toffset
11196 function writeSlice (slice
) { toffset
+= slice
.copy(tbuffer
, toffset
) }
11197 function writeUInt32 (i
) { toffset
= tbuffer
.writeUInt32LE(i
, toffset
) }
11198 function writeUInt64 (i
) { toffset
= bufferutils
.writeUInt64LE(tbuffer
, i
, toffset
) }
11199 function writeVarInt (i
) {
11200 varuint
.encode(i
, tbuffer
, toffset
)
11201 toffset
+= varuint
.encode
.bytes
11203 function writeVarSlice (slice
) { writeVarInt(slice
.length
); writeSlice(slice
) }
11205 var hashOutputs
= ZERO
11206 var hashPrevouts
= ZERO
11207 var hashSequence
= ZERO
11209 if (!(hashType
& Transaction
.SIGHASH_ANYONECANPAY
)) {
11210 tbuffer
= Buffer
.allocUnsafe(36 * this.ins
.length
)
11213 this.ins
.forEach(function (txIn
) {
11214 writeSlice(txIn
.hash
)
11215 writeUInt32(txIn
.index
)
11218 hashPrevouts
= bcrypto
.hash256(tbuffer
)
11221 if (!(hashType
& Transaction
.SIGHASH_ANYONECANPAY
) &&
11222 (hashType
& 0x1f) !== Transaction
.SIGHASH_SINGLE
&&
11223 (hashType
& 0x1f) !== Transaction
.SIGHASH_NONE
) {
11224 tbuffer
= Buffer
.allocUnsafe(4 * this.ins
.length
)
11227 this.ins
.forEach(function (txIn
) {
11228 writeUInt32(txIn
.sequence
)
11231 hashSequence
= bcrypto
.hash256(tbuffer
)
11234 if ((hashType
& 0x1f) !== Transaction
.SIGHASH_SINGLE
&&
11235 (hashType
& 0x1f) !== Transaction
.SIGHASH_NONE
) {
11236 var txOutsSize
= this.outs
.reduce(function (sum
, output
) {
11237 return sum
+ 8 + varSliceSize(output
.script
)
11240 tbuffer
= Buffer
.allocUnsafe(txOutsSize
)
11243 this.outs
.forEach(function (out
) {
11244 writeUInt64(out
.value
)
11245 writeVarSlice(out
.script
)
11248 hashOutputs
= bcrypto
.hash256(tbuffer
)
11249 } else if ((hashType
& 0x1f) === Transaction
.SIGHASH_SINGLE
&& inIndex
< this.outs
.length
) {
11250 var output
= this.outs
[inIndex
]
11252 tbuffer
= Buffer
.allocUnsafe(8 + varSliceSize(output
.script
))
11254 writeUInt64(output
.value
)
11255 writeVarSlice(output
.script
)
11257 hashOutputs
= bcrypto
.hash256(tbuffer
)
11260 tbuffer
= Buffer
.allocUnsafe(156 + varSliceSize(prevOutScript
))
11263 var input
= this.ins
[inIndex
]
11264 writeUInt32(this.version
)
11265 writeSlice(hashPrevouts
)
11266 writeSlice(hashSequence
)
11267 writeSlice(input
.hash
)
11268 writeUInt32(input
.index
)
11269 writeVarSlice(prevOutScript
)
11271 writeUInt32(input
.sequence
)
11272 writeSlice(hashOutputs
)
11273 writeUInt32(this.locktime
)
11274 writeUInt32(hashType
)
11275 return bcrypto
.hash256(tbuffer
)
11278 Transaction
.prototype.getHash = function () {
11279 return bcrypto
.hash256(this.__toBuffer(undefined, undefined, false))
11282 Transaction
.prototype.getId = function () {
11283 // transaction hash's are displayed in reverse order
11284 return this.getHash().reverse().toString('hex')
11287 Transaction
.prototype.toBuffer = function (buffer
, initialOffset
) {
11288 return this.__toBuffer(buffer
, initialOffset
, true)
11291 Transaction
.prototype.__toBuffer = function (buffer
, initialOffset
, __allowWitness
) {
11292 if (!buffer
) buffer
= Buffer
.allocUnsafe(this.__byteLength(__allowWitness
))
11294 var offset
= initialOffset
|| 0
11295 function writeSlice (slice
) { offset
+= slice
.copy(buffer
, offset
) }
11296 function writeUInt8 (i
) { offset
= buffer
.writeUInt8(i
, offset
) }
11297 function writeUInt32 (i
) { offset
= buffer
.writeUInt32LE(i
, offset
) }
11298 function writeInt32 (i
) { offset
= buffer
.writeInt32LE(i
, offset
) }
11299 function writeUInt64 (i
) { offset
= bufferutils
.writeUInt64LE(buffer
, i
, offset
) }
11300 function writeVarInt (i
) {
11301 varuint
.encode(i
, buffer
, offset
)
11302 offset
+= varuint
.encode
.bytes
11304 function writeVarSlice (slice
) { writeVarInt(slice
.length
); writeSlice(slice
) }
11305 function writeVector (vector
) { writeVarInt(vector
.length
); vector
.forEach(writeVarSlice
) }
11307 writeInt32(this.version
)
11309 var hasWitnesses
= __allowWitness
&& this.hasWitnesses()
11311 if (hasWitnesses
) {
11312 writeUInt8(Transaction
.ADVANCED_TRANSACTION_MARKER
)
11313 writeUInt8(Transaction
.ADVANCED_TRANSACTION_FLAG
)
11316 writeVarInt(this.ins
.length
)
11318 this.ins
.forEach(function (txIn
) {
11319 writeSlice(txIn
.hash
)
11320 writeUInt32(txIn
.index
)
11321 writeVarSlice(txIn
.script
)
11322 writeUInt32(txIn
.sequence
)
11325 writeVarInt(this.outs
.length
)
11326 this.outs
.forEach(function (txOut
) {
11327 if (!txOut
.valueBuffer
) {
11328 writeUInt64(txOut
.value
)
11330 writeSlice(txOut
.valueBuffer
)
11333 writeVarSlice(txOut
.script
)
11336 if (hasWitnesses
) {
11337 this.ins
.forEach(function (input
) {
11338 writeVector(input
.witness
)
11342 writeUInt32(this.locktime
)
11344 // avoid slicing unless necessary
11345 if (initialOffset
!== undefined) return buffer
.slice(initialOffset
, offset
)
11349 Transaction
.prototype.toHex = function () {
11350 return this.toBuffer().toString('hex')
11353 Transaction
.prototype.setInputScript = function (index
, scriptSig
) {
11354 typeforce(types
.tuple(types
.Number
, types
.Buffer
), arguments
)
11356 this.ins
[index
].script
= scriptSig
11359 Transaction
.prototype.setWitness = function (index
, witness
) {
11360 typeforce(types
.tuple(types
.Number
, [types
.Buffer
]), arguments
)
11362 this.ins
[index
].witness
= witness
11365 module
.exports
= Transaction
11367 },{"./bufferutils":46,"./crypto":47,"./script":54,"./types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112,"varuint-bitcoin":114}],79:[function(require
,module
,exports
){
11368 var Buffer
= require('safe-buffer').Buffer
11369 var baddress
= require('./address')
11370 var bcrypto
= require('./crypto')
11371 var bscript
= require('./script')
11372 var btemplates
= require('./templates')
11373 var networks
= require('./networks')
11374 var ops
= require('bitcoin-ops')
11375 var typeforce
= require('typeforce')
11376 var types
= require('./types')
11377 var scriptTypes
= btemplates
.types
11378 var SIGNABLE
= [btemplates
.types
.P2PKH
, btemplates
.types
.P2PK
, btemplates
.types
.MULTISIG
]
11379 var P2SH
= SIGNABLE
.concat([btemplates
.types
.P2WPKH
, btemplates
.types
.P2WSH
])
11381 var ECPair
= require('./ecpair')
11382 var ECSignature
= require('./ecsignature')
11383 var Transaction
= require('./transaction')
11385 function supportedType (type
) {
11386 return SIGNABLE
.indexOf(type
) !== -1
11389 function supportedP2SHType (type
) {
11390 return P2SH
.indexOf(type
) !== -1
11393 function extractChunks (type
, chunks
, script
) {
11395 var signatures
= []
11397 case scriptTypes
.P2PKH:
11398 // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)')
11399 pubKeys
= chunks
.slice(1)
11400 signatures
= chunks
.slice(0, 1)
11403 case scriptTypes
.P2PK:
11404 pubKeys
[0] = script
? btemplates
.pubKey
.output
.decode(script
) : undefined
11405 signatures
= chunks
.slice(0, 1)
11408 case scriptTypes
.MULTISIG:
11410 var multisig
= btemplates
.multisig
.output
.decode(script
)
11411 pubKeys
= multisig
.pubKeys
11414 signatures
= chunks
.slice(1).map(function (chunk
) {
11415 return chunk
.length
=== 0 ? undefined : chunk
11422 signatures: signatures
11425 function expandInput (scriptSig
, witnessStack
) {
11426 if (scriptSig
.length
=== 0 && witnessStack
.length
=== 0) return {}
11434 var witnessScriptType
11435 var redeemScriptType
11436 var witness
= false
11442 var scriptSigChunks
= bscript
.decompile(scriptSig
)
11443 var sigType
= btemplates
.classifyInput(scriptSigChunks
, true)
11444 if (sigType
=== scriptTypes
.P2SH
) {
11446 redeemScript
= scriptSigChunks
[scriptSigChunks
.length
- 1]
11447 redeemScriptType
= btemplates
.classifyOutput(redeemScript
)
11448 prevOutScript
= btemplates
.scriptHash
.output
.encode(bcrypto
.hash160(redeemScript
))
11449 prevOutType
= scriptTypes
.P2SH
11450 script
= redeemScript
11453 var classifyWitness
= btemplates
.classifyWitness(witnessStack
, true)
11454 if (classifyWitness
=== scriptTypes
.P2WSH
) {
11455 witnessScript
= witnessStack
[witnessStack
.length
- 1]
11456 witnessScriptType
= btemplates
.classifyOutput(witnessScript
)
11459 if (scriptSig
.length
=== 0) {
11460 prevOutScript
= btemplates
.witnessScriptHash
.output
.encode(bcrypto
.sha256(witnessScript
))
11461 prevOutType
= scriptTypes
.P2WSH
11462 if (redeemScript
!== undefined) {
11463 throw new Error('Redeem script given when unnecessary')
11467 if (!redeemScript
) {
11468 throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty')
11470 witnessProgram
= btemplates
.witnessScriptHash
.output
.encode(bcrypto
.sha256(witnessScript
))
11471 if (!redeemScript
.equals(witnessProgram
)) {
11472 throw new Error('Redeem script didn\'t match witnessScript')
11476 if (!supportedType(btemplates
.classifyOutput(witnessScript
))) {
11477 throw new Error('unsupported witness script')
11480 script
= witnessScript
11481 scriptType
= witnessScriptType
11482 chunks
= witnessStack
.slice(0, -1)
11483 } else if (classifyWitness
=== scriptTypes
.P2WPKH
) {
11485 var key
= witnessStack
[witnessStack
.length
- 1]
11486 var keyHash
= bcrypto
.hash160(key
)
11487 if (scriptSig
.length
=== 0) {
11488 prevOutScript
= btemplates
.witnessPubKeyHash
.output
.encode(keyHash
)
11489 prevOutType
= scriptTypes
.P2WPKH
11490 if (typeof redeemScript
!== 'undefined') {
11491 throw new Error('Redeem script given when unnecessary')
11494 if (!redeemScript
) {
11495 throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty')
11497 witnessProgram
= btemplates
.witnessPubKeyHash
.output
.encode(keyHash
)
11498 if (!redeemScript
.equals(witnessProgram
)) {
11499 throw new Error('Redeem script did not have the right witness program')
11503 scriptType
= scriptTypes
.P2PKH
11504 chunks
= witnessStack
11505 } else if (redeemScript
) {
11506 if (!supportedP2SHType(redeemScriptType
)) {
11507 throw new Error('Bad redeemscript!')
11510 script
= redeemScript
11511 scriptType
= redeemScriptType
11512 chunks
= scriptSigChunks
.slice(0, -1)
11514 prevOutType
= scriptType
= btemplates
.classifyInput(scriptSig
)
11515 chunks
= scriptSigChunks
11518 var expanded
= extractChunks(scriptType
, chunks
, script
)
11521 pubKeys: expanded
.pubKeys
,
11522 signatures: expanded
.signatures
,
11523 prevOutScript: prevOutScript
,
11524 prevOutType: prevOutType
,
11525 signType: scriptType
,
11526 signScript: script
,
11527 witness: Boolean(witness
)
11531 result
.redeemScript
= redeemScript
11532 result
.redeemScriptType
= redeemScriptType
11536 result
.witnessScript
= witnessScript
11537 result
.witnessScriptType
= witnessScriptType
11543 // could be done in expandInput, but requires the original Transaction for hashForSignature
11544 function fixMultisigOrder (input
, transaction
, vin
) {
11545 if (input
.redeemScriptType
!== scriptTypes
.MULTISIG
|| !input
.redeemScript
) return
11546 if (input
.pubKeys
.length
=== input
.signatures
.length
) return
11548 var unmatched
= input
.signatures
.concat()
11550 input
.signatures
= input
.pubKeys
.map(function (pubKey
) {
11551 var keyPair
= ECPair
.fromPublicKeyBuffer(pubKey
)
11554 // check for a signature
11555 unmatched
.some(function (signature
, i
) {
11556 // skip if undefined || OP_0
11557 if (!signature
) return false
11559 // TODO: avoid O(n) hashForSignature
11560 var parsed
= ECSignature
.parseScriptSignature(signature
)
11561 var hash
= transaction
.hashForSignature(vin
, input
.redeemScript
, parsed
.hashType
)
11563 // skip if signature does not match pubKey
11564 if (!keyPair
.verify(hash
, parsed
.signature
)) return false
11566 // remove matched signature from unmatched
11567 unmatched
[i
] = undefined
11577 function expandOutput (script
, scriptType
, ourPubKey
) {
11578 typeforce(types
.Buffer
, script
)
11580 var scriptChunks
= bscript
.decompile(script
)
11582 scriptType
= btemplates
.classifyOutput(script
)
11587 switch (scriptType
) {
11588 // does our hash160(pubKey) match the output scripts?
11589 case scriptTypes
.P2PKH:
11590 if (!ourPubKey
) break
11592 var pkh1
= scriptChunks
[2]
11593 var pkh2
= bcrypto
.hash160(ourPubKey
)
11594 if (pkh1
.equals(pkh2
)) pubKeys
= [ourPubKey
]
11597 // does our hash160(pubKey) match the output scripts?
11598 case scriptTypes
.P2WPKH:
11599 if (!ourPubKey
) break
11601 var wpkh1
= scriptChunks
[1]
11602 var wpkh2
= bcrypto
.hash160(ourPubKey
)
11603 if (wpkh1
.equals(wpkh2
)) pubKeys
= [ourPubKey
]
11606 case scriptTypes
.P2PK:
11607 pubKeys
= scriptChunks
.slice(0, 1)
11610 case scriptTypes
.MULTISIG:
11611 pubKeys
= scriptChunks
.slice(1, -2)
11614 default: return { scriptType: scriptType
}
11619 scriptType: scriptType
,
11620 signatures: pubKeys
.map(function () { return undefined })
11624 function checkP2SHInput (input
, redeemScriptHash
) {
11625 if (input
.prevOutType
) {
11626 if (input
.prevOutType
!== scriptTypes
.P2SH
) throw new Error('PrevOutScript must be P2SH')
11628 var prevOutScriptScriptHash
= bscript
.decompile(input
.prevOutScript
)[1]
11629 if (!prevOutScriptScriptHash
.equals(redeemScriptHash
)) throw new Error('Inconsistent hash160(RedeemScript)')
11633 function checkP2WSHInput (input
, witnessScriptHash
) {
11634 if (input
.prevOutType
) {
11635 if (input
.prevOutType
!== scriptTypes
.P2WSH
) throw new Error('PrevOutScript must be P2WSH')
11637 var scriptHash
= bscript
.decompile(input
.prevOutScript
)[1]
11638 if (!scriptHash
.equals(witnessScriptHash
)) throw new Error('Inconsistent sha25(WitnessScript)')
11642 function prepareInput (input
, kpPubKey
, redeemScript
, witnessValue
, witnessScript
) {
11649 var redeemScriptHash
11651 var witness
= false
11654 var witnessScriptHash
11659 if (redeemScript
&& witnessScript
) {
11660 redeemScriptHash
= bcrypto
.hash160(redeemScript
)
11661 witnessScriptHash
= bcrypto
.sha256(witnessScript
)
11662 checkP2SHInput(input
, redeemScriptHash
)
11664 if (!redeemScript
.equals(btemplates
.witnessScriptHash
.output
.encode(witnessScriptHash
))) throw new Error('Witness script inconsistent with redeem script')
11666 expanded
= expandOutput(witnessScript
, undefined, kpPubKey
)
11667 if (!expanded
.pubKeys
) throw new Error('WitnessScript not supported "' + bscript
.toASM(redeemScript
) + '"')
11669 prevOutType
= btemplates
.types
.P2SH
11670 prevOutScript
= btemplates
.scriptHash
.output
.encode(redeemScriptHash
)
11671 p2sh
= witness
= p2wsh
= true
11672 p2shType
= btemplates
.types
.P2WSH
11673 signType
= witnessType
= expanded
.scriptType
11674 signScript
= witnessScript
11675 } else if (redeemScript
) {
11676 redeemScriptHash
= bcrypto
.hash160(redeemScript
)
11677 checkP2SHInput(input
, redeemScriptHash
)
11679 expanded
= expandOutput(redeemScript
, undefined, kpPubKey
)
11680 if (!expanded
.pubKeys
) throw new Error('RedeemScript not supported "' + bscript
.toASM(redeemScript
) + '"')
11682 prevOutType
= btemplates
.types
.P2SH
11683 prevOutScript
= btemplates
.scriptHash
.output
.encode(redeemScriptHash
)
11685 signType
= p2shType
= expanded
.scriptType
11686 signScript
= redeemScript
11687 witness
= signType
=== btemplates
.types
.P2WPKH
11688 } else if (witnessScript
) {
11689 witnessScriptHash
= bcrypto
.sha256(witnessScript
)
11690 checkP2WSHInput(input
, witnessScriptHash
)
11692 expanded
= expandOutput(witnessScript
, undefined, kpPubKey
)
11693 if (!expanded
.pubKeys
) throw new Error('WitnessScript not supported "' + bscript
.toASM(redeemScript
) + '"')
11695 prevOutType
= btemplates
.types
.P2WSH
11696 prevOutScript
= btemplates
.witnessScriptHash
.output
.encode(witnessScriptHash
)
11697 witness
= p2wsh
= true
11698 signType
= witnessType
= expanded
.scriptType
11699 signScript
= witnessScript
11700 } else if (input
.prevOutType
) {
11701 // embedded scripts are not possible without a redeemScript
11702 if (input
.prevOutType
=== scriptTypes
.P2SH
||
11703 input
.prevOutType
=== scriptTypes
.P2WSH
) {
11704 throw new Error('PrevOutScript is ' + input
.prevOutType
+ ', requires redeemScript')
11707 prevOutType
= input
.prevOutType
11708 prevOutScript
= input
.prevOutScript
11709 expanded
= expandOutput(input
.prevOutScript
, input
.prevOutType
, kpPubKey
)
11710 if (!expanded
.pubKeys
) return
11712 witness
= (input
.prevOutType
=== scriptTypes
.P2WPKH
)
11713 signType
= prevOutType
11714 signScript
= prevOutScript
11716 prevOutScript
= btemplates
.pubKeyHash
.output
.encode(bcrypto
.hash160(kpPubKey
))
11717 expanded
= expandOutput(prevOutScript
, scriptTypes
.P2PKH
, kpPubKey
)
11719 prevOutType
= scriptTypes
.P2PKH
11721 signType
= prevOutType
11722 signScript
= prevOutScript
11725 if (signType
=== scriptTypes
.P2WPKH
) {
11726 signScript
= btemplates
.pubKeyHash
.output
.encode(btemplates
.witnessPubKeyHash
.output
.decode(signScript
))
11730 input
.redeemScript
= redeemScript
11731 input
.redeemScriptType
= p2shType
11735 input
.witnessScript
= witnessScript
11736 input
.witnessScriptType
= witnessType
11739 input
.pubKeys
= expanded
.pubKeys
11740 input
.signatures
= expanded
.signatures
11741 input
.signScript
= signScript
11742 input
.signType
= signType
11743 input
.prevOutScript
= prevOutScript
11744 input
.prevOutType
= prevOutType
11745 input
.witness
= witness
11748 function buildStack (type
, signatures
, pubKeys
, allowIncomplete
) {
11749 if (type
=== scriptTypes
.P2PKH
) {
11750 if (signatures
.length
=== 1 && Buffer
.isBuffer(signatures
[0]) && pubKeys
.length
=== 1) return btemplates
.pubKeyHash
.input
.encodeStack(signatures
[0], pubKeys
[0])
11751 } else if (type
=== scriptTypes
.P2PK
) {
11752 if (signatures
.length
=== 1 && Buffer
.isBuffer(signatures
[0])) return btemplates
.pubKey
.input
.encodeStack(signatures
[0])
11753 } else if (type
=== scriptTypes
.MULTISIG
) {
11754 if (signatures
.length
> 0) {
11755 signatures
= signatures
.map(function (signature
) {
11756 return signature
|| ops
.OP_0
11758 if (!allowIncomplete
) {
11759 // remove blank signatures
11760 signatures
= signatures
.filter(function (x
) { return x
!== ops
.OP_0
})
11763 return btemplates
.multisig
.input
.encodeStack(signatures
)
11766 throw new Error('Not yet supported')
11769 if (!allowIncomplete
) throw new Error('Not enough signatures provided')
11773 function buildInput (input
, allowIncomplete
) {
11774 var scriptType
= input
.prevOutType
11778 if (supportedType(scriptType
)) {
11779 sig
= buildStack(scriptType
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
11783 if (scriptType
=== btemplates
.types
.P2SH
) {
11784 // We can remove this error later when we have a guarantee prepareInput
11785 // rejects unsignable scripts - it MUST be signable at this point.
11786 if (!allowIncomplete
&& !supportedP2SHType(input
.redeemScriptType
)) {
11787 throw new Error('Impossible to sign this type')
11790 if (supportedType(input
.redeemScriptType
)) {
11791 sig
= buildStack(input
.redeemScriptType
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
11794 // If it wasn't SIGNABLE, it's witness, defer to that
11795 if (input
.redeemScriptType
) {
11797 scriptType
= input
.redeemScriptType
11801 switch (scriptType
) {
11802 // P2WPKH is a special case of P2PKH
11803 case btemplates
.types
.P2WPKH:
11804 witness
= buildStack(btemplates
.types
.P2PKH
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
11807 case btemplates
.types
.P2WSH:
11808 // We can remove this check later
11809 if (!allowIncomplete
&& !supportedType(input
.witnessScriptType
)) {
11810 throw new Error('Impossible to sign this type')
11813 if (supportedType(input
.witnessScriptType
)) {
11814 witness
= buildStack(input
.witnessScriptType
, input
.signatures
, input
.pubKeys
, allowIncomplete
)
11815 witness
.push(input
.witnessScript
)
11816 scriptType
= input
.witnessScriptType
11822 // append redeemScript if necessary
11824 sig
.push(input
.redeemScript
)
11829 script: bscript
.compile(sig
),
11834 function TransactionBuilder (network
, maximumFeeRate
) {
11835 this.prevTxMap
= {}
11836 this.network
= network
|| networks
.bitcoin
11838 // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth)
11839 this.maximumFeeRate
= maximumFeeRate
|| 2500
11842 this.tx
= new Transaction()
11845 TransactionBuilder
.prototype.setLockTime = function (locktime
) {
11846 typeforce(types
.UInt32
, locktime
)
11848 // if any signatures exist, throw
11849 if (this.inputs
.some(function (input
) {
11850 if (!input
.signatures
) return false
11852 return input
.signatures
.some(function (s
) { return s
})
11854 throw new Error('No, this would invalidate signatures')
11857 this.tx
.locktime
= locktime
11860 TransactionBuilder
.prototype.setVersion = function (version
) {
11861 typeforce(types
.UInt32
, version
)
11863 // XXX: this might eventually become more complex depending on what the versions represent
11864 this.tx
.version
= version
11867 TransactionBuilder
.fromTransaction = function (transaction
, network
) {
11868 var txb
= new TransactionBuilder(network
)
11870 // Copy transaction fields
11871 txb
.setVersion(transaction
.version
)
11872 txb
.setLockTime(transaction
.locktime
)
11874 // Copy outputs (done first to avoid signature invalidation)
11875 transaction
.outs
.forEach(function (txOut
) {
11876 txb
.addOutput(txOut
.script
, txOut
.value
)
11880 transaction
.ins
.forEach(function (txIn
) {
11881 txb
.__addInputUnsafe(txIn
.hash
, txIn
.index
, {
11882 sequence: txIn
.sequence
,
11883 script: txIn
.script
,
11884 witness: txIn
.witness
11888 // fix some things not possible through the public API
11889 txb
.inputs
.forEach(function (input
, i
) {
11890 fixMultisigOrder(input
, transaction
, i
)
11896 TransactionBuilder
.prototype.addInput = function (txHash
, vout
, sequence
, prevOutScript
) {
11897 if (!this.__canModifyInputs()) {
11898 throw new Error('No, this would invalidate signatures')
11903 // is it a hex string?
11904 if (typeof txHash
=== 'string') {
11905 // transaction hashs's are displayed in reverse order, un-reverse it
11906 txHash
= Buffer
.from(txHash
, 'hex').reverse()
11908 // is it a Transaction object?
11909 } else if (txHash
instanceof Transaction
) {
11910 var txOut
= txHash
.outs
[vout
]
11911 prevOutScript
= txOut
.script
11912 value
= txOut
.value
11914 txHash
= txHash
.getHash()
11917 return this.__addInputUnsafe(txHash
, vout
, {
11918 sequence: sequence
,
11919 prevOutScript: prevOutScript
,
11924 TransactionBuilder
.prototype.__addInputUnsafe = function (txHash
, vout
, options
) {
11925 if (Transaction
.isCoinbaseHash(txHash
)) {
11926 throw new Error('coinbase inputs not supported')
11929 var prevTxOut
= txHash
.toString('hex') + ':' + vout
11930 if (this.prevTxMap
[prevTxOut
] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut
)
11934 // derive what we can from the scriptSig
11935 if (options
.script
!== undefined) {
11936 input
= expandInput(options
.script
, options
.witness
|| [])
11939 // if an input value was given, retain it
11940 if (options
.value
!== undefined) {
11941 input
.value
= options
.value
11944 // derive what we can from the previous transactions output script
11945 if (!input
.prevOutScript
&& options
.prevOutScript
) {
11948 if (!input
.pubKeys
&& !input
.signatures
) {
11949 var expanded
= expandOutput(options
.prevOutScript
)
11951 if (expanded
.pubKeys
) {
11952 input
.pubKeys
= expanded
.pubKeys
11953 input
.signatures
= expanded
.signatures
11956 prevOutType
= expanded
.scriptType
11959 input
.prevOutScript
= options
.prevOutScript
11960 input
.prevOutType
= prevOutType
|| btemplates
.classifyOutput(options
.prevOutScript
)
11963 var vin
= this.tx
.addInput(txHash
, vout
, options
.sequence
, options
.scriptSig
)
11964 this.inputs
[vin
] = input
11965 this.prevTxMap
[prevTxOut
] = vin
11969 TransactionBuilder
.prototype.addOutput = function (scriptPubKey
, value
) {
11970 if (!this.__canModifyOutputs()) {
11971 throw new Error('No, this would invalidate signatures')
11974 // Attempt to get a script if it's a base58 address string
11975 if (typeof scriptPubKey
=== 'string') {
11976 scriptPubKey
= baddress
.toOutputScript(scriptPubKey
, this.network
)
11979 return this.tx
.addOutput(scriptPubKey
, value
)
11982 TransactionBuilder
.prototype.build = function () {
11983 return this.__build(false)
11985 TransactionBuilder
.prototype.buildIncomplete = function () {
11986 return this.__build(true)
11989 TransactionBuilder
.prototype.__build = function (allowIncomplete
) {
11990 if (!allowIncomplete
) {
11991 if (!this.tx
.ins
.length
) throw new Error('Transaction has no inputs')
11992 if (!this.tx
.outs
.length
) throw new Error('Transaction has no outputs')
11995 var tx
= this.tx
.clone()
11996 // Create script signatures from inputs
11997 this.inputs
.forEach(function (input
, i
) {
11998 var scriptType
= input
.witnessScriptType
|| input
.redeemScriptType
|| input
.prevOutType
11999 if (!scriptType
&& !allowIncomplete
) throw new Error('Transaction is not complete')
12000 var result
= buildInput(input
, allowIncomplete
)
12002 // skip if no result
12003 if (!allowIncomplete
) {
12004 if (!supportedType(result
.type
) && result
.type
!== btemplates
.types
.P2WPKH
) {
12005 throw new Error(result
.type
+ ' not supported')
12009 tx
.setInputScript(i
, result
.script
)
12010 tx
.setWitness(i
, result
.witness
)
12013 if (!allowIncomplete
) {
12014 // do not rely on this, its merely a last resort
12015 if (this.__overMaximumFees(tx
.virtualSize())) {
12016 throw new Error('Transaction has absurd fees')
12023 function canSign (input
) {
12024 return input
.prevOutScript
!== undefined &&
12025 input
.signScript
!== undefined &&
12026 input
.pubKeys
!== undefined &&
12027 input
.signatures
!== undefined &&
12028 input
.signatures
.length
=== input
.pubKeys
.length
&&
12029 input
.pubKeys
.length
> 0 &&
12031 input
.witness
=== false ||
12032 (input
.witness
=== true && input
.value
!== undefined)
12036 TransactionBuilder
.prototype.sign = function (vin
, keyPair
, redeemScript
, hashType
, witnessValue
, witnessScript
) {
12037 // TODO: remove keyPair.network matching in 4.0.0
12038 if (keyPair
.network
&& keyPair
.network
!== this.network
) throw new TypeError('Inconsistent network')
12039 if (!this.inputs
[vin
]) throw new Error('No input at index: ' + vin
)
12040 hashType
= hashType
|| Transaction
.SIGHASH_ALL
12042 var input
= this.inputs
[vin
]
12044 // if redeemScript was previously provided, enforce consistency
12045 if (input
.redeemScript
!== undefined &&
12047 !input
.redeemScript
.equals(redeemScript
)) {
12048 throw new Error('Inconsistent redeemScript')
12051 var kpPubKey
= keyPair
.publicKey
|| keyPair
.getPublicKeyBuffer()
12052 if (!canSign(input
)) {
12053 if (witnessValue
!== undefined) {
12054 if (input
.value
!== undefined && input
.value
!== witnessValue
) throw new Error('Input didn\'t match witnessValue')
12055 typeforce(types
.Satoshi
, witnessValue
)
12056 input
.value
= witnessValue
12059 if (!canSign(input
)) prepareInput(input
, kpPubKey
, redeemScript
, witnessValue
, witnessScript
)
12060 if (!canSign(input
)) throw Error(input
.prevOutType
+ ' not supported')
12065 if (input
.witness
) {
12066 signatureHash
= this.tx
.hashForWitnessV0(vin
, input
.signScript
, input
.value
, hashType
)
12068 signatureHash
= this.tx
.hashForSignature(vin
, input
.signScript
, hashType
)
12071 // enforce in order signing of public keys
12072 var signed
= input
.pubKeys
.some(function (pubKey
, i
) {
12073 if (!kpPubKey
.equals(pubKey
)) return false
12074 if (input
.signatures
[i
]) throw new Error('Signature already exists')
12075 if (kpPubKey
.length
!== 33 &&
12076 input
.signType
=== scriptTypes
.P2WPKH
) throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH')
12078 var signature
= keyPair
.sign(signatureHash
)
12079 if (Buffer
.isBuffer(signature
)) signature
= ECSignature
.fromRSBuffer(signature
)
12081 input
.signatures
[i
] = signature
.toScriptSignature(hashType
)
12085 if (!signed
) throw new Error('Key pair cannot sign for this input')
12088 function signatureHashType (buffer
) {
12089 return buffer
.readUInt8(buffer
.length
- 1)
12092 TransactionBuilder
.prototype.__canModifyInputs = function () {
12093 return this.inputs
.every(function (input
) {
12095 if (input
.signatures
=== undefined) return true
12097 return input
.signatures
.every(function (signature
) {
12098 if (!signature
) return true
12099 var hashType
= signatureHashType(signature
)
12101 // if SIGHASH_ANYONECANPAY is set, signatures would not
12102 // be invalidated by more inputs
12103 return hashType
& Transaction
.SIGHASH_ANYONECANPAY
12108 TransactionBuilder
.prototype.__canModifyOutputs = function () {
12109 var nInputs
= this.tx
.ins
.length
12110 var nOutputs
= this.tx
.outs
.length
12112 return this.inputs
.every(function (input
) {
12113 if (input
.signatures
=== undefined) return true
12115 return input
.signatures
.every(function (signature
) {
12116 if (!signature
) return true
12117 var hashType
= signatureHashType(signature
)
12119 var hashTypeMod
= hashType
& 0x1f
12120 if (hashTypeMod
=== Transaction
.SIGHASH_NONE
) return true
12121 if (hashTypeMod
=== Transaction
.SIGHASH_SINGLE
) {
12122 // if SIGHASH_SINGLE is set, and nInputs > nOutputs
12123 // some signatures would be invalidated by the addition
12125 return nInputs
<= nOutputs
12131 TransactionBuilder
.prototype.__overMaximumFees = function (bytes
) {
12132 // not all inputs will have .value defined
12133 var incoming
= this.inputs
.reduce(function (a
, x
) { return a
+ (x
.value
>>> 0) }, 0)
12135 // but all outputs do, and if we have any input value
12136 // we can immediately determine if the outputs are too small
12137 var outgoing
= this.tx
.outs
.reduce(function (a
, x
) { return a
+ x
.value
}, 0)
12138 var fee
= incoming
- outgoing
12139 var feeRate
= fee
/ bytes
12141 return feeRate
> this.maximumFeeRate
12144 module
.exports
= TransactionBuilder
12146 },{"./address":44,"./crypto":47,"./ecpair":49,"./ecsignature":50,"./networks":53,"./script":54,"./templates":56,"./transaction":78,"./types":80,"bitcoin-ops":42,"safe-buffer":101,"typeforce":112}],80:[function(require
,module
,exports
){
12147 var typeforce
= require('typeforce')
12149 var UINT31_MAX
= Math
.pow(2, 31) - 1
12150 function UInt31 (value
) {
12151 return typeforce
.UInt32(value
) && value
<= UINT31_MAX
12154 function BIP32Path (value
) {
12155 return typeforce
.String(value
) && value
.match(/^(m\/)?(\d+'?\/)*\d+'?$/)
12157 BIP32Path
.toJSON = function () { return 'BIP32 derivation path' }
12159 var SATOSHI_MAX
= 21 * 1e14
12160 function Satoshi (value
) {
12161 return typeforce
.UInt53(value
) && value
<= SATOSHI_MAX
12164 // external dependent types
12165 var BigInt
= typeforce
.quacksLike('BigInteger')
12166 var ECPoint
= typeforce
.quacksLike('Point')
12168 // exposed, external API
12169 var ECSignature
= typeforce
.compile({ r: BigInt
, s: BigInt
})
12170 var Network
= typeforce
.compile({
12171 messagePrefix: typeforce
.oneOf(typeforce
.Buffer
, typeforce
.String
),
12173 public: typeforce
.UInt32
,
12174 private: typeforce
.UInt32
12176 pubKeyHash: typeforce
.oneOf(typeforce
.UInt8
, typeforce
.UInt16
),
12177 scriptHash: typeforce
.oneOf(typeforce
.UInt8
, typeforce
.UInt16
),
12178 wif: typeforce
.UInt8
12181 // extend typeforce types with ours
12184 BIP32Path: BIP32Path
,
12185 Buffer256bit: typeforce
.BufferN(32),
12187 ECSignature: ECSignature
,
12188 Hash160bit: typeforce
.BufferN(20),
12189 Hash256bit: typeforce
.BufferN(32),
12195 for (var typeName
in typeforce
) {
12196 types
[typeName
] = typeforce
[typeName
]
12199 module
.exports
= types
12201 },{"typeforce":112}],81:[function(require
,module
,exports
){
12202 var basex
= require('base-x')
12203 var ALPHABET
= '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
12205 module
.exports
= basex(ALPHABET
)
12207 },{"base-x":35}],82:[function(require
,module
,exports
){
12210 var base58
= require('bs58')
12211 var Buffer
= require('safe-buffer').Buffer
12213 module
.exports = function (checksumFn
) {
12214 // Encode a buffer as a base58-check encoded string
12215 function encode (payload
) {
12216 var checksum
= checksumFn(payload
)
12218 return base58
.encode(Buffer
.concat([
12221 ], payload
.length
+ 4))
12224 function decodeRaw (buffer
) {
12225 var payload
= buffer
.slice(0, -4)
12226 var checksum
= buffer
.slice(-4)
12227 var newChecksum
= checksumFn(payload
)
12229 if (checksum
[0] ^ newChecksum
[0] |
12230 checksum
[1] ^ newChecksum
[1] |
12231 checksum
[2] ^ newChecksum
[2] |
12232 checksum
[3] ^ newChecksum
[3]) return
12237 // Decode a base58-check encoded string to a buffer, no result if checksum is wrong
12238 function decodeUnsafe (string
) {
12239 var buffer
= base58
.decodeUnsafe(string
)
12240 if (!buffer
) return
12242 return decodeRaw(buffer
)
12245 function decode (string
) {
12246 var buffer
= base58
.decode(string
)
12247 var payload
= decodeRaw(buffer
, checksumFn
)
12248 if (!payload
) throw new Error('Invalid checksum')
12255 decodeUnsafe: decodeUnsafe
12259 },{"bs58":81,"safe-buffer":101}],83:[function(require
,module
,exports
){
12262 var createHash
= require('create-hash')
12263 var bs58checkBase
= require('./base')
12265 // SHA256(SHA256(buffer))
12266 function sha256x2 (buffer
) {
12267 var tmp
= createHash('sha256').update(buffer
).digest()
12268 return createHash('sha256').update(tmp
).digest()
12271 module
.exports
= bs58checkBase(sha256x2
)
12273 },{"./base":82,"create-hash":85}],84:[function(require
,module
,exports
){
12274 var Buffer
= require('safe-buffer').Buffer
12275 var Transform
= require('stream').Transform
12276 var StringDecoder
= require('string_decoder').StringDecoder
12277 var inherits
= require('inherits')
12279 function CipherBase (hashMode
) {
12280 Transform
.call(this)
12281 this.hashMode
= typeof hashMode
=== 'string'
12282 if (this.hashMode
) {
12283 this[hashMode
] = this._finalOrDigest
12285 this.final
= this._finalOrDigest
12288 this.__final
= this._final
12291 this._decoder
= null
12292 this._encoding
= null
12294 inherits(CipherBase
, Transform
)
12296 CipherBase
.prototype.update = function (data
, inputEnc
, outputEnc
) {
12297 if (typeof data
=== 'string') {
12298 data
= Buffer
.from(data
, inputEnc
)
12301 var outData
= this._update(data
)
12302 if (this.hashMode
) return this
12305 outData
= this._toString(outData
, outputEnc
)
12311 CipherBase
.prototype.setAutoPadding = function () {}
12312 CipherBase
.prototype.getAuthTag = function () {
12313 throw new Error('trying to get auth tag in unsupported state')
12316 CipherBase
.prototype.setAuthTag = function () {
12317 throw new Error('trying to set auth tag in unsupported state')
12320 CipherBase
.prototype.setAAD = function () {
12321 throw new Error('trying to set aad in unsupported state')
12324 CipherBase
.prototype._transform = function (data
, _
, next
) {
12327 if (this.hashMode
) {
12330 this.push(this._update(data
))
12338 CipherBase
.prototype._flush = function (done
) {
12341 this.push(this.__final())
12348 CipherBase
.prototype._finalOrDigest = function (outputEnc
) {
12349 var outData
= this.__final() || Buffer
.alloc(0)
12351 outData
= this._toString(outData
, outputEnc
, true)
12356 CipherBase
.prototype._toString = function (value
, enc
, fin
) {
12357 if (!this._decoder
) {
12358 this._decoder
= new StringDecoder(enc
)
12359 this._encoding
= enc
12362 if (this._encoding
!== enc
) throw new Error('can\'t switch encodings')
12364 var out
= this._decoder
.write(value
)
12366 out
+= this._decoder
.end()
12372 module
.exports
= CipherBase
12374 },{"inherits":96,"safe-buffer":101,"stream":28,"string_decoder":29}],85:[function(require
,module
,exports
){
12375 (function (Buffer
){
12377 var inherits
= require('inherits')
12378 var md5
= require('./md5')
12379 var RIPEMD160
= require('ripemd160')
12380 var sha
= require('sha.js')
12382 var Base
= require('cipher-base')
12384 function HashNoConstructor (hash
) {
12385 Base
.call(this, 'digest')
12391 inherits(HashNoConstructor
, Base
)
12393 HashNoConstructor
.prototype._update = function (data
) {
12394 this.buffers
.push(data
)
12397 HashNoConstructor
.prototype._final = function () {
12398 var buf
= Buffer
.concat(this.buffers
)
12399 var r
= this._hash(buf
)
12400 this.buffers
= null
12405 function Hash (hash
) {
12406 Base
.call(this, 'digest')
12411 inherits(Hash
, Base
)
12413 Hash
.prototype._update = function (data
) {
12414 this._hash
.update(data
)
12417 Hash
.prototype._final = function () {
12418 return this._hash
.digest()
12421 module
.exports
= function createHash (alg
) {
12422 alg
= alg
.toLowerCase()
12423 if (alg
=== 'md5') return new HashNoConstructor(md5
)
12424 if (alg
=== 'rmd160' || alg
=== 'ripemd160') return new Hash(new RIPEMD160())
12426 return new Hash(sha(alg
))
12429 }).call(this,require("buffer").Buffer
)
12430 },{"./md5":87,"buffer":5,"cipher-base":84,"inherits":96,"ripemd160":100,"sha.js":103}],86:[function(require
,module
,exports
){
12431 (function (Buffer
){
12434 var zeroBuffer
= new Buffer(intSize
)
12440 function toArray (buf
) {
12441 if ((buf
.length
% intSize
) !== 0) {
12442 var len
= buf
.length
+ (intSize
- (buf
.length
% intSize
))
12443 buf
= Buffer
.concat([buf
, zeroBuffer
], len
)
12446 var arr
= new Array(buf
.length
>>> 2)
12447 for (var i
= 0, j
= 0; i
< buf
.length
; i
+= intSize
, j
++) {
12448 arr
[j
] = buf
.readInt32LE(i
)
12454 module
.exports
= function hash (buf
, fn
) {
12455 var arr
= fn(toArray(buf
), buf
.length
* charSize
)
12456 buf
= new Buffer(hashSize
)
12457 for (var i
= 0; i
< arr
.length
; i
++) {
12458 buf
.writeInt32LE(arr
[i
], i
<< 2, true)
12463 }).call(this,require("buffer").Buffer
)
12464 },{"buffer":5}],87:[function(require
,module
,exports
){
12467 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
12468 * Digest Algorithm, as defined in RFC 1321.
12469 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
12470 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
12471 * Distributed under the BSD License
12472 * See http://pajhome.org.uk/crypt/md5 for more info.
12475 var makeHash
= require('./make-hash')
12478 * Calculate the MD5 of an array of little-endian words, and a bit length
12480 function core_md5 (x
, len
) {
12481 /* append padding */
12482 x
[len
>> 5] |= 0x80 << ((len
) % 32)
12483 x
[(((len
+ 64) >>> 9) << 4) + 14] = len
12487 var c
= -1732584194
12490 for (var i
= 0; i
< x
.length
; i
+= 16) {
12496 a
= md5_ff(a
, b
, c
, d
, x
[i
+ 0], 7, -680876936)
12497 d
= md5_ff(d
, a
, b
, c
, x
[i
+ 1], 12, -389564586)
12498 c
= md5_ff(c
, d
, a
, b
, x
[i
+ 2], 17, 606105819)
12499 b
= md5_ff(b
, c
, d
, a
, x
[i
+ 3], 22, -1044525330)
12500 a
= md5_ff(a
, b
, c
, d
, x
[i
+ 4], 7, -176418897)
12501 d
= md5_ff(d
, a
, b
, c
, x
[i
+ 5], 12, 1200080426)
12502 c
= md5_ff(c
, d
, a
, b
, x
[i
+ 6], 17, -1473231341)
12503 b
= md5_ff(b
, c
, d
, a
, x
[i
+ 7], 22, -45705983)
12504 a
= md5_ff(a
, b
, c
, d
, x
[i
+ 8], 7, 1770035416)
12505 d
= md5_ff(d
, a
, b
, c
, x
[i
+ 9], 12, -1958414417)
12506 c
= md5_ff(c
, d
, a
, b
, x
[i
+ 10], 17, -42063)
12507 b
= md5_ff(b
, c
, d
, a
, x
[i
+ 11], 22, -1990404162)
12508 a
= md5_ff(a
, b
, c
, d
, x
[i
+ 12], 7, 1804603682)
12509 d
= md5_ff(d
, a
, b
, c
, x
[i
+ 13], 12, -40341101)
12510 c
= md5_ff(c
, d
, a
, b
, x
[i
+ 14], 17, -1502002290)
12511 b
= md5_ff(b
, c
, d
, a
, x
[i
+ 15], 22, 1236535329)
12513 a
= md5_gg(a
, b
, c
, d
, x
[i
+ 1], 5, -165796510)
12514 d
= md5_gg(d
, a
, b
, c
, x
[i
+ 6], 9, -1069501632)
12515 c
= md5_gg(c
, d
, a
, b
, x
[i
+ 11], 14, 643717713)
12516 b
= md5_gg(b
, c
, d
, a
, x
[i
+ 0], 20, -373897302)
12517 a
= md5_gg(a
, b
, c
, d
, x
[i
+ 5], 5, -701558691)
12518 d
= md5_gg(d
, a
, b
, c
, x
[i
+ 10], 9, 38016083)
12519 c
= md5_gg(c
, d
, a
, b
, x
[i
+ 15], 14, -660478335)
12520 b
= md5_gg(b
, c
, d
, a
, x
[i
+ 4], 20, -405537848)
12521 a
= md5_gg(a
, b
, c
, d
, x
[i
+ 9], 5, 568446438)
12522 d
= md5_gg(d
, a
, b
, c
, x
[i
+ 14], 9, -1019803690)
12523 c
= md5_gg(c
, d
, a
, b
, x
[i
+ 3], 14, -187363961)
12524 b
= md5_gg(b
, c
, d
, a
, x
[i
+ 8], 20, 1163531501)
12525 a
= md5_gg(a
, b
, c
, d
, x
[i
+ 13], 5, -1444681467)
12526 d
= md5_gg(d
, a
, b
, c
, x
[i
+ 2], 9, -51403784)
12527 c
= md5_gg(c
, d
, a
, b
, x
[i
+ 7], 14, 1735328473)
12528 b
= md5_gg(b
, c
, d
, a
, x
[i
+ 12], 20, -1926607734)
12530 a
= md5_hh(a
, b
, c
, d
, x
[i
+ 5], 4, -378558)
12531 d
= md5_hh(d
, a
, b
, c
, x
[i
+ 8], 11, -2022574463)
12532 c
= md5_hh(c
, d
, a
, b
, x
[i
+ 11], 16, 1839030562)
12533 b
= md5_hh(b
, c
, d
, a
, x
[i
+ 14], 23, -35309556)
12534 a
= md5_hh(a
, b
, c
, d
, x
[i
+ 1], 4, -1530992060)
12535 d
= md5_hh(d
, a
, b
, c
, x
[i
+ 4], 11, 1272893353)
12536 c
= md5_hh(c
, d
, a
, b
, x
[i
+ 7], 16, -155497632)
12537 b
= md5_hh(b
, c
, d
, a
, x
[i
+ 10], 23, -1094730640)
12538 a
= md5_hh(a
, b
, c
, d
, x
[i
+ 13], 4, 681279174)
12539 d
= md5_hh(d
, a
, b
, c
, x
[i
+ 0], 11, -358537222)
12540 c
= md5_hh(c
, d
, a
, b
, x
[i
+ 3], 16, -722521979)
12541 b
= md5_hh(b
, c
, d
, a
, x
[i
+ 6], 23, 76029189)
12542 a
= md5_hh(a
, b
, c
, d
, x
[i
+ 9], 4, -640364487)
12543 d
= md5_hh(d
, a
, b
, c
, x
[i
+ 12], 11, -421815835)
12544 c
= md5_hh(c
, d
, a
, b
, x
[i
+ 15], 16, 530742520)
12545 b
= md5_hh(b
, c
, d
, a
, x
[i
+ 2], 23, -995338651)
12547 a
= md5_ii(a
, b
, c
, d
, x
[i
+ 0], 6, -198630844)
12548 d
= md5_ii(d
, a
, b
, c
, x
[i
+ 7], 10, 1126891415)
12549 c
= md5_ii(c
, d
, a
, b
, x
[i
+ 14], 15, -1416354905)
12550 b
= md5_ii(b
, c
, d
, a
, x
[i
+ 5], 21, -57434055)
12551 a
= md5_ii(a
, b
, c
, d
, x
[i
+ 12], 6, 1700485571)
12552 d
= md5_ii(d
, a
, b
, c
, x
[i
+ 3], 10, -1894986606)
12553 c
= md5_ii(c
, d
, a
, b
, x
[i
+ 10], 15, -1051523)
12554 b
= md5_ii(b
, c
, d
, a
, x
[i
+ 1], 21, -2054922799)
12555 a
= md5_ii(a
, b
, c
, d
, x
[i
+ 8], 6, 1873313359)
12556 d
= md5_ii(d
, a
, b
, c
, x
[i
+ 15], 10, -30611744)
12557 c
= md5_ii(c
, d
, a
, b
, x
[i
+ 6], 15, -1560198380)
12558 b
= md5_ii(b
, c
, d
, a
, x
[i
+ 13], 21, 1309151649)
12559 a
= md5_ii(a
, b
, c
, d
, x
[i
+ 4], 6, -145523070)
12560 d
= md5_ii(d
, a
, b
, c
, x
[i
+ 11], 10, -1120210379)
12561 c
= md5_ii(c
, d
, a
, b
, x
[i
+ 2], 15, 718787259)
12562 b
= md5_ii(b
, c
, d
, a
, x
[i
+ 9], 21, -343485551)
12564 a
= safe_add(a
, olda
)
12565 b
= safe_add(b
, oldb
)
12566 c
= safe_add(c
, oldc
)
12567 d
= safe_add(d
, oldd
)
12570 return [a
, b
, c
, d
]
12574 * These functions implement the four basic operations the algorithm uses.
12576 function md5_cmn (q
, a
, b
, x
, s
, t
) {
12577 return safe_add(bit_rol(safe_add(safe_add(a
, q
), safe_add(x
, t
)), s
), b
)
12580 function md5_ff (a
, b
, c
, d
, x
, s
, t
) {
12581 return md5_cmn((b
& c
) | ((~b
) & d
), a
, b
, x
, s
, t
)
12584 function md5_gg (a
, b
, c
, d
, x
, s
, t
) {
12585 return md5_cmn((b
& d
) | (c
& (~d
)), a
, b
, x
, s
, t
)
12588 function md5_hh (a
, b
, c
, d
, x
, s
, t
) {
12589 return md5_cmn(b
^ c
^ d
, a
, b
, x
, s
, t
)
12592 function md5_ii (a
, b
, c
, d
, x
, s
, t
) {
12593 return md5_cmn(c
^ (b
| (~d
)), a
, b
, x
, s
, t
)
12597 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
12598 * to work around bugs in some JS interpreters.
12600 function safe_add (x
, y
) {
12601 var lsw
= (x
& 0xFFFF) + (y
& 0xFFFF)
12602 var msw
= (x
>> 16) + (y
>> 16) + (lsw
>> 16)
12603 return (msw
<< 16) | (lsw
& 0xFFFF)
12607 * Bitwise rotate a 32-bit number to the left.
12609 function bit_rol (num
, cnt
) {
12610 return (num
<< cnt
) | (num
>>> (32 - cnt
))
12613 module
.exports
= function md5 (buf
) {
12614 return makeHash(buf
, core_md5
)
12617 },{"./make-hash":86}],88:[function(require
,module
,exports
){
12619 var inherits
= require('inherits')
12620 var Legacy
= require('./legacy')
12621 var Base
= require('cipher-base')
12622 var Buffer
= require('safe-buffer').Buffer
12623 var md5
= require('create-hash/md5')
12624 var RIPEMD160
= require('ripemd160')
12626 var sha
= require('sha.js')
12628 var ZEROS
= Buffer
.alloc(128)
12630 function Hmac (alg
, key
) {
12631 Base
.call(this, 'digest')
12632 if (typeof key
=== 'string') {
12633 key
= Buffer
.from(key
)
12636 var blocksize
= (alg
=== 'sha512' || alg
=== 'sha384') ? 128 : 64
12640 if (key
.length
> blocksize
) {
12641 var hash
= alg
=== 'rmd160' ? new RIPEMD160() : sha(alg
)
12642 key
= hash
.update(key
).digest()
12643 } else if (key
.length
< blocksize
) {
12644 key
= Buffer
.concat([key
, ZEROS
], blocksize
)
12647 var ipad
= this._ipad
= Buffer
.allocUnsafe(blocksize
)
12648 var opad
= this._opad
= Buffer
.allocUnsafe(blocksize
)
12650 for (var i
= 0; i
< blocksize
; i
++) {
12651 ipad
[i
] = key
[i
] ^ 0x36
12652 opad
[i
] = key
[i
] ^ 0x5C
12654 this._hash
= alg
=== 'rmd160' ? new RIPEMD160() : sha(alg
)
12655 this._hash
.update(ipad
)
12658 inherits(Hmac
, Base
)
12660 Hmac
.prototype._update = function (data
) {
12661 this._hash
.update(data
)
12664 Hmac
.prototype._final = function () {
12665 var h
= this._hash
.digest()
12666 var hash
= this._alg
=== 'rmd160' ? new RIPEMD160() : sha(this._alg
)
12667 return hash
.update(this._opad
).update(h
).digest()
12670 module
.exports
= function createHmac (alg
, key
) {
12671 alg
= alg
.toLowerCase()
12672 if (alg
=== 'rmd160' || alg
=== 'ripemd160') {
12673 return new Hmac('rmd160', key
)
12675 if (alg
=== 'md5') {
12676 return new Legacy(md5
, key
)
12678 return new Hmac(alg
, key
)
12681 },{"./legacy":89,"cipher-base":84,"create-hash/md5":87,"inherits":96,"ripemd160":100,"safe-buffer":101,"sha.js":103}],89:[function(require
,module
,exports
){
12683 var inherits
= require('inherits')
12684 var Buffer
= require('safe-buffer').Buffer
12686 var Base
= require('cipher-base')
12688 var ZEROS
= Buffer
.alloc(128)
12691 function Hmac (alg
, key
) {
12692 Base
.call(this, 'digest')
12693 if (typeof key
=== 'string') {
12694 key
= Buffer
.from(key
)
12700 if (key
.length
> blocksize
) {
12702 } else if (key
.length
< blocksize
) {
12703 key
= Buffer
.concat([key
, ZEROS
], blocksize
)
12706 var ipad
= this._ipad
= Buffer
.allocUnsafe(blocksize
)
12707 var opad
= this._opad
= Buffer
.allocUnsafe(blocksize
)
12709 for (var i
= 0; i
< blocksize
; i
++) {
12710 ipad
[i
] = key
[i
] ^ 0x36
12711 opad
[i
] = key
[i
] ^ 0x5C
12714 this._hash
= [ipad
]
12717 inherits(Hmac
, Base
)
12719 Hmac
.prototype._update = function (data
) {
12720 this._hash
.push(data
)
12723 Hmac
.prototype._final = function () {
12724 var h
= this._alg(Buffer
.concat(this._hash
))
12725 return this._alg(Buffer
.concat([this._opad
, h
]))
12727 module
.exports
= Hmac
12729 },{"cipher-base":84,"inherits":96,"safe-buffer":101}],90:[function(require
,module
,exports
){
12730 var assert
= require('assert')
12731 var BigInteger
= require('bigi')
12733 var Point
= require('./point')
12735 function Curve (p
, a
, b
, Gx
, Gy
, n
, h
) {
12739 this.G
= Point
.fromAffine(this, Gx
, Gy
)
12743 this.infinity
= new Point(this, null, null, BigInteger
.ZERO
)
12746 this.pOverFour
= p
.add(BigInteger
.ONE
).shiftRight(2)
12748 // determine size of p in bytes
12749 this.pLength
= Math
.floor((this.p
.bitLength() + 7) / 8)
12752 Curve
.prototype.pointFromX = function (isOdd
, x
) {
12753 var alpha
= x
.pow(3).add(this.a
.multiply(x
)).add(this.b
).mod(this.p
)
12754 var beta
= alpha
.modPow(this.pOverFour
, this.p
) // XXX: not compatible with all curves
12757 if (beta
.isEven() ^ !isOdd
) {
12758 y
= this.p
.subtract(y
) // -y % p
12761 return Point
.fromAffine(this, x
, y
)
12764 Curve
.prototype.isInfinity = function (Q
) {
12765 if (Q
=== this.infinity
) return true
12767 return Q
.z
.signum() === 0 && Q
.y
.signum() !== 0
12770 Curve
.prototype.isOnCurve = function (Q
) {
12771 if (this.isInfinity(Q
)) return true
12779 // Check that xQ and yQ are integers in the interval [0, p - 1]
12780 if (x
.signum() < 0 || x
.compareTo(p
) >= 0) return false
12781 if (y
.signum() < 0 || y
.compareTo(p
) >= 0) return false
12783 // and check that y^2 = x^3 + ax + b (mod p)
12784 var lhs
= y
.square().mod(p
)
12785 var rhs
= x
.pow(3).add(a
.multiply(x
)).add(b
).mod(p
)
12786 return lhs
.equals(rhs
)
12790 * Validate an elliptic curve point.
12792 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
12794 Curve
.prototype.validate = function (Q
) {
12796 assert(!this.isInfinity(Q
), 'Point is at infinity')
12797 assert(this.isOnCurve(Q
), 'Point is not on the curve')
12799 // Check nQ = O (where Q is a scalar multiple of G)
12800 var nQ
= Q
.multiply(this.n
)
12801 assert(this.isInfinity(nQ
), 'Point is not a scalar multiple of G')
12806 module
.exports
= Curve
12808 },{"./point":94,"assert":1,"bigi":39}],91:[function(require
,module
,exports
){
12811 "p": "fffffffdffffffffffffffffffffffff",
12812 "a": "fffffffdfffffffffffffffffffffffc",
12813 "b": "e87579c11079f43dd824993c2cee5ed3",
12814 "n": "fffffffe0000000075a30d1b9038a115",
12816 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
12817 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
12820 "p": "fffffffffffffffffffffffffffffffeffffac73",
12823 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
12825 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
12826 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
12829 "p": "ffffffffffffffffffffffffffffffff7fffffff",
12830 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
12831 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
12832 "n": "0100000000000000000001f4c8f927aed3ca752257",
12834 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
12835 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
12838 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
12841 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
12843 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
12844 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
12847 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
12848 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
12849 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
12850 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
12852 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
12853 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
12856 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
12859 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
12861 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
12862 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
12865 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
12866 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
12867 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
12868 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
12870 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
12871 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
12875 },{}],92:[function(require
,module
,exports
){
12876 var Point
= require('./point')
12877 var Curve
= require('./curve')
12879 var getCurveByName
= require('./names')
12884 getCurveByName: getCurveByName
12887 },{"./curve":90,"./names":93,"./point":94}],93:[function(require
,module
,exports
){
12888 var BigInteger
= require('bigi')
12890 var curves
= require('./curves.json')
12891 var Curve
= require('./curve')
12893 function getCurveByName (name
) {
12894 var curve
= curves
[name
]
12895 if (!curve
) return null
12897 var p
= new BigInteger(curve
.p
, 16)
12898 var a
= new BigInteger(curve
.a
, 16)
12899 var b
= new BigInteger(curve
.b
, 16)
12900 var n
= new BigInteger(curve
.n
, 16)
12901 var h
= new BigInteger(curve
.h
, 16)
12902 var Gx
= new BigInteger(curve
.Gx
, 16)
12903 var Gy
= new BigInteger(curve
.Gy
, 16)
12905 return new Curve(p
, a
, b
, Gx
, Gy
, n
, h
)
12908 module
.exports
= getCurveByName
12910 },{"./curve":90,"./curves.json":91,"bigi":39}],94:[function(require
,module
,exports
){
12911 var assert
= require('assert')
12912 var Buffer
= require('safe-buffer').Buffer
12913 var BigInteger
= require('bigi')
12915 var THREE
= BigInteger
.valueOf(3)
12917 function Point (curve
, x
, y
, z
) {
12918 assert
.notStrictEqual(z
, undefined, 'Missing Z coordinate')
12926 this.compressed
= true
12929 Object
.defineProperty(Point
.prototype, 'zInv', {
12931 if (this._zInv
=== null) {
12932 this._zInv
= this.z
.modInverse(this.curve
.p
)
12939 Object
.defineProperty(Point
.prototype, 'affineX', {
12941 return this.x
.multiply(this.zInv
).mod(this.curve
.p
)
12945 Object
.defineProperty(Point
.prototype, 'affineY', {
12947 return this.y
.multiply(this.zInv
).mod(this.curve
.p
)
12951 Point
.fromAffine = function (curve
, x
, y
) {
12952 return new Point(curve
, x
, y
, BigInteger
.ONE
)
12955 Point
.prototype.equals = function (other
) {
12956 if (other
=== this) return true
12957 if (this.curve
.isInfinity(this)) return this.curve
.isInfinity(other
)
12958 if (this.curve
.isInfinity(other
)) return this.curve
.isInfinity(this)
12960 // u = Y2 * Z1 - Y1 * Z2
12961 var u
= other
.y
.multiply(this.z
).subtract(this.y
.multiply(other
.z
)).mod(this.curve
.p
)
12963 if (u
.signum() !== 0) return false
12965 // v = X2 * Z1 - X1 * Z2
12966 var v
= other
.x
.multiply(this.z
).subtract(this.x
.multiply(other
.z
)).mod(this.curve
.p
)
12968 return v
.signum() === 0
12971 Point
.prototype.negate = function () {
12972 var y
= this.curve
.p
.subtract(this.y
)
12974 return new Point(this.curve
, this.x
, y
, this.z
)
12977 Point
.prototype.add = function (b
) {
12978 if (this.curve
.isInfinity(this)) return b
12979 if (this.curve
.isInfinity(b
)) return this
12986 // u = Y2 * Z1 - Y1 * Z2
12987 var u
= y2
.multiply(this.z
).subtract(y1
.multiply(b
.z
)).mod(this.curve
.p
)
12988 // v = X2 * Z1 - X1 * Z2
12989 var v
= x2
.multiply(this.z
).subtract(x1
.multiply(b
.z
)).mod(this.curve
.p
)
12991 if (v
.signum() === 0) {
12992 if (u
.signum() === 0) {
12993 return this.twice() // this == b, so double
12996 return this.curve
.infinity
// this = -b, so infinity
12999 var v2
= v
.square()
13000 var v3
= v2
.multiply(v
)
13001 var x1v2
= x1
.multiply(v2
)
13002 var zu2
= u
.square().multiply(this.z
)
13004 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
13005 var x3
= zu2
.subtract(x1v2
.shiftLeft(1)).multiply(b
.z
).subtract(v3
).multiply(v
).mod(this.curve
.p
)
13006 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
13007 var y3
= x1v2
.multiply(THREE
).multiply(u
).subtract(y1
.multiply(v3
)).subtract(zu2
.multiply(u
)).multiply(b
.z
).add(u
.multiply(v3
)).mod(this.curve
.p
)
13008 // z3 = v^3 * z1 * z2
13009 var z3
= v3
.multiply(this.z
).multiply(b
.z
).mod(this.curve
.p
)
13011 return new Point(this.curve
, x3
, y3
, z3
)
13014 Point
.prototype.twice = function () {
13015 if (this.curve
.isInfinity(this)) return this
13016 if (this.y
.signum() === 0) return this.curve
.infinity
13021 var y1z1
= y1
.multiply(this.z
).mod(this.curve
.p
)
13022 var y1sqz1
= y1z1
.multiply(y1
).mod(this.curve
.p
)
13023 var a
= this.curve
.a
13025 // w = 3 * x1^2 + a * z1^2
13026 var w
= x1
.square().multiply(THREE
)
13028 if (a
.signum() !== 0) {
13029 w
= w
.add(this.z
.square().multiply(a
))
13032 w
= w
.mod(this.curve
.p
)
13033 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
13034 var x3
= w
.square().subtract(x1
.shiftLeft(3).multiply(y1sqz1
)).shiftLeft(1).multiply(y1z1
).mod(this.curve
.p
)
13035 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
13036 var y3
= w
.multiply(THREE
).multiply(x1
).subtract(y1sqz1
.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1
).subtract(w
.pow(3)).mod(this.curve
.p
)
13037 // z3 = 8 * (y1 * z1)^3
13038 var z3
= y1z1
.pow(3).shiftLeft(3).mod(this.curve
.p
)
13040 return new Point(this.curve
, x3
, y3
, z3
)
13043 // Simple NAF (Non-Adjacent Form) multiplication algorithm
13044 // TODO: modularize the multiplication algorithm
13045 Point
.prototype.multiply = function (k
) {
13046 if (this.curve
.isInfinity(this)) return this
13047 if (k
.signum() === 0) return this.curve
.infinity
13050 var h
= e
.multiply(THREE
)
13052 var neg
= this.negate()
13055 for (var i
= h
.bitLength() - 2; i
> 0; --i
) {
13056 var hBit
= h
.testBit(i
)
13057 var eBit
= e
.testBit(i
)
13061 if (hBit
!== eBit
) {
13062 R
= R
.add(hBit
? this : neg
)
13069 // Compute this*j + x*k (simultaneous multiplication)
13070 Point
.prototype.multiplyTwo = function (j
, x
, k
) {
13071 var i
= Math
.max(j
.bitLength(), k
.bitLength()) - 1
13072 var R
= this.curve
.infinity
13073 var both
= this.add(x
)
13076 var jBit
= j
.testBit(i
)
13077 var kBit
= k
.testBit(i
)
13096 Point
.prototype.getEncoded = function (compressed
) {
13097 if (compressed
== null) compressed
= this.compressed
13098 if (this.curve
.isInfinity(this)) return Buffer
.alloc(1, 0) // Infinity point encoded is simply '00'
13100 var x
= this.affineX
13101 var y
= this.affineY
13102 var byteLength
= this.curve
.pLength
13107 buffer
= Buffer
.allocUnsafe(1 + byteLength
)
13108 buffer
.writeUInt8(y
.isEven() ? 0x02 : 0x03, 0)
13112 buffer
= Buffer
.allocUnsafe(1 + byteLength
+ byteLength
)
13113 buffer
.writeUInt8(0x04, 0)
13115 y
.toBuffer(byteLength
).copy(buffer
, 1 + byteLength
)
13118 x
.toBuffer(byteLength
).copy(buffer
, 1)
13123 Point
.decodeFrom = function (curve
, buffer
) {
13124 var type
= buffer
.readUInt8(0)
13125 var compressed
= (type
!== 4)
13127 var byteLength
= Math
.floor((curve
.p
.bitLength() + 7) / 8)
13128 var x
= BigInteger
.fromBuffer(buffer
.slice(1, 1 + byteLength
))
13132 assert
.equal(buffer
.length
, byteLength
+ 1, 'Invalid sequence length')
13133 assert(type
=== 0x02 || type
=== 0x03, 'Invalid sequence tag')
13135 var isOdd
= (type
=== 0x03)
13136 Q
= curve
.pointFromX(isOdd
, x
)
13138 assert
.equal(buffer
.length
, 1 + byteLength
+ byteLength
, 'Invalid sequence length')
13140 var y
= BigInteger
.fromBuffer(buffer
.slice(1 + byteLength
))
13141 Q
= Point
.fromAffine(curve
, x
, y
)
13144 Q
.compressed
= compressed
13148 Point
.prototype.toString = function () {
13149 if (this.curve
.isInfinity(this)) return '(INFINITY)'
13151 return '(' + this.affineX
.toString() + ',' + this.affineY
.toString() + ')'
13154 module
.exports
= Point
13156 },{"assert":1,"bigi":39,"safe-buffer":101}],95:[function(require
,module
,exports
){
13157 (function (Buffer
){
13159 var Transform
= require('stream').Transform
13160 var inherits
= require('inherits')
13162 function HashBase (blockSize
) {
13163 Transform
.call(this)
13165 this._block
= new Buffer(blockSize
)
13166 this._blockSize
= blockSize
13167 this._blockOffset
= 0
13168 this._length
= [0, 0, 0, 0]
13170 this._finalized
= false
13173 inherits(HashBase
, Transform
)
13175 HashBase
.prototype._transform = function (chunk
, encoding
, callback
) {
13178 if (encoding
!== 'buffer') chunk
= new Buffer(chunk
, encoding
)
13187 HashBase
.prototype._flush = function (callback
) {
13190 this.push(this._digest())
13198 HashBase
.prototype.update = function (data
, encoding
) {
13199 if (!Buffer
.isBuffer(data
) && typeof data
!== 'string') throw new TypeError('Data must be a string or a buffer')
13200 if (this._finalized
) throw new Error('Digest already called')
13201 if (!Buffer
.isBuffer(data
)) data
= new Buffer(data
, encoding
|| 'binary')
13204 var block
= this._block
13206 while (this._blockOffset
+ data
.length
- offset
>= this._blockSize
) {
13207 for (var i
= this._blockOffset
; i
< this._blockSize
;) block
[i
++] = data
[offset
++]
13209 this._blockOffset
= 0
13211 while (offset
< data
.length
) block
[this._blockOffset
++] = data
[offset
++]
13214 for (var j
= 0, carry
= data
.length
* 8; carry
> 0; ++j
) {
13215 this._length
[j
] += carry
13216 carry
= (this._length
[j
] / 0x0100000000) | 0
13217 if (carry
> 0) this._length
[j
] -= 0x0100000000 * carry
13223 HashBase
.prototype._update = function (data
) {
13224 throw new Error('_update is not implemented')
13227 HashBase
.prototype.digest = function (encoding
) {
13228 if (this._finalized
) throw new Error('Digest already called')
13229 this._finalized
= true
13231 var digest
= this._digest()
13232 if (encoding
!== undefined) digest
= digest
.toString(encoding
)
13236 HashBase
.prototype._digest = function () {
13237 throw new Error('_digest is not implemented')
13240 module
.exports
= HashBase
13242 }).call(this,require("buffer").Buffer
)
13243 },{"buffer":5,"inherits":96,"stream":28}],96:[function(require
,module
,exports
){
13244 arguments
[4][9][0].apply(exports
,arguments
)
13245 },{"dup":9}],97:[function(require
,module
,exports
){
13246 (function (Buffer
){
13247 // constant-space merkle root calculation algorithm
13248 module
.exports
= function fastRoot (values
, digestFn
) {
13249 if (!Array
.isArray(values
)) throw TypeError('Expected values Array')
13250 if (typeof digestFn
!== 'function') throw TypeError('Expected digest Function')
13252 var length
= values
.length
13253 var results
= values
.concat()
13255 while (length
> 1) {
13258 for (var i
= 0; i
< length
; i
+= 2, ++j
) {
13259 var left
= results
[i
]
13260 var right
= i
+ 1 === length
? left : results
[i
+ 1]
13261 var data
= Buffer
.concat([left
, right
])
13263 results
[j
] = digestFn(data
)
13272 }).call(this,require("buffer").Buffer
)
13273 },{"buffer":5}],98:[function(require
,module
,exports
){
13274 var OPS
= require('bitcoin-ops')
13276 function encodingLength (i
) {
13277 return i
< OPS
.OP_PUSHDATA1
? 1
13283 function encode (buffer
, number
, offset
) {
13284 var size
= encodingLength(number
)
13288 buffer
.writeUInt8(number
, offset
)
13291 } else if (size
=== 2) {
13292 buffer
.writeUInt8(OPS
.OP_PUSHDATA1
, offset
)
13293 buffer
.writeUInt8(number
, offset
+ 1)
13296 } else if (size
=== 3) {
13297 buffer
.writeUInt8(OPS
.OP_PUSHDATA2
, offset
)
13298 buffer
.writeUInt16LE(number
, offset
+ 1)
13302 buffer
.writeUInt8(OPS
.OP_PUSHDATA4
, offset
)
13303 buffer
.writeUInt32LE(number
, offset
+ 1)
13309 function decode (buffer
, offset
) {
13310 var opcode
= buffer
.readUInt8(offset
)
13314 if (opcode
< OPS
.OP_PUSHDATA1
) {
13319 } else if (opcode
=== OPS
.OP_PUSHDATA1
) {
13320 if (offset
+ 2 > buffer
.length
) return null
13321 number
= buffer
.readUInt8(offset
+ 1)
13325 } else if (opcode
=== OPS
.OP_PUSHDATA2
) {
13326 if (offset
+ 3 > buffer
.length
) return null
13327 number
= buffer
.readUInt16LE(offset
+ 1)
13332 if (offset
+ 5 > buffer
.length
) return null
13333 if (opcode
!== OPS
.OP_PUSHDATA4
) throw new Error('Unexpected opcode')
13335 number
= buffer
.readUInt32LE(offset
+ 1)
13347 encodingLength: encodingLength
,
13352 },{"bitcoin-ops":42}],99:[function(require
,module
,exports
){
13353 (function (process
,global
){
13356 function oldBrowser () {
13357 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
13360 var Buffer
= require('safe-buffer').Buffer
13361 var crypto
= global
.crypto
|| global
.msCrypto
13363 if (crypto
&& crypto
.getRandomValues
) {
13364 module
.exports
= randomBytes
13366 module
.exports
= oldBrowser
13369 function randomBytes (size
, cb
) {
13370 // phantomjs needs to throw
13371 if (size
> 65536) throw new Error('requested too many random bytes')
13372 // in case browserify isn't using the Uint8Array version
13373 var rawBytes
= new global
.Uint8Array(size
)
13375 // This will not work in older browsers.
13376 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
13377 if (size
> 0) { // getRandomValues fails on IE if size == 0
13378 crypto
.getRandomValues(rawBytes
)
13381 // XXX: phantomjs doesn't like a buffer being passed here
13382 var bytes
= Buffer
.from(rawBytes
.buffer
)
13384 if (typeof cb
=== 'function') {
13385 return process
.nextTick(function () {
13393 }).call(this,require('_process'),typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
13394 },{"_process":13,"safe-buffer":101}],100:[function(require
,module
,exports
){
13395 (function (Buffer
){
13397 var inherits
= require('inherits')
13398 var HashBase
= require('hash-base')
13400 function RIPEMD160 () {
13401 HashBase
.call(this, 64)
13404 this._a
= 0x67452301
13405 this._b
= 0xefcdab89
13406 this._c
= 0x98badcfe
13407 this._d
= 0x10325476
13408 this._e
= 0xc3d2e1f0
13411 inherits(RIPEMD160
, HashBase
)
13413 RIPEMD160
.prototype._update = function () {
13414 var m
= new Array(16)
13415 for (var i
= 0; i
< 16; ++i
) m
[i
] = this._block
.readInt32LE(i
* 4)
13423 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
13425 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
13426 al
= fn1(al
, bl
, cl
, dl
, el
, m
[0], 0x00000000, 11); cl
= rotl(cl
, 10)
13427 el
= fn1(el
, al
, bl
, cl
, dl
, m
[1], 0x00000000, 14); bl
= rotl(bl
, 10)
13428 dl
= fn1(dl
, el
, al
, bl
, cl
, m
[2], 0x00000000, 15); al
= rotl(al
, 10)
13429 cl
= fn1(cl
, dl
, el
, al
, bl
, m
[3], 0x00000000, 12); el
= rotl(el
, 10)
13430 bl
= fn1(bl
, cl
, dl
, el
, al
, m
[4], 0x00000000, 5); dl
= rotl(dl
, 10)
13431 al
= fn1(al
, bl
, cl
, dl
, el
, m
[5], 0x00000000, 8); cl
= rotl(cl
, 10)
13432 el
= fn1(el
, al
, bl
, cl
, dl
, m
[6], 0x00000000, 7); bl
= rotl(bl
, 10)
13433 dl
= fn1(dl
, el
, al
, bl
, cl
, m
[7], 0x00000000, 9); al
= rotl(al
, 10)
13434 cl
= fn1(cl
, dl
, el
, al
, bl
, m
[8], 0x00000000, 11); el
= rotl(el
, 10)
13435 bl
= fn1(bl
, cl
, dl
, el
, al
, m
[9], 0x00000000, 13); dl
= rotl(dl
, 10)
13436 al
= fn1(al
, bl
, cl
, dl
, el
, m
[10], 0x00000000, 14); cl
= rotl(cl
, 10)
13437 el
= fn1(el
, al
, bl
, cl
, dl
, m
[11], 0x00000000, 15); bl
= rotl(bl
, 10)
13438 dl
= fn1(dl
, el
, al
, bl
, cl
, m
[12], 0x00000000, 6); al
= rotl(al
, 10)
13439 cl
= fn1(cl
, dl
, el
, al
, bl
, m
[13], 0x00000000, 7); el
= rotl(el
, 10)
13440 bl
= fn1(bl
, cl
, dl
, el
, al
, m
[14], 0x00000000, 9); dl
= rotl(dl
, 10)
13441 al
= fn1(al
, bl
, cl
, dl
, el
, m
[15], 0x00000000, 8); cl
= rotl(cl
, 10)
13443 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
13445 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
13446 el
= fn2(el
, al
, bl
, cl
, dl
, m
[7], 0x5a827999, 7); bl
= rotl(bl
, 10)
13447 dl
= fn2(dl
, el
, al
, bl
, cl
, m
[4], 0x5a827999, 6); al
= rotl(al
, 10)
13448 cl
= fn2(cl
, dl
, el
, al
, bl
, m
[13], 0x5a827999, 8); el
= rotl(el
, 10)
13449 bl
= fn2(bl
, cl
, dl
, el
, al
, m
[1], 0x5a827999, 13); dl
= rotl(dl
, 10)
13450 al
= fn2(al
, bl
, cl
, dl
, el
, m
[10], 0x5a827999, 11); cl
= rotl(cl
, 10)
13451 el
= fn2(el
, al
, bl
, cl
, dl
, m
[6], 0x5a827999, 9); bl
= rotl(bl
, 10)
13452 dl
= fn2(dl
, el
, al
, bl
, cl
, m
[15], 0x5a827999, 7); al
= rotl(al
, 10)
13453 cl
= fn2(cl
, dl
, el
, al
, bl
, m
[3], 0x5a827999, 15); el
= rotl(el
, 10)
13454 bl
= fn2(bl
, cl
, dl
, el
, al
, m
[12], 0x5a827999, 7); dl
= rotl(dl
, 10)
13455 al
= fn2(al
, bl
, cl
, dl
, el
, m
[0], 0x5a827999, 12); cl
= rotl(cl
, 10)
13456 el
= fn2(el
, al
, bl
, cl
, dl
, m
[9], 0x5a827999, 15); bl
= rotl(bl
, 10)
13457 dl
= fn2(dl
, el
, al
, bl
, cl
, m
[5], 0x5a827999, 9); al
= rotl(al
, 10)
13458 cl
= fn2(cl
, dl
, el
, al
, bl
, m
[2], 0x5a827999, 11); el
= rotl(el
, 10)
13459 bl
= fn2(bl
, cl
, dl
, el
, al
, m
[14], 0x5a827999, 7); dl
= rotl(dl
, 10)
13460 al
= fn2(al
, bl
, cl
, dl
, el
, m
[11], 0x5a827999, 13); cl
= rotl(cl
, 10)
13461 el
= fn2(el
, al
, bl
, cl
, dl
, m
[8], 0x5a827999, 12); bl
= rotl(bl
, 10)
13463 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
13465 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
13466 dl
= fn3(dl
, el
, al
, bl
, cl
, m
[3], 0x6ed9eba1, 11); al
= rotl(al
, 10)
13467 cl
= fn3(cl
, dl
, el
, al
, bl
, m
[10], 0x6ed9eba1, 13); el
= rotl(el
, 10)
13468 bl
= fn3(bl
, cl
, dl
, el
, al
, m
[14], 0x6ed9eba1, 6); dl
= rotl(dl
, 10)
13469 al
= fn3(al
, bl
, cl
, dl
, el
, m
[4], 0x6ed9eba1, 7); cl
= rotl(cl
, 10)
13470 el
= fn3(el
, al
, bl
, cl
, dl
, m
[9], 0x6ed9eba1, 14); bl
= rotl(bl
, 10)
13471 dl
= fn3(dl
, el
, al
, bl
, cl
, m
[15], 0x6ed9eba1, 9); al
= rotl(al
, 10)
13472 cl
= fn3(cl
, dl
, el
, al
, bl
, m
[8], 0x6ed9eba1, 13); el
= rotl(el
, 10)
13473 bl
= fn3(bl
, cl
, dl
, el
, al
, m
[1], 0x6ed9eba1, 15); dl
= rotl(dl
, 10)
13474 al
= fn3(al
, bl
, cl
, dl
, el
, m
[2], 0x6ed9eba1, 14); cl
= rotl(cl
, 10)
13475 el
= fn3(el
, al
, bl
, cl
, dl
, m
[7], 0x6ed9eba1, 8); bl
= rotl(bl
, 10)
13476 dl
= fn3(dl
, el
, al
, bl
, cl
, m
[0], 0x6ed9eba1, 13); al
= rotl(al
, 10)
13477 cl
= fn3(cl
, dl
, el
, al
, bl
, m
[6], 0x6ed9eba1, 6); el
= rotl(el
, 10)
13478 bl
= fn3(bl
, cl
, dl
, el
, al
, m
[13], 0x6ed9eba1, 5); dl
= rotl(dl
, 10)
13479 al
= fn3(al
, bl
, cl
, dl
, el
, m
[11], 0x6ed9eba1, 12); cl
= rotl(cl
, 10)
13480 el
= fn3(el
, al
, bl
, cl
, dl
, m
[5], 0x6ed9eba1, 7); bl
= rotl(bl
, 10)
13481 dl
= fn3(dl
, el
, al
, bl
, cl
, m
[12], 0x6ed9eba1, 5); al
= rotl(al
, 10)
13483 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
13485 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
13486 cl
= fn4(cl
, dl
, el
, al
, bl
, m
[1], 0x8f1bbcdc, 11); el
= rotl(el
, 10)
13487 bl
= fn4(bl
, cl
, dl
, el
, al
, m
[9], 0x8f1bbcdc, 12); dl
= rotl(dl
, 10)
13488 al
= fn4(al
, bl
, cl
, dl
, el
, m
[11], 0x8f1bbcdc, 14); cl
= rotl(cl
, 10)
13489 el
= fn4(el
, al
, bl
, cl
, dl
, m
[10], 0x8f1bbcdc, 15); bl
= rotl(bl
, 10)
13490 dl
= fn4(dl
, el
, al
, bl
, cl
, m
[0], 0x8f1bbcdc, 14); al
= rotl(al
, 10)
13491 cl
= fn4(cl
, dl
, el
, al
, bl
, m
[8], 0x8f1bbcdc, 15); el
= rotl(el
, 10)
13492 bl
= fn4(bl
, cl
, dl
, el
, al
, m
[12], 0x8f1bbcdc, 9); dl
= rotl(dl
, 10)
13493 al
= fn4(al
, bl
, cl
, dl
, el
, m
[4], 0x8f1bbcdc, 8); cl
= rotl(cl
, 10)
13494 el
= fn4(el
, al
, bl
, cl
, dl
, m
[13], 0x8f1bbcdc, 9); bl
= rotl(bl
, 10)
13495 dl
= fn4(dl
, el
, al
, bl
, cl
, m
[3], 0x8f1bbcdc, 14); al
= rotl(al
, 10)
13496 cl
= fn4(cl
, dl
, el
, al
, bl
, m
[7], 0x8f1bbcdc, 5); el
= rotl(el
, 10)
13497 bl
= fn4(bl
, cl
, dl
, el
, al
, m
[15], 0x8f1bbcdc, 6); dl
= rotl(dl
, 10)
13498 al
= fn4(al
, bl
, cl
, dl
, el
, m
[14], 0x8f1bbcdc, 8); cl
= rotl(cl
, 10)
13499 el
= fn4(el
, al
, bl
, cl
, dl
, m
[5], 0x8f1bbcdc, 6); bl
= rotl(bl
, 10)
13500 dl
= fn4(dl
, el
, al
, bl
, cl
, m
[6], 0x8f1bbcdc, 5); al
= rotl(al
, 10)
13501 cl
= fn4(cl
, dl
, el
, al
, bl
, m
[2], 0x8f1bbcdc, 12); el
= rotl(el
, 10)
13503 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
13505 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
13506 bl
= fn5(bl
, cl
, dl
, el
, al
, m
[4], 0xa953fd4e, 9); dl
= rotl(dl
, 10)
13507 al
= fn5(al
, bl
, cl
, dl
, el
, m
[0], 0xa953fd4e, 15); cl
= rotl(cl
, 10)
13508 el
= fn5(el
, al
, bl
, cl
, dl
, m
[5], 0xa953fd4e, 5); bl
= rotl(bl
, 10)
13509 dl
= fn5(dl
, el
, al
, bl
, cl
, m
[9], 0xa953fd4e, 11); al
= rotl(al
, 10)
13510 cl
= fn5(cl
, dl
, el
, al
, bl
, m
[7], 0xa953fd4e, 6); el
= rotl(el
, 10)
13511 bl
= fn5(bl
, cl
, dl
, el
, al
, m
[12], 0xa953fd4e, 8); dl
= rotl(dl
, 10)
13512 al
= fn5(al
, bl
, cl
, dl
, el
, m
[2], 0xa953fd4e, 13); cl
= rotl(cl
, 10)
13513 el
= fn5(el
, al
, bl
, cl
, dl
, m
[10], 0xa953fd4e, 12); bl
= rotl(bl
, 10)
13514 dl
= fn5(dl
, el
, al
, bl
, cl
, m
[14], 0xa953fd4e, 5); al
= rotl(al
, 10)
13515 cl
= fn5(cl
, dl
, el
, al
, bl
, m
[1], 0xa953fd4e, 12); el
= rotl(el
, 10)
13516 bl
= fn5(bl
, cl
, dl
, el
, al
, m
[3], 0xa953fd4e, 13); dl
= rotl(dl
, 10)
13517 al
= fn5(al
, bl
, cl
, dl
, el
, m
[8], 0xa953fd4e, 14); cl
= rotl(cl
, 10)
13518 el
= fn5(el
, al
, bl
, cl
, dl
, m
[11], 0xa953fd4e, 11); bl
= rotl(bl
, 10)
13519 dl
= fn5(dl
, el
, al
, bl
, cl
, m
[6], 0xa953fd4e, 8); al
= rotl(al
, 10)
13520 cl
= fn5(cl
, dl
, el
, al
, bl
, m
[15], 0xa953fd4e, 5); el
= rotl(el
, 10)
13521 bl
= fn5(bl
, cl
, dl
, el
, al
, m
[13], 0xa953fd4e, 6); dl
= rotl(dl
, 10)
13529 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
13531 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
13532 ar
= fn5(ar
, br
, cr
, dr
, er
, m
[5], 0x50a28be6, 8); cr
= rotl(cr
, 10)
13533 er
= fn5(er
, ar
, br
, cr
, dr
, m
[14], 0x50a28be6, 9); br
= rotl(br
, 10)
13534 dr
= fn5(dr
, er
, ar
, br
, cr
, m
[7], 0x50a28be6, 9); ar
= rotl(ar
, 10)
13535 cr
= fn5(cr
, dr
, er
, ar
, br
, m
[0], 0x50a28be6, 11); er
= rotl(er
, 10)
13536 br
= fn5(br
, cr
, dr
, er
, ar
, m
[9], 0x50a28be6, 13); dr
= rotl(dr
, 10)
13537 ar
= fn5(ar
, br
, cr
, dr
, er
, m
[2], 0x50a28be6, 15); cr
= rotl(cr
, 10)
13538 er
= fn5(er
, ar
, br
, cr
, dr
, m
[11], 0x50a28be6, 15); br
= rotl(br
, 10)
13539 dr
= fn5(dr
, er
, ar
, br
, cr
, m
[4], 0x50a28be6, 5); ar
= rotl(ar
, 10)
13540 cr
= fn5(cr
, dr
, er
, ar
, br
, m
[13], 0x50a28be6, 7); er
= rotl(er
, 10)
13541 br
= fn5(br
, cr
, dr
, er
, ar
, m
[6], 0x50a28be6, 7); dr
= rotl(dr
, 10)
13542 ar
= fn5(ar
, br
, cr
, dr
, er
, m
[15], 0x50a28be6, 8); cr
= rotl(cr
, 10)
13543 er
= fn5(er
, ar
, br
, cr
, dr
, m
[8], 0x50a28be6, 11); br
= rotl(br
, 10)
13544 dr
= fn5(dr
, er
, ar
, br
, cr
, m
[1], 0x50a28be6, 14); ar
= rotl(ar
, 10)
13545 cr
= fn5(cr
, dr
, er
, ar
, br
, m
[10], 0x50a28be6, 14); er
= rotl(er
, 10)
13546 br
= fn5(br
, cr
, dr
, er
, ar
, m
[3], 0x50a28be6, 12); dr
= rotl(dr
, 10)
13547 ar
= fn5(ar
, br
, cr
, dr
, er
, m
[12], 0x50a28be6, 6); cr
= rotl(cr
, 10)
13549 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
13551 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
13552 er
= fn4(er
, ar
, br
, cr
, dr
, m
[6], 0x5c4dd124, 9); br
= rotl(br
, 10)
13553 dr
= fn4(dr
, er
, ar
, br
, cr
, m
[11], 0x5c4dd124, 13); ar
= rotl(ar
, 10)
13554 cr
= fn4(cr
, dr
, er
, ar
, br
, m
[3], 0x5c4dd124, 15); er
= rotl(er
, 10)
13555 br
= fn4(br
, cr
, dr
, er
, ar
, m
[7], 0x5c4dd124, 7); dr
= rotl(dr
, 10)
13556 ar
= fn4(ar
, br
, cr
, dr
, er
, m
[0], 0x5c4dd124, 12); cr
= rotl(cr
, 10)
13557 er
= fn4(er
, ar
, br
, cr
, dr
, m
[13], 0x5c4dd124, 8); br
= rotl(br
, 10)
13558 dr
= fn4(dr
, er
, ar
, br
, cr
, m
[5], 0x5c4dd124, 9); ar
= rotl(ar
, 10)
13559 cr
= fn4(cr
, dr
, er
, ar
, br
, m
[10], 0x5c4dd124, 11); er
= rotl(er
, 10)
13560 br
= fn4(br
, cr
, dr
, er
, ar
, m
[14], 0x5c4dd124, 7); dr
= rotl(dr
, 10)
13561 ar
= fn4(ar
, br
, cr
, dr
, er
, m
[15], 0x5c4dd124, 7); cr
= rotl(cr
, 10)
13562 er
= fn4(er
, ar
, br
, cr
, dr
, m
[8], 0x5c4dd124, 12); br
= rotl(br
, 10)
13563 dr
= fn4(dr
, er
, ar
, br
, cr
, m
[12], 0x5c4dd124, 7); ar
= rotl(ar
, 10)
13564 cr
= fn4(cr
, dr
, er
, ar
, br
, m
[4], 0x5c4dd124, 6); er
= rotl(er
, 10)
13565 br
= fn4(br
, cr
, dr
, er
, ar
, m
[9], 0x5c4dd124, 15); dr
= rotl(dr
, 10)
13566 ar
= fn4(ar
, br
, cr
, dr
, er
, m
[1], 0x5c4dd124, 13); cr
= rotl(cr
, 10)
13567 er
= fn4(er
, ar
, br
, cr
, dr
, m
[2], 0x5c4dd124, 11); br
= rotl(br
, 10)
13569 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
13571 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
13572 dr
= fn3(dr
, er
, ar
, br
, cr
, m
[15], 0x6d703ef3, 9); ar
= rotl(ar
, 10)
13573 cr
= fn3(cr
, dr
, er
, ar
, br
, m
[5], 0x6d703ef3, 7); er
= rotl(er
, 10)
13574 br
= fn3(br
, cr
, dr
, er
, ar
, m
[1], 0x6d703ef3, 15); dr
= rotl(dr
, 10)
13575 ar
= fn3(ar
, br
, cr
, dr
, er
, m
[3], 0x6d703ef3, 11); cr
= rotl(cr
, 10)
13576 er
= fn3(er
, ar
, br
, cr
, dr
, m
[7], 0x6d703ef3, 8); br
= rotl(br
, 10)
13577 dr
= fn3(dr
, er
, ar
, br
, cr
, m
[14], 0x6d703ef3, 6); ar
= rotl(ar
, 10)
13578 cr
= fn3(cr
, dr
, er
, ar
, br
, m
[6], 0x6d703ef3, 6); er
= rotl(er
, 10)
13579 br
= fn3(br
, cr
, dr
, er
, ar
, m
[9], 0x6d703ef3, 14); dr
= rotl(dr
, 10)
13580 ar
= fn3(ar
, br
, cr
, dr
, er
, m
[11], 0x6d703ef3, 12); cr
= rotl(cr
, 10)
13581 er
= fn3(er
, ar
, br
, cr
, dr
, m
[8], 0x6d703ef3, 13); br
= rotl(br
, 10)
13582 dr
= fn3(dr
, er
, ar
, br
, cr
, m
[12], 0x6d703ef3, 5); ar
= rotl(ar
, 10)
13583 cr
= fn3(cr
, dr
, er
, ar
, br
, m
[2], 0x6d703ef3, 14); er
= rotl(er
, 10)
13584 br
= fn3(br
, cr
, dr
, er
, ar
, m
[10], 0x6d703ef3, 13); dr
= rotl(dr
, 10)
13585 ar
= fn3(ar
, br
, cr
, dr
, er
, m
[0], 0x6d703ef3, 13); cr
= rotl(cr
, 10)
13586 er
= fn3(er
, ar
, br
, cr
, dr
, m
[4], 0x6d703ef3, 7); br
= rotl(br
, 10)
13587 dr
= fn3(dr
, er
, ar
, br
, cr
, m
[13], 0x6d703ef3, 5); ar
= rotl(ar
, 10)
13589 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
13591 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
13592 cr
= fn2(cr
, dr
, er
, ar
, br
, m
[8], 0x7a6d76e9, 15); er
= rotl(er
, 10)
13593 br
= fn2(br
, cr
, dr
, er
, ar
, m
[6], 0x7a6d76e9, 5); dr
= rotl(dr
, 10)
13594 ar
= fn2(ar
, br
, cr
, dr
, er
, m
[4], 0x7a6d76e9, 8); cr
= rotl(cr
, 10)
13595 er
= fn2(er
, ar
, br
, cr
, dr
, m
[1], 0x7a6d76e9, 11); br
= rotl(br
, 10)
13596 dr
= fn2(dr
, er
, ar
, br
, cr
, m
[3], 0x7a6d76e9, 14); ar
= rotl(ar
, 10)
13597 cr
= fn2(cr
, dr
, er
, ar
, br
, m
[11], 0x7a6d76e9, 14); er
= rotl(er
, 10)
13598 br
= fn2(br
, cr
, dr
, er
, ar
, m
[15], 0x7a6d76e9, 6); dr
= rotl(dr
, 10)
13599 ar
= fn2(ar
, br
, cr
, dr
, er
, m
[0], 0x7a6d76e9, 14); cr
= rotl(cr
, 10)
13600 er
= fn2(er
, ar
, br
, cr
, dr
, m
[5], 0x7a6d76e9, 6); br
= rotl(br
, 10)
13601 dr
= fn2(dr
, er
, ar
, br
, cr
, m
[12], 0x7a6d76e9, 9); ar
= rotl(ar
, 10)
13602 cr
= fn2(cr
, dr
, er
, ar
, br
, m
[2], 0x7a6d76e9, 12); er
= rotl(er
, 10)
13603 br
= fn2(br
, cr
, dr
, er
, ar
, m
[13], 0x7a6d76e9, 9); dr
= rotl(dr
, 10)
13604 ar
= fn2(ar
, br
, cr
, dr
, er
, m
[9], 0x7a6d76e9, 12); cr
= rotl(cr
, 10)
13605 er
= fn2(er
, ar
, br
, cr
, dr
, m
[7], 0x7a6d76e9, 5); br
= rotl(br
, 10)
13606 dr
= fn2(dr
, er
, ar
, br
, cr
, m
[10], 0x7a6d76e9, 15); ar
= rotl(ar
, 10)
13607 cr
= fn2(cr
, dr
, er
, ar
, br
, m
[14], 0x7a6d76e9, 8); er
= rotl(er
, 10)
13609 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
13611 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
13612 br
= fn1(br
, cr
, dr
, er
, ar
, m
[12], 0x00000000, 8); dr
= rotl(dr
, 10)
13613 ar
= fn1(ar
, br
, cr
, dr
, er
, m
[15], 0x00000000, 5); cr
= rotl(cr
, 10)
13614 er
= fn1(er
, ar
, br
, cr
, dr
, m
[10], 0x00000000, 12); br
= rotl(br
, 10)
13615 dr
= fn1(dr
, er
, ar
, br
, cr
, m
[4], 0x00000000, 9); ar
= rotl(ar
, 10)
13616 cr
= fn1(cr
, dr
, er
, ar
, br
, m
[1], 0x00000000, 12); er
= rotl(er
, 10)
13617 br
= fn1(br
, cr
, dr
, er
, ar
, m
[5], 0x00000000, 5); dr
= rotl(dr
, 10)
13618 ar
= fn1(ar
, br
, cr
, dr
, er
, m
[8], 0x00000000, 14); cr
= rotl(cr
, 10)
13619 er
= fn1(er
, ar
, br
, cr
, dr
, m
[7], 0x00000000, 6); br
= rotl(br
, 10)
13620 dr
= fn1(dr
, er
, ar
, br
, cr
, m
[6], 0x00000000, 8); ar
= rotl(ar
, 10)
13621 cr
= fn1(cr
, dr
, er
, ar
, br
, m
[2], 0x00000000, 13); er
= rotl(er
, 10)
13622 br
= fn1(br
, cr
, dr
, er
, ar
, m
[13], 0x00000000, 6); dr
= rotl(dr
, 10)
13623 ar
= fn1(ar
, br
, cr
, dr
, er
, m
[14], 0x00000000, 5); cr
= rotl(cr
, 10)
13624 er
= fn1(er
, ar
, br
, cr
, dr
, m
[0], 0x00000000, 15); br
= rotl(br
, 10)
13625 dr
= fn1(dr
, er
, ar
, br
, cr
, m
[3], 0x00000000, 13); ar
= rotl(ar
, 10)
13626 cr
= fn1(cr
, dr
, er
, ar
, br
, m
[9], 0x00000000, 11); er
= rotl(er
, 10)
13627 br
= fn1(br
, cr
, dr
, er
, ar
, m
[11], 0x00000000, 11); dr
= rotl(dr
, 10)
13630 var t
= (this._b
+ cl
+ dr
) | 0
13631 this._b
= (this._c
+ dl
+ er
) | 0
13632 this._c
= (this._d
+ el
+ ar
) | 0
13633 this._d
= (this._e
+ al
+ br
) | 0
13634 this._e
= (this._a
+ bl
+ cr
) | 0
13638 RIPEMD160
.prototype._digest = function () {
13639 // create padding and handle blocks
13640 this._block
[this._blockOffset
++] = 0x80
13641 if (this._blockOffset
> 56) {
13642 this._block
.fill(0, this._blockOffset
, 64)
13644 this._blockOffset
= 0
13647 this._block
.fill(0, this._blockOffset
, 56)
13648 this._block
.writeUInt32LE(this._length
[0], 56)
13649 this._block
.writeUInt32LE(this._length
[1], 60)
13653 var buffer
= new Buffer(20)
13654 buffer
.writeInt32LE(this._a
, 0)
13655 buffer
.writeInt32LE(this._b
, 4)
13656 buffer
.writeInt32LE(this._c
, 8)
13657 buffer
.writeInt32LE(this._d
, 12)
13658 buffer
.writeInt32LE(this._e
, 16)
13662 function rotl (x
, n
) {
13663 return (x
<< n
) | (x
>>> (32 - n
))
13666 function fn1 (a
, b
, c
, d
, e
, m
, k
, s
) {
13667 return (rotl((a
+ (b
^ c
^ d
) + m
+ k
) | 0, s
) + e
) | 0
13670 function fn2 (a
, b
, c
, d
, e
, m
, k
, s
) {
13671 return (rotl((a
+ ((b
& c
) | ((~b
) & d
)) + m
+ k
) | 0, s
) + e
) | 0
13674 function fn3 (a
, b
, c
, d
, e
, m
, k
, s
) {
13675 return (rotl((a
+ ((b
| (~c
)) ^ d
) + m
+ k
) | 0, s
) + e
) | 0
13678 function fn4 (a
, b
, c
, d
, e
, m
, k
, s
) {
13679 return (rotl((a
+ ((b
& d
) | (c
& (~d
))) + m
+ k
) | 0, s
) + e
) | 0
13682 function fn5 (a
, b
, c
, d
, e
, m
, k
, s
) {
13683 return (rotl((a
+ (b
^ (c
| (~d
))) + m
+ k
) | 0, s
) + e
) | 0
13686 module
.exports
= RIPEMD160
13688 }).call(this,require("buffer").Buffer
)
13689 },{"buffer":5,"hash-base":95,"inherits":96}],101:[function(require
,module
,exports
){
13690 /* eslint-disable node/no-deprecated-api */
13691 var buffer
= require('buffer')
13692 var Buffer
= buffer
.Buffer
13694 // alternative to using Object.keys for old browsers
13695 function copyProps (src
, dst
) {
13696 for (var key
in src
) {
13697 dst
[key
] = src
[key
]
13700 if (Buffer
.from && Buffer
.alloc
&& Buffer
.allocUnsafe
&& Buffer
.allocUnsafeSlow
) {
13701 module
.exports
= buffer
13703 // Copy properties from require('buffer')
13704 copyProps(buffer
, exports
)
13705 exports
.Buffer
= SafeBuffer
13708 function SafeBuffer (arg
, encodingOrOffset
, length
) {
13709 return Buffer(arg
, encodingOrOffset
, length
)
13712 // Copy static methods from Buffer
13713 copyProps(Buffer
, SafeBuffer
)
13715 SafeBuffer
.from = function (arg
, encodingOrOffset
, length
) {
13716 if (typeof arg
=== 'number') {
13717 throw new TypeError('Argument must not be a number')
13719 return Buffer(arg
, encodingOrOffset
, length
)
13722 SafeBuffer
.alloc = function (size
, fill
, encoding
) {
13723 if (typeof size
!== 'number') {
13724 throw new TypeError('Argument must be a number')
13726 var buf
= Buffer(size
)
13727 if (fill
!== undefined) {
13728 if (typeof encoding
=== 'string') {
13729 buf
.fill(fill
, encoding
)
13739 SafeBuffer
.allocUnsafe = function (size
) {
13740 if (typeof size
!== 'number') {
13741 throw new TypeError('Argument must be a number')
13743 return Buffer(size
)
13746 SafeBuffer
.allocUnsafeSlow = function (size
) {
13747 if (typeof size
!== 'number') {
13748 throw new TypeError('Argument must be a number')
13750 return buffer
.SlowBuffer(size
)
13753 },{"buffer":5}],102:[function(require
,module
,exports
){
13754 var Buffer
= require('safe-buffer').Buffer
13756 // prototype class for hash functions
13757 function Hash (blockSize
, finalSize
) {
13758 this._block
= Buffer
.alloc(blockSize
)
13759 this._finalSize
= finalSize
13760 this._blockSize
= blockSize
13764 Hash
.prototype.update = function (data
, enc
) {
13765 if (typeof data
=== 'string') {
13766 enc
= enc
|| 'utf8'
13767 data
= Buffer
.from(data
, enc
)
13770 var block
= this._block
13771 var blockSize
= this._blockSize
13772 var length
= data
.length
13773 var accum
= this._len
13775 for (var offset
= 0; offset
< length
;) {
13776 var assigned
= accum
% blockSize
13777 var remainder
= Math
.min(length
- offset
, blockSize
- assigned
)
13779 for (var i
= 0; i
< remainder
; i
++) {
13780 block
[assigned
+ i
] = data
[offset
+ i
]
13784 offset
+= remainder
13786 if ((accum
% blockSize
) === 0) {
13787 this._update(block
)
13791 this._len
+= length
13795 Hash
.prototype.digest = function (enc
) {
13796 var rem
= this._len
% this._blockSize
13798 this._block
[rem
] = 0x80
13800 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
13801 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
13802 this._block
.fill(0, rem
+ 1)
13804 if (rem
>= this._finalSize
) {
13805 this._update(this._block
)
13806 this._block
.fill(0)
13809 var bits
= this._len
* 8
13812 if (bits
<= 0xffffffff) {
13813 this._block
.writeUInt32BE(bits
, this._blockSize
- 4)
13817 var lowBits
= (bits
& 0xffffffff) >>> 0
13818 var highBits
= (bits
- lowBits
) / 0x100000000
13820 this._block
.writeUInt32BE(highBits
, this._blockSize
- 8)
13821 this._block
.writeUInt32BE(lowBits
, this._blockSize
- 4)
13824 this._update(this._block
)
13825 var hash
= this._hash()
13827 return enc
? hash
.toString(enc
) : hash
13830 Hash
.prototype._update = function () {
13831 throw new Error('_update must be implemented by subclass')
13834 module
.exports
= Hash
13836 },{"safe-buffer":101}],103:[function(require
,module
,exports
){
13837 var exports
= module
.exports
= function SHA (algorithm
) {
13838 algorithm
= algorithm
.toLowerCase()
13840 var Algorithm
= exports
[algorithm
]
13841 if (!Algorithm
) throw new Error(algorithm
+ ' is not supported (we accept pull requests)')
13843 return new Algorithm()
13846 exports
.sha
= require('./sha')
13847 exports
.sha1
= require('./sha1')
13848 exports
.sha224
= require('./sha224')
13849 exports
.sha256
= require('./sha256')
13850 exports
.sha384
= require('./sha384')
13851 exports
.sha512
= require('./sha512')
13853 },{"./sha":104,"./sha1":105,"./sha224":106,"./sha256":107,"./sha384":108,"./sha512":109}],104:[function(require
,module
,exports
){
13855 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
13856 * in FIPS PUB 180-1
13857 * This source code is derived from sha1.js of the same repository.
13858 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
13859 * operation was added.
13862 var inherits
= require('inherits')
13863 var Hash
= require('./hash')
13864 var Buffer
= require('safe-buffer').Buffer
13867 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13870 var W
= new Array(80)
13876 Hash
.call(this, 64, 56)
13879 inherits(Sha
, Hash
)
13881 Sha
.prototype.init = function () {
13882 this._a
= 0x67452301
13883 this._b
= 0xefcdab89
13884 this._c
= 0x98badcfe
13885 this._d
= 0x10325476
13886 this._e
= 0xc3d2e1f0
13891 function rotl5 (num
) {
13892 return (num
<< 5) | (num
>>> 27)
13895 function rotl30 (num
) {
13896 return (num
<< 30) | (num
>>> 2)
13899 function ft (s
, b
, c
, d
) {
13900 if (s
=== 0) return (b
& c
) | ((~b
) & d
)
13901 if (s
=== 2) return (b
& c
) | (b
& d
) | (c
& d
)
13905 Sha
.prototype._update = function (M
) {
13908 var a
= this._a
| 0
13909 var b
= this._b
| 0
13910 var c
= this._c
| 0
13911 var d
= this._d
| 0
13912 var e
= this._e
| 0
13914 for (var i
= 0; i
< 16; ++i
) W
[i
] = M
.readInt32BE(i
* 4)
13915 for (; i
< 80; ++i
) W
[i
] = W
[i
- 3] ^ W
[i
- 8] ^ W
[i
- 14] ^ W
[i
- 16]
13917 for (var j
= 0; j
< 80; ++j
) {
13919 var t
= (rotl5(a
) + ft(s
, b
, c
, d
) + e
+ W
[j
] + K
[s
]) | 0
13928 this._a
= (a
+ this._a
) | 0
13929 this._b
= (b
+ this._b
) | 0
13930 this._c
= (c
+ this._c
) | 0
13931 this._d
= (d
+ this._d
) | 0
13932 this._e
= (e
+ this._e
) | 0
13935 Sha
.prototype._hash = function () {
13936 var H
= Buffer
.allocUnsafe(20)
13938 H
.writeInt32BE(this._a
| 0, 0)
13939 H
.writeInt32BE(this._b
| 0, 4)
13940 H
.writeInt32BE(this._c
| 0, 8)
13941 H
.writeInt32BE(this._d
| 0, 12)
13942 H
.writeInt32BE(this._e
| 0, 16)
13947 module
.exports
= Sha
13949 },{"./hash":102,"inherits":96,"safe-buffer":101}],105:[function(require
,module
,exports
){
13951 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
13952 * in FIPS PUB 180-1
13953 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
13954 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
13955 * Distributed under the BSD License
13956 * See http://pajhome.org.uk/crypt/md5 for details.
13959 var inherits
= require('inherits')
13960 var Hash
= require('./hash')
13961 var Buffer
= require('safe-buffer').Buffer
13964 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
13967 var W
= new Array(80)
13973 Hash
.call(this, 64, 56)
13976 inherits(Sha1
, Hash
)
13978 Sha1
.prototype.init = function () {
13979 this._a
= 0x67452301
13980 this._b
= 0xefcdab89
13981 this._c
= 0x98badcfe
13982 this._d
= 0x10325476
13983 this._e
= 0xc3d2e1f0
13988 function rotl1 (num
) {
13989 return (num
<< 1) | (num
>>> 31)
13992 function rotl5 (num
) {
13993 return (num
<< 5) | (num
>>> 27)
13996 function rotl30 (num
) {
13997 return (num
<< 30) | (num
>>> 2)
14000 function ft (s
, b
, c
, d
) {
14001 if (s
=== 0) return (b
& c
) | ((~b
) & d
)
14002 if (s
=== 2) return (b
& c
) | (b
& d
) | (c
& d
)
14006 Sha1
.prototype._update = function (M
) {
14009 var a
= this._a
| 0
14010 var b
= this._b
| 0
14011 var c
= this._c
| 0
14012 var d
= this._d
| 0
14013 var e
= this._e
| 0
14015 for (var i
= 0; i
< 16; ++i
) W
[i
] = M
.readInt32BE(i
* 4)
14016 for (; i
< 80; ++i
) W
[i
] = rotl1(W
[i
- 3] ^ W
[i
- 8] ^ W
[i
- 14] ^ W
[i
- 16])
14018 for (var j
= 0; j
< 80; ++j
) {
14020 var t
= (rotl5(a
) + ft(s
, b
, c
, d
) + e
+ W
[j
] + K
[s
]) | 0
14029 this._a
= (a
+ this._a
) | 0
14030 this._b
= (b
+ this._b
) | 0
14031 this._c
= (c
+ this._c
) | 0
14032 this._d
= (d
+ this._d
) | 0
14033 this._e
= (e
+ this._e
) | 0
14036 Sha1
.prototype._hash = function () {
14037 var H
= Buffer
.allocUnsafe(20)
14039 H
.writeInt32BE(this._a
| 0, 0)
14040 H
.writeInt32BE(this._b
| 0, 4)
14041 H
.writeInt32BE(this._c
| 0, 8)
14042 H
.writeInt32BE(this._d
| 0, 12)
14043 H
.writeInt32BE(this._e
| 0, 16)
14048 module
.exports
= Sha1
14050 },{"./hash":102,"inherits":96,"safe-buffer":101}],106:[function(require
,module
,exports
){
14052 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14054 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14055 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14059 var inherits
= require('inherits')
14060 var Sha256
= require('./sha256')
14061 var Hash
= require('./hash')
14062 var Buffer
= require('safe-buffer').Buffer
14064 var W
= new Array(64)
14066 function Sha224 () {
14069 this._w
= W
// new Array(64)
14071 Hash
.call(this, 64, 56)
14074 inherits(Sha224
, Sha256
)
14076 Sha224
.prototype.init = function () {
14077 this._a
= 0xc1059ed8
14078 this._b
= 0x367cd507
14079 this._c
= 0x3070dd17
14080 this._d
= 0xf70e5939
14081 this._e
= 0xffc00b31
14082 this._f
= 0x68581511
14083 this._g
= 0x64f98fa7
14084 this._h
= 0xbefa4fa4
14089 Sha224
.prototype._hash = function () {
14090 var H
= Buffer
.allocUnsafe(28)
14092 H
.writeInt32BE(this._a
, 0)
14093 H
.writeInt32BE(this._b
, 4)
14094 H
.writeInt32BE(this._c
, 8)
14095 H
.writeInt32BE(this._d
, 12)
14096 H
.writeInt32BE(this._e
, 16)
14097 H
.writeInt32BE(this._f
, 20)
14098 H
.writeInt32BE(this._g
, 24)
14103 module
.exports
= Sha224
14105 },{"./hash":102,"./sha256":107,"inherits":96,"safe-buffer":101}],107:[function(require
,module
,exports
){
14107 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
14109 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
14110 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
14114 var inherits
= require('inherits')
14115 var Hash
= require('./hash')
14116 var Buffer
= require('safe-buffer').Buffer
14119 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
14120 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
14121 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
14122 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
14123 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
14124 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
14125 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
14126 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
14127 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
14128 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
14129 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
14130 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
14131 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
14132 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
14133 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
14134 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
14137 var W
= new Array(64)
14139 function Sha256 () {
14142 this._w
= W
// new Array(64)
14144 Hash
.call(this, 64, 56)
14147 inherits(Sha256
, Hash
)
14149 Sha256
.prototype.init = function () {
14150 this._a
= 0x6a09e667
14151 this._b
= 0xbb67ae85
14152 this._c
= 0x3c6ef372
14153 this._d
= 0xa54ff53a
14154 this._e
= 0x510e527f
14155 this._f
= 0x9b05688c
14156 this._g
= 0x1f83d9ab
14157 this._h
= 0x5be0cd19
14162 function ch (x
, y
, z
) {
14163 return z
^ (x
& (y
^ z
))
14166 function maj (x
, y
, z
) {
14167 return (x
& y
) | (z
& (x
| y
))
14170 function sigma0 (x
) {
14171 return (x
>>> 2 | x
<< 30) ^ (x
>>> 13 | x
<< 19) ^ (x
>>> 22 | x
<< 10)
14174 function sigma1 (x
) {
14175 return (x
>>> 6 | x
<< 26) ^ (x
>>> 11 | x
<< 21) ^ (x
>>> 25 | x
<< 7)
14178 function gamma0 (x
) {
14179 return (x
>>> 7 | x
<< 25) ^ (x
>>> 18 | x
<< 14) ^ (x
>>> 3)
14182 function gamma1 (x
) {
14183 return (x
>>> 17 | x
<< 15) ^ (x
>>> 19 | x
<< 13) ^ (x
>>> 10)
14186 Sha256
.prototype._update = function (M
) {
14189 var a
= this._a
| 0
14190 var b
= this._b
| 0
14191 var c
= this._c
| 0
14192 var d
= this._d
| 0
14193 var e
= this._e
| 0
14194 var f
= this._f
| 0
14195 var g
= this._g
| 0
14196 var h
= this._h
| 0
14198 for (var i
= 0; i
< 16; ++i
) W
[i
] = M
.readInt32BE(i
* 4)
14199 for (; i
< 64; ++i
) W
[i
] = (gamma1(W
[i
- 2]) + W
[i
- 7] + gamma0(W
[i
- 15]) + W
[i
- 16]) | 0
14201 for (var j
= 0; j
< 64; ++j
) {
14202 var T1
= (h
+ sigma1(e
) + ch(e
, f
, g
) + K
[j
] + W
[j
]) | 0
14203 var T2
= (sigma0(a
) + maj(a
, b
, c
)) | 0
14215 this._a
= (a
+ this._a
) | 0
14216 this._b
= (b
+ this._b
) | 0
14217 this._c
= (c
+ this._c
) | 0
14218 this._d
= (d
+ this._d
) | 0
14219 this._e
= (e
+ this._e
) | 0
14220 this._f
= (f
+ this._f
) | 0
14221 this._g
= (g
+ this._g
) | 0
14222 this._h
= (h
+ this._h
) | 0
14225 Sha256
.prototype._hash = function () {
14226 var H
= Buffer
.allocUnsafe(32)
14228 H
.writeInt32BE(this._a
, 0)
14229 H
.writeInt32BE(this._b
, 4)
14230 H
.writeInt32BE(this._c
, 8)
14231 H
.writeInt32BE(this._d
, 12)
14232 H
.writeInt32BE(this._e
, 16)
14233 H
.writeInt32BE(this._f
, 20)
14234 H
.writeInt32BE(this._g
, 24)
14235 H
.writeInt32BE(this._h
, 28)
14240 module
.exports
= Sha256
14242 },{"./hash":102,"inherits":96,"safe-buffer":101}],108:[function(require
,module
,exports
){
14243 var inherits
= require('inherits')
14244 var SHA512
= require('./sha512')
14245 var Hash
= require('./hash')
14246 var Buffer
= require('safe-buffer').Buffer
14248 var W
= new Array(160)
14250 function Sha384 () {
14254 Hash
.call(this, 128, 112)
14257 inherits(Sha384
, SHA512
)
14259 Sha384
.prototype.init = function () {
14260 this._ah
= 0xcbbb9d5d
14261 this._bh
= 0x629a292a
14262 this._ch
= 0x9159015a
14263 this._dh
= 0x152fecd8
14264 this._eh
= 0x67332667
14265 this._fh
= 0x8eb44a87
14266 this._gh
= 0xdb0c2e0d
14267 this._hh
= 0x47b5481d
14269 this._al
= 0xc1059ed8
14270 this._bl
= 0x367cd507
14271 this._cl
= 0x3070dd17
14272 this._dl
= 0xf70e5939
14273 this._el
= 0xffc00b31
14274 this._fl
= 0x68581511
14275 this._gl
= 0x64f98fa7
14276 this._hl
= 0xbefa4fa4
14281 Sha384
.prototype._hash = function () {
14282 var H
= Buffer
.allocUnsafe(48)
14284 function writeInt64BE (h
, l
, offset
) {
14285 H
.writeInt32BE(h
, offset
)
14286 H
.writeInt32BE(l
, offset
+ 4)
14289 writeInt64BE(this._ah
, this._al
, 0)
14290 writeInt64BE(this._bh
, this._bl
, 8)
14291 writeInt64BE(this._ch
, this._cl
, 16)
14292 writeInt64BE(this._dh
, this._dl
, 24)
14293 writeInt64BE(this._eh
, this._el
, 32)
14294 writeInt64BE(this._fh
, this._fl
, 40)
14299 module
.exports
= Sha384
14301 },{"./hash":102,"./sha512":109,"inherits":96,"safe-buffer":101}],109:[function(require
,module
,exports
){
14302 var inherits
= require('inherits')
14303 var Hash
= require('./hash')
14304 var Buffer
= require('safe-buffer').Buffer
14307 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
14308 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
14309 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
14310 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
14311 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
14312 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
14313 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
14314 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
14315 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
14316 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
14317 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
14318 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
14319 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
14320 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
14321 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
14322 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
14323 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
14324 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
14325 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
14326 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
14327 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
14328 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
14329 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
14330 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
14331 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
14332 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
14333 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
14334 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
14335 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
14336 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
14337 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
14338 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
14339 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
14340 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
14341 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
14342 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
14343 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
14344 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
14345 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
14346 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
14349 var W
= new Array(160)
14351 function Sha512 () {
14355 Hash
.call(this, 128, 112)
14358 inherits(Sha512
, Hash
)
14360 Sha512
.prototype.init = function () {
14361 this._ah
= 0x6a09e667
14362 this._bh
= 0xbb67ae85
14363 this._ch
= 0x3c6ef372
14364 this._dh
= 0xa54ff53a
14365 this._eh
= 0x510e527f
14366 this._fh
= 0x9b05688c
14367 this._gh
= 0x1f83d9ab
14368 this._hh
= 0x5be0cd19
14370 this._al
= 0xf3bcc908
14371 this._bl
= 0x84caa73b
14372 this._cl
= 0xfe94f82b
14373 this._dl
= 0x5f1d36f1
14374 this._el
= 0xade682d1
14375 this._fl
= 0x2b3e6c1f
14376 this._gl
= 0xfb41bd6b
14377 this._hl
= 0x137e2179
14382 function Ch (x
, y
, z
) {
14383 return z
^ (x
& (y
^ z
))
14386 function maj (x
, y
, z
) {
14387 return (x
& y
) | (z
& (x
| y
))
14390 function sigma0 (x
, xl
) {
14391 return (x
>>> 28 | xl
<< 4) ^ (xl
>>> 2 | x
<< 30) ^ (xl
>>> 7 | x
<< 25)
14394 function sigma1 (x
, xl
) {
14395 return (x
>>> 14 | xl
<< 18) ^ (x
>>> 18 | xl
<< 14) ^ (xl
>>> 9 | x
<< 23)
14398 function Gamma0 (x
, xl
) {
14399 return (x
>>> 1 | xl
<< 31) ^ (x
>>> 8 | xl
<< 24) ^ (x
>>> 7)
14402 function Gamma0l (x
, xl
) {
14403 return (x
>>> 1 | xl
<< 31) ^ (x
>>> 8 | xl
<< 24) ^ (x
>>> 7 | xl
<< 25)
14406 function Gamma1 (x
, xl
) {
14407 return (x
>>> 19 | xl
<< 13) ^ (xl
>>> 29 | x
<< 3) ^ (x
>>> 6)
14410 function Gamma1l (x
, xl
) {
14411 return (x
>>> 19 | xl
<< 13) ^ (xl
>>> 29 | x
<< 3) ^ (x
>>> 6 | xl
<< 26)
14414 function getCarry (a
, b
) {
14415 return (a
>>> 0) < (b
>>> 0) ? 1 : 0
14418 Sha512
.prototype._update = function (M
) {
14421 var ah
= this._ah
| 0
14422 var bh
= this._bh
| 0
14423 var ch
= this._ch
| 0
14424 var dh
= this._dh
| 0
14425 var eh
= this._eh
| 0
14426 var fh
= this._fh
| 0
14427 var gh
= this._gh
| 0
14428 var hh
= this._hh
| 0
14430 var al
= this._al
| 0
14431 var bl
= this._bl
| 0
14432 var cl
= this._cl
| 0
14433 var dl
= this._dl
| 0
14434 var el
= this._el
| 0
14435 var fl
= this._fl
| 0
14436 var gl
= this._gl
| 0
14437 var hl
= this._hl
| 0
14439 for (var i
= 0; i
< 32; i
+= 2) {
14440 W
[i
] = M
.readInt32BE(i
* 4)
14441 W
[i
+ 1] = M
.readInt32BE(i
* 4 + 4)
14443 for (; i
< 160; i
+= 2) {
14444 var xh
= W
[i
- 15 * 2]
14445 var xl
= W
[i
- 15 * 2 + 1]
14446 var gamma0
= Gamma0(xh
, xl
)
14447 var gamma0l
= Gamma0l(xl
, xh
)
14450 xl
= W
[i
- 2 * 2 + 1]
14451 var gamma1
= Gamma1(xh
, xl
)
14452 var gamma1l
= Gamma1l(xl
, xh
)
14454 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
14455 var Wi7h
= W
[i
- 7 * 2]
14456 var Wi7l
= W
[i
- 7 * 2 + 1]
14458 var Wi16h
= W
[i
- 16 * 2]
14459 var Wi16l
= W
[i
- 16 * 2 + 1]
14461 var Wil
= (gamma0l
+ Wi7l
) | 0
14462 var Wih
= (gamma0
+ Wi7h
+ getCarry(Wil
, gamma0l
)) | 0
14463 Wil
= (Wil
+ gamma1l
) | 0
14464 Wih
= (Wih
+ gamma1
+ getCarry(Wil
, gamma1l
)) | 0
14465 Wil
= (Wil
+ Wi16l
) | 0
14466 Wih
= (Wih
+ Wi16h
+ getCarry(Wil
, Wi16l
)) | 0
14472 for (var j
= 0; j
< 160; j
+= 2) {
14476 var majh
= maj(ah
, bh
, ch
)
14477 var majl
= maj(al
, bl
, cl
)
14479 var sigma0h
= sigma0(ah
, al
)
14480 var sigma0l
= sigma0(al
, ah
)
14481 var sigma1h
= sigma1(eh
, el
)
14482 var sigma1l
= sigma1(el
, eh
)
14484 // t1 = h + sigma1 + ch + K[j] + W[j]
14488 var chh
= Ch(eh
, fh
, gh
)
14489 var chl
= Ch(el
, fl
, gl
)
14491 var t1l
= (hl
+ sigma1l
) | 0
14492 var t1h
= (hh
+ sigma1h
+ getCarry(t1l
, hl
)) | 0
14493 t1l
= (t1l
+ chl
) | 0
14494 t1h
= (t1h
+ chh
+ getCarry(t1l
, chl
)) | 0
14495 t1l
= (t1l
+ Kil
) | 0
14496 t1h
= (t1h
+ Kih
+ getCarry(t1l
, Kil
)) | 0
14497 t1l
= (t1l
+ Wil
) | 0
14498 t1h
= (t1h
+ Wih
+ getCarry(t1l
, Wil
)) | 0
14500 // t2 = sigma0 + maj
14501 var t2l
= (sigma0l
+ majl
) | 0
14502 var t2h
= (sigma0h
+ majh
+ getCarry(t2l
, sigma0l
)) | 0
14510 el
= (dl
+ t1l
) | 0
14511 eh
= (dh
+ t1h
+ getCarry(el
, dl
)) | 0
14518 al
= (t1l
+ t2l
) | 0
14519 ah
= (t1h
+ t2h
+ getCarry(al
, t1l
)) | 0
14522 this._al
= (this._al
+ al
) | 0
14523 this._bl
= (this._bl
+ bl
) | 0
14524 this._cl
= (this._cl
+ cl
) | 0
14525 this._dl
= (this._dl
+ dl
) | 0
14526 this._el
= (this._el
+ el
) | 0
14527 this._fl
= (this._fl
+ fl
) | 0
14528 this._gl
= (this._gl
+ gl
) | 0
14529 this._hl
= (this._hl
+ hl
) | 0
14531 this._ah
= (this._ah
+ ah
+ getCarry(this._al
, al
)) | 0
14532 this._bh
= (this._bh
+ bh
+ getCarry(this._bl
, bl
)) | 0
14533 this._ch
= (this._ch
+ ch
+ getCarry(this._cl
, cl
)) | 0
14534 this._dh
= (this._dh
+ dh
+ getCarry(this._dl
, dl
)) | 0
14535 this._eh
= (this._eh
+ eh
+ getCarry(this._el
, el
)) | 0
14536 this._fh
= (this._fh
+ fh
+ getCarry(this._fl
, fl
)) | 0
14537 this._gh
= (this._gh
+ gh
+ getCarry(this._gl
, gl
)) | 0
14538 this._hh
= (this._hh
+ hh
+ getCarry(this._hl
, hl
)) | 0
14541 Sha512
.prototype._hash = function () {
14542 var H
= Buffer
.allocUnsafe(64)
14544 function writeInt64BE (h
, l
, offset
) {
14545 H
.writeInt32BE(h
, offset
)
14546 H
.writeInt32BE(l
, offset
+ 4)
14549 writeInt64BE(this._ah
, this._al
, 0)
14550 writeInt64BE(this._bh
, this._bl
, 8)
14551 writeInt64BE(this._ch
, this._cl
, 16)
14552 writeInt64BE(this._dh
, this._dl
, 24)
14553 writeInt64BE(this._eh
, this._el
, 32)
14554 writeInt64BE(this._fh
, this._fl
, 40)
14555 writeInt64BE(this._gh
, this._gl
, 48)
14556 writeInt64BE(this._hh
, this._hl
, 56)
14561 module
.exports
= Sha512
14563 },{"./hash":102,"inherits":96,"safe-buffer":101}],110:[function(require
,module
,exports
){
14564 var native = require('./native')
14566 function getTypeName (fn
) {
14567 return fn
.name
|| fn
.toString().match(/function (.*?)\s
*\(/)[1]
14570 function getValueTypeName (value
) {
14571 return native.Nil(value
) ? '' : getTypeName(value
.constructor)
14574 function getValue (value
) {
14575 if (native.Function(value
)) return ''
14576 if (native.String(value
)) return JSON
.stringify(value
)
14577 if (value
&& native.Object(value
)) return ''
14581 function tfJSON (type
) {
14582 if (native.Function(type
)) return type
.toJSON
? type
.toJSON() : getTypeName(type
)
14583 if (native.Array(type
)) return 'Array'
14584 if (type
&& native.Object(type
)) return 'Object'
14586 return type
!== undefined ? type : ''
14589 function tfErrorString (type
, value
, valueTypeName
) {
14590 var valueJson
= getValue(value
)
14592 return 'Expected ' + tfJSON(type
) + ', got' +
14593 (valueTypeName
!== '' ? ' ' + valueTypeName : '') +
14594 (valueJson
!== '' ? ' ' + valueJson : '')
14597 function TfTypeError (type
, value
, valueTypeName
) {
14598 valueTypeName
= valueTypeName
|| getValueTypeName(value
)
14599 this.message
= tfErrorString(type
, value
, valueTypeName
)
14601 Error
.captureStackTrace(this, TfTypeError
)
14603 this.__value
= value
14604 this.__valueTypeName
= valueTypeName
14607 TfTypeError
.prototype = Object
.create(Error
.prototype)
14608 TfTypeError
.prototype.constructor = TfTypeError
14610 function tfPropertyErrorString (type
, label
, name
, value
, valueTypeName
) {
14611 var description
= '" of type '
14612 if (label
=== 'key') description
= '" with key type '
14614 return tfErrorString('property "' + tfJSON(name
) + description
+ tfJSON(type
), value
, valueTypeName
)
14617 function TfPropertyTypeError (type
, property
, label
, value
, valueTypeName
) {
14619 valueTypeName
= valueTypeName
|| getValueTypeName(value
)
14620 this.message
= tfPropertyErrorString(type
, label
, property
, value
, valueTypeName
)
14622 this.message
= 'Unexpected property "' + property
+ '"'
14625 Error
.captureStackTrace(this, TfTypeError
)
14626 this.__label
= label
14627 this.__property
= property
14629 this.__value
= value
14630 this.__valueTypeName
= valueTypeName
14633 TfPropertyTypeError
.prototype = Object
.create(Error
.prototype)
14634 TfPropertyTypeError
.prototype.constructor = TfTypeError
14636 function tfCustomError (expected
, actual
) {
14637 return new TfTypeError(expected
, {}, actual
)
14640 function tfSubError (e
, property
, label
) {
14642 if (e
instanceof TfPropertyTypeError
) {
14643 property
= property
+ '.' + e
.__property
14645 e
= new TfPropertyTypeError(
14646 e
.__type
, property
, e
.__label
, e
.__value
, e
.__valueTypeName
14650 } else if (e
instanceof TfTypeError
) {
14651 e
= new TfPropertyTypeError(
14652 e
.__type
, property
, label
, e
.__value
, e
.__valueTypeName
14656 Error
.captureStackTrace(e
)
14661 TfTypeError: TfTypeError
,
14662 TfPropertyTypeError: TfPropertyTypeError
,
14663 tfCustomError: tfCustomError
,
14664 tfSubError: tfSubError
,
14666 getValueTypeName: getValueTypeName
14669 },{"./native":113}],111:[function(require
,module
,exports
){
14670 (function (Buffer
){
14671 var NATIVE
= require('./native')
14672 var ERRORS
= require('./errors')
14674 function _Buffer (value
) {
14675 return Buffer
.isBuffer(value
)
14678 function Hex (value
) {
14679 return typeof value
=== 'string' && /^([0-9a-f]{2})+$/i.test(value
)
14682 function _LengthN (type
, length
) {
14683 var name
= type
.toJSON()
14685 function Length (value
) {
14686 if (!type(value
)) return false
14687 if (value
.length
=== length
) return true
14689 throw ERRORS
.tfCustomError(name
+ '(Length: ' + length
+ ')', name
+ '(Length: ' + value
.length
+ ')')
14691 Length
.toJSON = function () { return name
}
14696 var _ArrayN
= _LengthN
.bind(null, NATIVE
.Array
)
14697 var _BufferN
= _LengthN
.bind(null, _Buffer
)
14698 var _HexN
= _LengthN
.bind(null, Hex
)
14699 var _StringN
= _LengthN
.bind(null, NATIVE
.String
)
14701 var UINT53_MAX
= Math
.pow(2, 53) - 1
14703 function Finite (value
) {
14704 return typeof value
=== 'number' && isFinite(value
)
14706 function Int8 (value
) { return ((value
<< 24) >> 24) === value
}
14707 function Int16 (value
) { return ((value
<< 16) >> 16) === value
}
14708 function Int32 (value
) { return (value
| 0) === value
}
14709 function UInt8 (value
) { return (value
& 0xff) === value
}
14710 function UInt16 (value
) { return (value
& 0xffff) === value
}
14711 function UInt32 (value
) { return (value
>>> 0) === value
}
14712 function UInt53 (value
) {
14713 return typeof value
=== 'number' &&
14715 value
<= UINT53_MAX
&&
14716 Math
.floor(value
) === value
14736 for (var typeName
in types
) {
14737 types
[typeName
].toJSON = function (t
) {
14739 }.bind(null, typeName
)
14742 module
.exports
= types
14744 }).call(this,{"isBuffer":require("../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
14745 },{"../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":10,"./errors":110,"./native":113}],112:[function(require
,module
,exports
){
14746 var ERRORS
= require('./errors')
14747 var NATIVE
= require('./native')
14750 var tfJSON
= ERRORS
.tfJSON
14751 var TfTypeError
= ERRORS
.TfTypeError
14752 var TfPropertyTypeError
= ERRORS
.TfPropertyTypeError
14753 var tfSubError
= ERRORS
.tfSubError
14754 var getValueTypeName
= ERRORS
.getValueTypeName
14757 arrayOf: function arrayOf (type
) {
14758 type
= compile(type
)
14760 function _arrayOf (array
, strict
) {
14761 if (!NATIVE
.Array(array
)) return false
14762 if (NATIVE
.Nil(array
)) return false
14764 return array
.every(function (value
, i
) {
14766 return typeforce(type
, value
, strict
)
14768 throw tfSubError(e
, i
)
14772 _arrayOf
.toJSON = function () { return '[' + tfJSON(type
) + ']' }
14777 maybe: function maybe (type
) {
14778 type
= compile(type
)
14780 function _maybe (value
, strict
) {
14781 return NATIVE
.Nil(value
) || type(value
, strict
, maybe
)
14783 _maybe
.toJSON = function () { return '?' + tfJSON(type
) }
14788 map: function map (propertyType
, propertyKeyType
) {
14789 propertyType
= compile(propertyType
)
14790 if (propertyKeyType
) propertyKeyType
= compile(propertyKeyType
)
14792 function _map (value
, strict
) {
14793 if (!NATIVE
.Object(value
)) return false
14794 if (NATIVE
.Nil(value
)) return false
14796 for (var propertyName
in value
) {
14798 if (propertyKeyType
) {
14799 typeforce(propertyKeyType
, propertyName
, strict
)
14802 throw tfSubError(e
, propertyName
, 'key')
14806 var propertyValue
= value
[propertyName
]
14807 typeforce(propertyType
, propertyValue
, strict
)
14809 throw tfSubError(e
, propertyName
)
14816 if (propertyKeyType
) {
14817 _map
.toJSON = function () {
14818 return '{' + tfJSON(propertyKeyType
) + ': ' + tfJSON(propertyType
) + '}'
14821 _map
.toJSON = function () { return '{' + tfJSON(propertyType
) + '}' }
14827 object: function object (uncompiled
) {
14830 for (var typePropertyName
in uncompiled
) {
14831 type
[typePropertyName
] = compile(uncompiled
[typePropertyName
])
14834 function _object (value
, strict
) {
14835 if (!NATIVE
.Object(value
)) return false
14836 if (NATIVE
.Nil(value
)) return false
14841 for (propertyName
in type
) {
14842 var propertyType
= type
[propertyName
]
14843 var propertyValue
= value
[propertyName
]
14845 typeforce(propertyType
, propertyValue
, strict
)
14848 throw tfSubError(e
, propertyName
)
14852 for (propertyName
in value
) {
14853 if (type
[propertyName
]) continue
14855 throw new TfPropertyTypeError(undefined, propertyName
)
14861 _object
.toJSON = function () { return tfJSON(type
) }
14866 oneOf: function oneOf () {
14867 var types
= [].slice
.call(arguments
).map(compile
)
14869 function _oneOf (value
, strict
) {
14870 return types
.some(function (type
) {
14872 return typeforce(type
, value
, strict
)
14878 _oneOf
.toJSON = function () { return types
.map(tfJSON
).join('|') }
14883 quacksLike: function quacksLike (type
) {
14884 function _quacksLike (value
) {
14885 return type
=== getValueTypeName(value
)
14887 _quacksLike
.toJSON = function () { return type
}
14892 tuple: function tuple () {
14893 var types
= [].slice
.call(arguments
).map(compile
)
14895 function _tuple (values
, strict
) {
14896 if (NATIVE
.Nil(values
)) return false
14897 if (NATIVE
.Nil(values
.length
)) return false
14898 if (strict
&& (values
.length
!== types
.length
)) return false
14900 return types
.every(function (type
, i
) {
14902 return typeforce(type
, values
[i
], strict
)
14904 throw tfSubError(e
, i
)
14908 _tuple
.toJSON = function () { return '(' + types
.map(tfJSON
).join(', ') + ')' }
14913 value: function value (expected
) {
14914 function _value (actual
) {
14915 return actual
=== expected
14917 _value
.toJSON = function () { return expected
}
14923 function compile (type
) {
14924 if (NATIVE
.String(type
)) {
14925 if (type
[0] === '?') return TYPES
.maybe(type
.slice(1))
14927 return NATIVE
[type
] || TYPES
.quacksLike(type
)
14928 } else if (type
&& NATIVE
.Object(type
)) {
14929 if (NATIVE
.Array(type
)) return TYPES
.arrayOf(type
[0])
14931 return TYPES
.object(type
)
14932 } else if (NATIVE
.Function(type
)) {
14936 return TYPES
.value(type
)
14939 function typeforce (type
, value
, strict
, surrogate
) {
14940 if (NATIVE
.Function(type
)) {
14941 if (type(value
, strict
)) return true
14943 throw new TfTypeError(surrogate
|| type
, value
)
14947 return typeforce(compile(type
), value
, strict
)
14950 // assign types to typeforce function
14951 for (var typeName
in NATIVE
) {
14952 typeforce
[typeName
] = NATIVE
[typeName
]
14955 for (typeName
in TYPES
) {
14956 typeforce
[typeName
] = TYPES
[typeName
]
14959 var EXTRA
= require('./extra')
14960 for (typeName
in EXTRA
) {
14961 typeforce
[typeName
] = EXTRA
[typeName
]
14965 function __async (type
, value
, strict
, callback
) {
14966 // default to falsy strict if using shorthand overload
14967 if (typeof strict
=== 'function') return __async(type
, value
, false, strict
)
14970 typeforce(type
, value
, strict
)
14978 typeforce
.async
= __async
14979 typeforce
.compile
= compile
14980 typeforce
.TfTypeError
= TfTypeError
14981 typeforce
.TfPropertyTypeError
= TfPropertyTypeError
14983 module
.exports
= typeforce
14985 },{"./errors":110,"./extra":111,"./native":113}],113:[function(require
,module
,exports
){
14987 Array: function (value
) { return value
!== null && value
!== undefined && value
.constructor === Array
},
14988 Boolean: function (value
) { return typeof value
=== 'boolean' },
14989 Function: function (value
) { return typeof value
=== 'function' },
14990 Nil: function (value
) { return value
=== undefined || value
=== null },
14991 Number: function (value
) { return typeof value
=== 'number' },
14992 Object: function (value
) { return typeof value
=== 'object' },
14993 String: function (value
) { return typeof value
=== 'string' },
14994 '': function () { return true }
14998 types
.Null
= types
.Nil
15000 for (var typeName
in types
) {
15001 types
[typeName
].toJSON = function (t
) {
15003 }.bind(null, typeName
)
15006 module
.exports
= types
15008 },{}],114:[function(require
,module
,exports
){
15010 var Buffer
= require('safe-buffer').Buffer
15012 // Number.MAX_SAFE_INTEGER
15013 var MAX_SAFE_INTEGER
= 9007199254740991
15015 function checkUInt53 (n
) {
15016 if (n
< 0 || n
> MAX_SAFE_INTEGER
|| n
% 1 !== 0) throw new RangeError('value out of range')
15019 function encode (number
, buffer
, offset
) {
15020 checkUInt53(number
)
15022 if (!buffer
) buffer
= Buffer
.allocUnsafe(encodingLength(number
))
15023 if (!Buffer
.isBuffer(buffer
)) throw new TypeError('buffer must be a Buffer instance')
15024 if (!offset
) offset
= 0
15027 if (number
< 0xfd) {
15028 buffer
.writeUInt8(number
, offset
)
15032 } else if (number
<= 0xffff) {
15033 buffer
.writeUInt8(0xfd, offset
)
15034 buffer
.writeUInt16LE(number
, offset
+ 1)
15038 } else if (number
<= 0xffffffff) {
15039 buffer
.writeUInt8(0xfe, offset
)
15040 buffer
.writeUInt32LE(number
, offset
+ 1)
15045 buffer
.writeUInt8(0xff, offset
)
15046 buffer
.writeUInt32LE(number
>>> 0, offset
+ 1)
15047 buffer
.writeUInt32LE((number
/ 0x100000000) | 0, offset
+ 5)
15054 function decode (buffer
, offset
) {
15055 if (!Buffer
.isBuffer(buffer
)) throw new TypeError('buffer must be a Buffer instance')
15056 if (!offset
) offset
= 0
15058 var first
= buffer
.readUInt8(offset
)
15061 if (first
< 0xfd) {
15066 } else if (first
=== 0xfd) {
15068 return buffer
.readUInt16LE(offset
+ 1)
15071 } else if (first
=== 0xfe) {
15073 return buffer
.readUInt32LE(offset
+ 1)
15078 var lo
= buffer
.readUInt32LE(offset
+ 1)
15079 var hi
= buffer
.readUInt32LE(offset
+ 5)
15080 var number
= hi
* 0x0100000000 + lo
15081 checkUInt53(number
)
15087 function encodingLength (number
) {
15088 checkUInt53(number
)
15092 : number
<= 0xffff ? 3
15093 : number
<= 0xffffffff ? 5
15098 module
.exports
= { encode: encode
, decode: decode
, encodingLength: encodingLength
}
15100 },{"safe-buffer":101}],115:[function(require
,module
,exports
){
15101 (function (Buffer
){
15102 var bs58check
= require('bs58check')
15104 function decodeRaw (buffer
, version
) {
15105 // check version only if defined
15106 if (version
!== undefined && buffer
[0] !== version
) throw new Error('Invalid network version')
15109 if (buffer
.length
=== 33) {
15111 version: buffer
[0],
15112 privateKey: buffer
.slice(1, 33),
15118 if (buffer
.length
!== 34) throw new Error('Invalid WIF length')
15120 // invalid compression flag
15121 if (buffer
[33] !== 0x01) throw new Error('Invalid compression flag')
15124 version: buffer
[0],
15125 privateKey: buffer
.slice(1, 33),
15130 function encodeRaw (version
, privateKey
, compressed
) {
15131 var result
= new Buffer(compressed
? 34 : 33)
15133 result
.writeUInt8(version
, 0)
15134 privateKey
.copy(result
, 1)
15143 function decode (string
, version
) {
15144 return decodeRaw(bs58check
.decode(string
), version
)
15147 function encode (version
, privateKey
, compressed
) {
15148 if (typeof version
=== 'number') return bs58check
.encode(encodeRaw(version
, privateKey
, compressed
))
15150 return bs58check
.encode(
15153 version
.privateKey
,
15161 decodeRaw: decodeRaw
,
15163 encodeRaw: encodeRaw
15166 }).call(this,require("buffer").Buffer
)
15167 },{"bs58check":83,"buffer":5}]},{},[34])(34)